source: trunk/src/proj_field.m @ 643

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

generalisation of update_imadoc, improverment of the GUI get_field

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