source: trunk/src/proj_field.m @ 517

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

various bugs corrected. get_field now used in a passive way from uvmat: variable names are transferred from get_field to uvmat.

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