source: trunk/src/proj_field.m @ 1040

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