source: trunk/src/proj_field.m @ 684

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

corrections in proj_field: reducing the field of an image, and read_field: reading norm of vectors on gridded mesh

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