source: trunk/src/proj_field.m @ 1060

Last change on this file since 1060 was 1060, checked in by sommeria, 5 years ago

projection repaired

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            VarAttribute_var.Role='coord_x';
512        end
513      %  VarAttribute_var.Role='coord_x';% the variable is now used as an absissa
514        VarAttribute_histo.Role='histo';
515        ProjData.VarAttribute=[ProjData.VarAttribute {VarAttribute_var} {VarAttribute_histo} {[]} {[]} {[]}];
516    end
517end
518
519%-----------------------------------------------------------------
520%project on a line
521% AJOUTER flux,circul,error
522% OUTPUT:
523% ProjData: projected field
524%
525function  [ProjData,errormsg] = proj_line(FieldData, ObjectData)
526%-----------------------------------------------------------------
527
528%% prepare heading for the projected field
529[ProjData,errormsg]=proj_heading(FieldData,ObjectData);%transfer global attributes
530if ~isempty(errormsg)
531    return
532end
533ProjData.NbDim=1;
534%initialisation of the input parameters and defaultoutput
535ProjMode=ObjectData.ProjMode; %rmq: ProjMode always defined from input={'projection','interp_lin','interp_tps'}
536% ProjAngle=90; %90 degrees projection by default
537width=0;
538if isfield(ObjectData,'RangeY')
539    width=max(ObjectData.RangeY);%Rangey needed bfor mode 'projection'
540end
541% default output
542Xline=[];
543flux=0;
544circul=0;
545liny=ObjectData.Coord(:,2);
546NbPoints=size(ObjectData.Coord,1);
547
548%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
549[CellInfo,NbDim,errormsg]=find_field_cells(FieldData);
550if ~isempty(errormsg)
551    errormsg=['error in proj_field/proj_line:' errormsg];
552    return
553end
554CellInfo=CellInfo(NbDim>=2); %keep only the 2D or 3D cells
555cell_select=true(size(CellInfo));
556for icell=1:length(CellInfo)
557    if isfield(CellInfo{icell},'ProjModeRequest')
558        if strcmp(ProjMode,'interp_tps')&& ~strcmp(CellInfo{icell}.CoordType,'tps')
559            cell_select(icell)=0;
560        end
561    end
562end
563if isempty(find(cell_select,1))
564    errormsg=[' invalid projection mode ''' ProjMode ''': use ''interp_tps'' to interpolate spatial derivatives'];
565    return
566end
567CellInfo=CellInfo(cell_select);
568
569%% projection line: object types selected from  proj_field='line','polyline','polygon','rectangle','ellipse':
570LineCoord=ObjectData.Coord;
571switch ObjectData.Type
572    case 'ellipse'
573        LineLength=2*pi*ObjectData.RangeX*ObjectData.RangeY;
574        NbSegment=0;
575    case 'rectangle'
576        LineCoord([1 4],1)=ObjectData.Coord(1,1)-ObjectData.RangeX;
577        LineCoord([1 2],2)=ObjectData.Coord(1,2)-ObjectData.RangeY;
578        LineCoord([2 3],1)=ObjectData.Coord(1,1)+ObjectData.RangeX;
579        LineCoord([4 1],2)=ObjectData.Coord(1,2)+ObjectData.RangeY;
580    case 'polygon'
581        LineCoord(NbPoints+1)=LineCoord(1);
582end
583if ~strcmp(ObjectData.Type,'ellipse')
584    if ~strcmp(ObjectData.Type,'rectangle') && NbPoints<2
585        return% line needs at least 2 points to be defined
586    end
587    dlinx=diff(LineCoord(:,1));
588    dliny=diff(LineCoord(:,2));
589    [theta,dlength]=cart2pol(dlinx,dliny);%angle and length of each segment
590    LineLength=sum(dlength);
591    NbSegment=numel(LineLength);
592end
593CheckClosedLine=~isempty(find(strcmp(ObjectData.Type,{'rectangle','ellipse','polygon'})));
594
595%% angles of the polyline and boundaries of action for mode 'projection'
596
597% determine a rectangles at +-width from the line (only used for the ProjMode='projection or 'interp_tps')
598xsup=zeros(1,NbPoints); xinf=zeros(1,NbPoints); ysup=zeros(1,NbPoints); yinf=zeros(1,NbPoints);
599if isequal(ProjMode,'projection')
600    if strcmp(ObjectData.Type,'line')
601        xsup=ObjectData.Coord(:,1)-width*sin(theta);
602        xinf=ObjectData.Coord(:,1)+width*sin(theta);
603        ysup=ObjectData.Coord(:,2)+width*cos(theta);
604        yinf=ObjectData.Coord(:,2)-width*cos(theta);
605    else
606        errormsg='mode projection only available for simple line, use interpolation otherwise';
607        return
608    end
609else % need to define the set of interpolation points
610    if isfield(ObjectData,'DX') && ~isempty(ObjectData.DX)
611        DX=abs(ObjectData.DX);%mesh of interpolation points along the line
612        if CheckClosedLine
613            NbPoint=ceil(LineLength/DX);
614            DX=LineLength/NbPoint;%adjust DX to get an integer nbre of intervals in a closed line
615            DX_edge=DX/2;
616        else
617            DX_edge=(LineLength-DX*floor(LineLength/DX))/2;%margin from the first point and first interpolation point, the same for the end point
618        end
619        XI=[];
620        YI=[];
621        ThetaI=[];
622        dlengthI=[];
623        if strcmp(ObjectData.Type,'ellipse')
624            phi=(DX_edge:DX:LineLength)*2*pi/LineLength;
625            XI=ObjectData.RangeX*cos(phi);
626            YI=ObjectData.RangeY*sin(phi);
627            dphi=2*pi*DX/LineLength;
628            [ThetaI,dlengthI]=cart2pol(-ObjectData.RangeX*sin(phi)*dphi,ObjectData.RangeY*cos(phi)*dphi);
629        else
630            for isegment=1:NbSegment
631                costheta=cos(theta(isegment));
632                sintheta=sin(theta(isegment));
633                %                 XIsegment=LineCoord(isegment,1)+DX_edge*costheta:DX*costheta:LineCoord(isegment+1,1));
634                %                 YIsegment=(LineCoord(isegment,2)+DX_edge*sintheta:DX*sintheta:LineCoord(isegment+1,2));
635                NbInterval=floor((dlength(isegment)-DX_edge)/DX);
636                LastX=DX_edge+DX*NbInterval;
637                NbPoint=NbInterval+1;
638                XIsegment=linspace(LineCoord(isegment,1)+DX_edge*costheta,LineCoord(isegment,1)+LastX*costheta,NbPoint);
639                YIsegment=linspace(LineCoord(isegment,2)+DX_edge*sintheta,LineCoord(isegment,2)+LastX*sintheta,NbPoint);
640                XI=[XI XIsegment];
641                YI=[YI YIsegment];
642                ThetaI=[ThetaI theta(isegment)*ones(1,numel(XIsegment))];
643                dlengthI=[dlengthI DX*ones(1,numel(XIsegment))];
644                DX_edge=DX-(dlength(isegment)-LastX);%edge for the next segment set to keep DX=DX_end+DX_edge between two segments
645            end
646        end
647        Xproj=cumsum(dlengthI);
648    else
649        errormsg='abscissa mesh along line DX needed for interpolation';
650        return
651    end
652end
653
654%% loop on variable cells with the same space dimension 2
655ProjData.ListVarName={};
656ProjData.VarDimName={};
657check_abscissa=0;
658for icell=1:length(CellInfo)
659    % list of variable types to be projected
660    ListProj={'VarIndex_scalar','VarIndex_image','VarIndex_color','VarIndex_vector_x','VarIndex_vector_y'};
661    check_proj=false(size(FieldData.ListVarName));
662    for ilist=1:numel(ListProj)
663        if isfield(CellInfo{icell},ListProj{ilist})
664            check_proj(CellInfo{icell}.(ListProj{ilist}))=1;
665        end
666    end
667    VarIndex=find(check_proj);% indices of the variables to be projected
668   
669    %identify error flag
670    errorflag=0; %default, no error flag
671    if isfield(CellInfo{icell},'VarIndex_errorflag');% test for error flag
672        FFName=FieldData.ListVarName{CellInfo{icell}.VarIndex_errorflag};
673        errorflag=FieldData.(FFName);
674    end
675    VarName=FieldData.ListVarName(VarIndex);% cell array of the names of variables to pje
676    ivar_U=[];
677    ivar_V=[];
678    %% check needed object properties for unstructured positions (position given by the variables with role coord_x, coord_y
679   
680    %         circul=0;
681    %         flux=0;
682    %%%%%%%  % A FAIRE CALCULER MEAN DES QUANTITES    %%%%%%
683    switch CellInfo{icell}.CoordType
684        %case of unstructured coordinates
685        case 'scattered'
686            coord_x=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(end)});
687            coord_y=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(end-1)});
688           
689            if strcmp(ProjMode,'projection')
690                if width==0
691                    errormsg='range of the projection object is missing';
692                    return
693                end
694                ProjData.ListVarName=[ProjData.ListVarName FieldData.ListVarName(CellInfo{icell}.CoordIndex(end))];
695                ProjData.VarDimName=[ProjData.VarDimName FieldData.ListVarName(CellInfo{icell}.CoordIndex(end))];
696                nbvar=numel(ProjData.ListVarName);
697                ProjData.VarAttribute{nbvar}.Role='coord_x';
698                ProjData.VarAttribute{nbvar}.long_name='abscissa along line';
699                % select the (non false) input data located in the band of projection
700                flagsel=(errorflag==0) & ((coord_y -yinf(1))*(xinf(2)-xinf(1))>(coord_x-xinf(1))*(yinf(2)-yinf(1))) ...
701                    & ((coord_y -ysup(1))*(xsup(2)-xsup(1))<(coord_x-xsup(1))*(ysup(2)-ysup(1))) ...
702                    & ((coord_y -yinf(2))*(xsup(2)-xinf(2))>(coord_x-xinf(2))*(ysup(2)-yinf(2))) ...
703                    & ((coord_y -yinf(1))*(xsup(1)-xinf(1))<(coord_x-xinf(1))*(ysup(1)-yinf(1)));
704                coord_x=coord_x(flagsel);
705                coord_y=coord_y(flagsel);
706                costheta=cos(theta);
707                sintheta=sin(theta);
708                Xproj=(coord_x-ObjectData.Coord(1,1))*costheta + (coord_y-ObjectData.Coord(1,2))*sintheta; %projection on the line
709                [Xproj,indsort]=sort(Xproj);% sort points by increasing absissa along the projection line
710                ProjData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(end)})=Xproj;
711                for ivar=1:numel(VarIndex)
712                    ProjData.(VarName{ivar})=FieldData.(VarName{ivar})(flagsel);% restrict variables to the projection band
713                    ProjData.(VarName{ivar})=ProjData.(VarName{ivar})(indsort);% sort by absissa
714                    ProjData.ListVarName=[ProjData.ListVarName VarName{ivar}];
715                    ProjData.VarDimName=[ProjData.VarDimName FieldData.ListVarName(CellInfo{icell}.CoordIndex(end))];
716                    ProjData.VarAttribute{nbvar+ivar}=FieldData.VarAttribute{VarIndex(ivar)};%reproduce var attribute
717                    if isfield(ProjData.VarAttribute{nbvar+ivar},'Role')
718                        if  strcmp(ProjData.VarAttribute{nbvar+ivar}.Role,'vector_x');
719                            ivar_U=nbvar+ivar;
720                        elseif strcmp(ProjData.VarAttribute{nbvar+ivar}.Role,'vector_y');
721                            ivar_V=nbvar+ivar;
722                        end
723                    end
724                    ProjData.VarAttribute{ivar+nbvar}.Role='discrete';% will promote plots of the profiles with continuoval(['us lines
725                end
726            elseif isequal(ProjMode,'interp_lin')  %filtering %linear interpolation:
727                if ~check_abscissa
728                    %XName=FieldData.ListVarName{CellInfo{icell}.CoordIndex(end)};
729                    XName='X';
730                    ProjData.ListVarName=[ProjData.ListVarName {XName}];
731                    ProjData.VarDimName=[ProjData.VarDimName {XName}];
732                    nbvar=numel(ProjData.ListVarName);
733                    ProjData.VarAttribute{nbvar}.Role='coord_x';
734                    ProjData.VarAttribute{nbvar}.long_name='abscissa along line';
735                    check_abscissa=1; % define abcissa only once
736                end
737                if ~isequal(errorflag,0)
738                    VarName_FF=FieldData.ListVarName{CellInfo{icell}.VarIndex_errorflag};
739                    indsel=find(FieldData.(VarName_FF)==0);
740                    coord_x=coord_x(indsel);
741                    coord_y=coord_y(indsel);
742                    for ivar=1:numel(CellInfo{icell}.VarIndex)
743                        VarName=FieldData.ListVarName{CellInfo{icell}.VarIndex(ivar)};
744                        FieldData.(VarName)=FieldData.(VarName)(indsel);
745                    end
746                end
747                [ProjVar,ListFieldProj,VarAttribute,errormsg]=calc_field_interp([coord_x coord_y],FieldData,CellInfo{icell}.FieldName,XI,YI);
748                ProjData.X=Xproj;
749                nbvar=numel(ProjData.ListVarName);
750                ProjData.ListVarName=[ProjData.ListVarName ListFieldProj];
751                ProjData.VarAttribute=[ProjData.VarAttribute VarAttribute];
752                for ivar=1:numel(VarAttribute)
753                    ProjData.VarDimName=[ProjData.VarDimName {XName}];
754                    if isfield(VarAttribute{ivar},'Role')
755                        if  strcmp(VarAttribute{ivar}.Role,'vector_x');
756                            ivar_U=ivar+nbvar;
757                        elseif strcmp(VarAttribute{ivar}.Role,'vector_y');
758                            ivar_V=ivar+nbvar;
759                        end
760                    end
761                    ProjData.VarAttribute{ivar+nbvar}.Role='coord_y';% will promote plots of the profiles with continuous lines
762                    ProjData.(ListFieldProj{ivar})=ProjVar{ivar};
763                end
764            end
765        case 'tps'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
766            if strcmp(ProjMode,'interp_tps')
767                Coord=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex});
768                NbCentres=FieldData.(FieldData.ListVarName{CellInfo{icell}.NbCentres_tps});
769                SubRange=FieldData.(FieldData.ListVarName{CellInfo{icell}.SubRange_tps});
770                if isfield(CellInfo{icell},'VarIndex_vector_x')&&isfield(CellInfo{icell},'VarIndex_vector_y')
771                    FieldVar=cat(3,FieldData.(FieldData.ListVarName{CellInfo{icell}.VarIndex_vector_x}),FieldData.(FieldData.ListVarName{CellInfo{icell}.VarIndex_vector_y}));
772                end
773                [DataOut,VarAttribute,errormsg]=calc_field_tps(Coord,NbCentres,SubRange,FieldVar,CellInfo{icell}.FieldName,cat(3,XI,YI));
774                ProjData.ListVarName=[ProjData.ListVarName {'X'}];
775                ProjData.VarDimName=[ProjData.VarDimName {'X'}];
776                ProjData.X=Xproj;
777                nbvar=numel(ProjData.ListVarName);
778                ProjData.VarAttribute{nbvar}.Role='coord_x';
779                ProjData.VarAttribute{nbvar}.long_name='abscissa along line';
780                ProjVarName=(fieldnames(DataOut))';
781                ProjData.ListVarName=[ProjData.ListVarName ProjVarName];
782                ProjData.VarAttribute=[ProjData.VarAttribute VarAttribute];
783                for ivar=1:numel(VarAttribute)
784                    ProjData.VarDimName=[ProjData.VarDimName {'X'}];
785                    if isfield(VarAttribute{ivar},'Role')
786                        if  strcmp(VarAttribute{ivar}.Role,'vector_x');
787                            ivar_U=ivar+nbvar;
788                        elseif strcmp(VarAttribute{ivar}.Role,'vector_y');
789                            ivar_V=ivar+nbvar;
790                        end
791                    end
792                    ProjData.VarAttribute{ivar+nbvar}.Role='coord_y';% will promote plots of the profiles with continuous lines
793                    ProjData.(ProjVarName{ivar})=DataOut.(ProjVarName{ivar});
794                end
795            end
796            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
797           
798        case 'grid'   %case of structured coordinates
799            if ~isequal(ObjectData.Type,'line')% exclude polyline
800                errormsg=['no  projection available on ' ObjectData.Type 'for structured coordinates'];
801                return
802            end%
803            test_interp2=0;%default
804           
805            if max(NbDim)==3 % 3D case
806                AZName=FieldData.ListVarName{CellInfo{icell}.CoordIndex(end)};
807                AYName=FieldData.ListVarName{CellInfo{icell}.CoordIndex(end-1)};
808                AXName=FieldData.ListVarName{CellInfo{icell}.CoordIndex(end-2)};
809                AX=FieldData.(AXName);% set of x positions
810                AY=FieldData.(AYName);% set of y positions
811                AZ=FieldData.(AZName);% set of z positions
812                 AName=FieldData.ListVarName{VarIndex(1)};
813                npxy=size(FieldData.(AName));
814                npz=npxy(1);
815                npy=npxy(2);
816                npx=npxy(1);
817                AXI=linspace(AX(1),AX(end), npx);%set of  x  positions for the interpolated input data
818                AYI=linspace(AY(1),AY(end), npy);%set of  x  positions for the interpolated input data
819                 AZI=linspace(AZ(1),AZ(end), npy);%set of  x  positions for the interpolated input data
820                for ivar=VarIndex
821                    VarName=FieldData.ListVarName{ivar};
822                    FieldData.(VarName)=interp3(FieldData.(AXName),FieldData.(AYName),FieldData.(AZName),FieldData.(VarName),AXI,AYI,AZI);
823
824%                     vec_A=reshape(squeeze(FieldData.(FieldData.ListVarName{ivar})),npx*npy,nbcolor); %put the original image in colum
825%                     if nbcolor==1
826%                         vec_B(ind_in)=vec_A(ICOMB);
827%                         vec_B(ind_out)=zeros(size(ind_out));
828%                         A_out=reshape(vec_B,npY,npX);
829%                         ProjData.(FieldData.ListVarName{ivar}) =sum(A_out,1)/npY;
830%                     elseif nbcolor==3
831%                         vec_B(ind_in,1:3)=vec_A(ICOMB,:);
832%                         vec_B(ind_out,1)=zeros(size(ind_out));
833%                         vec_B(ind_out,2)=zeros(size(ind_out));
834%                         vec_B(ind_out,3)=zeros(size(ind_out));
835%                         A_out=reshape(vec_B,npY,npX,nbcolor);
836%                         ProjData.(FieldData.ListVarName{ivar})=squeeze(sum(A_out,1)/npY);
837%                     end
838                    ProjData.ListVarName=[ProjData.ListVarName FieldData.ListVarName{ivar}];
839                    ProjData.VarDimName=[ProjData.VarDimName {AXName}];%to generalize with the initial name of the x coordinate
840                    ProjData.VarAttribute{ivar}.Role='continuous';% for plot with continuous line
841                end
842               
843            else
844                AYName=FieldData.ListVarName{CellInfo{icell}.CoordIndex(end-1)};
845                AXName=FieldData.ListVarName{CellInfo{icell}.CoordIndex(end)};
846                AX=FieldData.(AXName);% set of x positions
847                AY=FieldData.(AYName);% set of y positions
848                AName=FieldData.ListVarName{VarIndex(1)};
849                npxy=size(FieldData.(AName));
850                npx=npxy(2);
851                npy=npxy(1);
852                if numel(AX)==2
853                    DX=(AX(2)-AX(1))/(npx-1);
854                else
855                    DX_vec=diff(AX);
856                    DX=max(DX_vec);
857                    DX_min=min(DX_vec);
858                    if (DX-DX_min)>0.0001*abs(DX)
859                        test_interp2=1;
860                        DX=DX_min;
861                    end
862                end
863                if numel(AY)==2
864                    DY=(AY(2)-AY(1))/(npy-1);
865                else
866                    DY_vec=diff(AY);
867                    DY=max(DY_vec);
868                    DY_min=min(DY_vec);
869                    if (DY-DY_min)>0.0001*abs(DY)
870                        test_interp2=1;
871                        DY=DY_min;
872                    end
873                end
874                AXI=linspace(AX(1),AX(end), npx);%set of  x  positions for the interpolated input data
875                AYI=linspace(AY(1),AY(end), npy);%set of  x  positions for the interpolated input data
876                if isfield(ObjectData,'DX')
877                    DXY_line=ObjectData.DX;%mesh on the projection line
878                else
879                    DXY_line=sqrt(abs(DX*DY));% mesh on the projection line
880                end
881                dlinx=ObjectData.Coord(2,1)-ObjectData.Coord(1,1);
882                dliny=ObjectData.Coord(2,2)-ObjectData.Coord(1,2);
883                linelength=sqrt(dlinx*dlinx+dliny*dliny);
884                theta=angle(dlinx+i*dliny);%angle of the line
885                if isfield(FieldData,'RangeX')
886                    XMin=min(FieldData.RangeX);%shift of the origin on the line
887                else
888                    XMin=0;
889                end
890                ProjData.(AXName)=linspace(XMin,XMin+linelength,linelength/DXY_line+1);%abscissa of the new pixels along the line
891                y=linspace(-width,width,2*width/DXY_line+1);%ordintes of the new pixels (coordinate across the line)
892                npX=length(ProjData.(AXName));
893                npY=length(y); %TODO: utiliser proj_grid
894                [X,Y]=meshgrid(ProjData.(AXName),y);%grid in the line coordinates
895                XIMA=ObjectData.Coord(1,1)+(X-XMin)*cos(theta)-Y*sin(theta);
896                YIMA=ObjectData.Coord(1,2)+(X-XMin)*sin(theta)+Y*cos(theta);
897                XIMA=(XIMA-AX(1))/DX+1;%  index of the original image along x
898                YIMA=(YIMA-AY(1))/DY+1;% index of the original image along y
899                XIMA=reshape(round(XIMA),1,npX*npY);%indices reorganized in 'line'
900                YIMA=reshape(round(YIMA),1,npX*npY);
901                flagin=XIMA>=1 & XIMA<=npx & YIMA >=1 & YIMA<=npy;%flagin=1 inside the original image
902                ind_in=find(flagin);
903                ind_out=find(~flagin);
904                ICOMB=(XIMA-1)*npy+YIMA;
905                ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
906                if numel(npxy)==2
907                    nbcolor=1;
908                elseif length(npxy)==3
909                    nbcolor=npxy(3);
910                else
911                    errormsg='multicomponent field not projected';
912                    display(errormsg)
913                    return
914                end
915                ProjData.ListVarName=[ProjData.ListVarName {AXName}];
916                ProjData.VarDimName=[ProjData.VarDimName {AXName}];
917                nbvar=numel(ProjData.VarDimName);
918                ProjData.VarAttribute{nbvar}.Role='coord_x';
919                for ivar=VarIndex
920                    %VarName{ivar}=FieldData.ListVarName{ivar};
921                    if test_interp2% interpolate on new grid
922                        FieldData.(FieldData.ListVarName{ivar})=interp2(FieldData.(AXName),FieldData.(AYName),FieldData.(FieldData.ListVarName{ivar}),AXI,AYI');
923                    end
924                    vec_A=reshape(squeeze(FieldData.(FieldData.ListVarName{ivar})),npx*npy,nbcolor); %put the original image in colum
925                    if nbcolor==1
926                        vec_B(ind_in)=vec_A(ICOMB);
927                        vec_B(ind_out)=zeros(size(ind_out));
928                        A_out=reshape(vec_B,npY,npX);
929                        ProjData.(FieldData.ListVarName{ivar}) =sum(A_out,1)/npY;
930                    elseif nbcolor==3
931                        vec_B(ind_in,1:3)=vec_A(ICOMB,:);
932                        vec_B(ind_out,1)=zeros(size(ind_out));
933                        vec_B(ind_out,2)=zeros(size(ind_out));
934                        vec_B(ind_out,3)=zeros(size(ind_out));
935                        A_out=reshape(vec_B,npY,npX,nbcolor);
936                        ProjData.(FieldData.ListVarName{ivar})=squeeze(sum(A_out,1)/npY);
937                    end
938                    ProjData.ListVarName=[ProjData.ListVarName FieldData.ListVarName{ivar}];
939                    ProjData.VarDimName=[ProjData.VarDimName {AXName}];%to generalize with the initial name of the x coordinate
940                    nbvar=nbvar+1;
941                    ProjData.VarAttribute{nbvar}.Role='coord_y';% for plot with continuous line
942                end
943                if nbcolor==3
944                    ProjData.VarDimName{end}={AXName,'rgb'};
945                end
946            end
947           
948    end
949if ~isempty(ivar_U) && ~isempty(ivar_V)
950    vector_x =ProjData.(ProjData.ListVarName{ivar_U});
951    ProjData.(ProjData.ListVarName{ivar_U}) =cos(theta)*vector_x+sin(theta)*ProjData.(ProjData.ListVarName{ivar_V});
952    ProjData.(ProjData.ListVarName{ivar_V}) =-sin(theta)*vector_x+cos(theta)*ProjData.(ProjData.ListVarName{ivar_V});
953end
954end
955
956% %shotarter case for horizontal or vertical line (A FAIRE
957% %     Rangx=[0.5 npx-0.5];%image coordiantes of corners
958% %     Rangy=[npy-0.5 0.5];
959% %     if isfield(Calib,'Pxcmx')&isfield(Calib,'Pxcmy')%old calib
960% %         Rangx=Rangx/Calib.Pxcmx;
961% %         Rangy=Rangy/Calib.Pxcmy;
962% %     else
963% %         [Rangx]=phys_XYZ(Calib,Rangx,[0.5 0.5],[0 0]);%case of translations without rotation and quadratic deformation
964% %         [xx,Rangy]=phys_XYZ(Calib,[0.5 0.5],Rangy,[0 0]);
965% %     end
966%
967% %     test_scal=0;%default% 3- 'UserData':(get(handles.Tag,'UserData')
968
969
970%-----------------------------------------------------------------
971%project on a plane
972% AJOUTER flux,circul,error
973function  [ProjData,errormsg] = proj_plane(FieldData, ObjectData)
974%-----------------------------------------------------------------
975
976%% rotation angles
977PlaneAngle=[0 0];
978norm_plane=[0 0 1];
979%cos_om=1;
980%sin_om=0;
981test90x=0;%=1 for 90 degree rotation alround x axis
982test90y=0;%=1 for 90 degree rotation alround y axis
983% if strcmp(ObjectData.Type,'plane_z')
984%     Delta_x=ObjectData.Coord(2,1)-ObjectData.Coord(1,1);
985%     Delta_y=ObjectData.Coord(2,2)-ObjectData.Coord(1,2);
986%     Delta_mod=sqrt(Delta_x*Delta_x+Delta_y*Delta_y);
987%     ObjectData.Angle=[0 0 0];
988%     ObjectData.Angle(1)=90*Delta_x/Delta_mod;
989%     ObjectData.0(2)=90*Delta_y/Delta_mod;
990% end
991if isfield(ObjectData,'Angle')
992    checkM2=0;
993    if numel(ObjectData.Angle)==2 && ~isequal(ObjectData.Angle,[0 0])
994        checkM2=1;
995        test90y=0;%isequal(ObjectData.Angle,[0 90 0]);
996    end
997    PlaneAngle=(pi/180)*ObjectData.Angle;
998    %     om=norm(PlaneAngle);%norm of rotation angle in radians
999    %     OmAxis=PlaneAngle/om; %unit vector marking the rotation axis
1000    %     cos_om=cos(om);
1001    %     sin_om=sin(om);
1002    %     coeff=OmAxis(3)*(1-cos_om);
1003    %     %components of the unity vector norm_plane normal to the projection plane
1004    %     norm_plane(1)=OmAxis(1)*coeff+OmAxis(2)*sin_om;
1005    %     norm_plane(2)=OmAxis(2)*coeff-OmAxis(1)*sin_om;
1006    %     norm_plane(3)=OmAxis(3)*coeff+cos_om;
1007   
1008    M1=[cos(PlaneAngle(1)) sin(PlaneAngle(1)) 0;-sin(PlaneAngle(1)) cos(PlaneAngle(1)) 0;0 0 1];
1009    M=M1;
1010    if checkM2
1011        M2=[1 0 0;0 cos(PlaneAngle(2)) sin(PlaneAngle(2));0 -sin(PlaneAngle(2)) cos(PlaneAngle(2))];
1012        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)
1013    end
1014    norm_plane=M*[0 0 1]';
1015   
1016end
1017testangle=~isequal(PlaneAngle,[0 0])||~isequal(ObjectData.Coord(1:2),[0 0 ]) ;% && ~test90y && ~test90x;%=1 for slanted plane
1018
1019%% mesh sizes DX and DY
1020DX=[];
1021DY=[];%default
1022if isfield(ObjectData,'DX') && ~isempty(ObjectData.DX)
1023    DX=abs(ObjectData.DX);%mesh of interpolation points
1024elseif isfield(FieldData,'CoordMesh')
1025    DX=FieldData.CoordMesh;
1026end
1027if isfield(ObjectData,'DY') && ~isempty(ObjectData.DY)
1028    DY=abs(ObjectData.DY);%mesh of interpolation points
1029elseif isfield(FieldData,'CoordMesh')
1030    DY=FieldData.CoordMesh;
1031end
1032if  ~strcmp(ObjectData.ProjMode,'projection') && (isempty(DX)||isempty(DY))
1033    errormsg='DX or DY not defined';
1034    return
1035end
1036InterpMesh=min(DX,DY);%mesh used for interpolation in a slanted plane
1037% if strcmp(ObjectData.Type,'plane_z')
1038%     InterpMesh=10*InterpMesh;%TODO: temporary, to shorten computation
1039% end
1040
1041%% extrema along each axis
1042testXMin=0;% test if min of X coordinates defined on the projection object, =0 by default
1043testXMax=0;% test if max of X coordinates defined on the projection object, =0 by default
1044testYMin=0;% test if min of Y coordinates defined on the projection object, =0 by default
1045testYMax=0;% test if max of Y coordinates defined on the projection object, =0 by default
1046if isfield(ObjectData,'RangeX') % rangeX defined by the projection object
1047    XMin=min(ObjectData.RangeX);
1048    XMax=max(ObjectData.RangeX);
1049    testXMin=XMax>XMin;%=1 if XMin defined (i.e. RangeY has two distinct elements)
1050    testXMax=1;% max of X coordinates defined on the projection object
1051end
1052if isfield(ObjectData,'RangeY') % rangeY defined by the projection object
1053    YMin=min(ObjectData.RangeY);
1054    YMax=max(ObjectData.RangeY);
1055    testYMin=YMax>YMin;%=1 if YMin defined (i.e. RangeY has tow distinct elements)
1056    testYMax=1;% max of Y coordinates defined on the projection object
1057end
1058width=0;%default width of the projection band
1059if isfield(ObjectData,'RangeZ')
1060    width=max(ObjectData.RangeZ);
1061end
1062
1063%% interpolation range
1064thresh2=[];
1065if isfield(ObjectData,'RangeInterp')
1066    thresh2=ObjectData.RangeInterp*ObjectData.RangeInterp;%square of interpolation range (do not interpolate beyond this range)
1067end
1068
1069%% initiate Matlab  structure for physical field
1070[ProjData,errormsg]=proj_heading(FieldData,ObjectData);
1071if ~isempty(errormsg)
1072    return
1073end
1074
1075%% reproduce initial plane position and angle
1076if isfield(FieldData,'PlaneCoord')&&length(FieldData.PlaneCoord)==3&& isfield(ProjData,'ProjObjectCoord')
1077    if length(ProjData.ProjObjectCoord)==3% if the projection plane has a z coordinate
1078        if isfield(ProjData,'.PlaneCoord') && ~isequal(ProjData.PlaneCoord(3),ProjData.ProjObjectCoord) %check the consistency with the z coordinate of the field plane (set by calibration)
1079            errormsg='inconsistent z position for field and projection plane';
1080            return
1081        end
1082    else % the z coordinate is set only by the field plane (by calibration)
1083        ProjData.ProjObjectCoord(3)=FieldData.PlaneCoord(3);
1084    end
1085    if isfield(FieldData,'PlaneAngle')
1086        if isfield(ProjData,'ProjObjectAngle')
1087            if ~isequal(FieldData.PlaneAngle,ProjData.ProjObjectAngle) %check the consistency with the z coordinate of the field plane (set by calibration)
1088                errormsg='inconsistent plane angle for field and projection plane';
1089                return
1090            end
1091        else
1092            ProjData.ProjObjectAngle=FieldData.PlaneAngle;
1093        end
1094    end
1095end
1096ProjData.NbDim=2;
1097ProjData.ListVarName={};
1098ProjData.VarDimName={};
1099ProjData.VarAttribute={};
1100if ~isempty(DX) && ~isempty(DY)
1101    ProjData.CoordMesh=sqrt(DX*DY);%define typical data mesh, useful for mouse selection in plots
1102elseif isfield(FieldData,'CoordMesh')
1103    ProjData.CoordMesh=FieldData.CoordMesh;
1104end
1105%error=0;%default
1106%flux=0;
1107
1108%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
1109
1110[CellInfo,NbDimArray,errormsg]=find_field_cells(FieldData);
1111
1112if ~isempty(errormsg)
1113    errormsg=['error in proj_field/proj_plane:' errormsg];
1114    return
1115end
1116
1117check_grid=zeros(size(CellInfo));% =1 if a grid is needed , =0 otherwise, for each field cell
1118ProjMode=num2cell(blanks(numel(CellInfo)));
1119ProjMode=regexprep(ProjMode,' ',ObjectData.ProjMode);
1120%ProjMode=cell(size(CellInfo));
1121% for icell=1:numel(CellInfo)
1122%     ProjMode{icell}=ObjectData.ProjMode;% projection mode of the plane object
1123% end
1124icell_grid=[];% field cell index which defines the grid
1125if ~strcmp(ObjectData.ProjMode,'projection')&& ~strcmp(ObjectData.Type,'plane_z')% TODO:rationalize
1126    %% define the new coordinates in case of interpolation on a imposed grid
1127    if ~testYMin
1128        errormsg='min Y value not defined for the projection grid';return
1129    end
1130    if ~testYMax
1131        errormsg='max Y value not defined for the projection grid';return
1132    end
1133    if ~testXMin
1134        errormsg='min X value not defined for the projection grid';return
1135    end
1136    if ~testXMax
1137        errormsg='max X value not defined for the projection grid';return
1138    end
1139else
1140    %% case of a grid requested by the input field
1141    for icell=1:numel(CellInfo)% TODO: recalculate coordinates here to get the bounds in the rotated coordinates
1142        if isfield(CellInfo{icell},'ProjModeRequest')
1143            switch CellInfo{icell}.ProjModeRequest
1144                case 'interp_lin'
1145                    ProjMode{icell}='interp_lin';
1146                case 'interp_tps'
1147                    ProjMode{icell}='interp_tps';
1148            end
1149        end
1150        if strcmp(ProjMode{icell},'interp_lin')||strcmp(ProjMode{icell},'interp_tps')
1151            check_grid(icell)=1;
1152        end
1153        if strcmp(CellInfo{icell}.CoordType,'grid') && NbDimArray(icell)>=2
1154            if ~testangle && isempty(icell_grid)% if the input gridded data is not modified, choose the first one in case of multiple gridded field cells
1155                icell_grid=icell;
1156                ProjMode{icell}='projection';
1157            end
1158            check_grid(icell)=1;
1159        end
1160    end
1161    if ~isempty(find(check_grid))% if a grid is requested by the input field
1162        if isempty(icell_grid)%  if the grid is not given by cell #icell_grid
1163            if ~isfield(FieldData,'XMax')
1164                FieldData=find_field_bounds(FieldData);
1165            end
1166        end
1167    end
1168end
1169if ~isempty(find(check_grid))||~strcmp(ObjectData.ProjMode,'projection')%no existing gridded data used
1170    if isempty(icell_grid)||~strcmp(ObjectData.ProjMode,'projection')%no existing gridded data used
1171        AYName='coord_y';
1172        AXName='coord_x';
1173        if strcmp(ObjectData.ProjMode,'projection')||strcmp(ObjectData.Type,'plane_z')
1174            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
1175            ProjData.coord_x=[FieldData.XMin FieldData.XMax];
1176            coord_x_proj=FieldData.XMin:FieldData.CoordMesh:FieldData.XMax;
1177            coord_y_proj=FieldData.YMin:FieldData.CoordMesh:FieldData.YMax;
1178        else
1179            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
1180            ProjData.coord_x=[ObjectData.RangeX(1) ObjectData.RangeX(2)];
1181            coord_x_proj=ObjectData.RangeX(1):ObjectData.DX:ObjectData.RangeX(2);
1182            coord_y_proj=ObjectData.RangeY(1):ObjectData.DY:ObjectData.RangeY(2);
1183        end
1184        [XI,YI]=meshgrid(coord_x_proj,coord_y_proj);%grid in the new coordinates
1185        ProjData.VarDimName={AYName,AXName};
1186        %         XI=ObjectData.Coord(1,1)+(X)*cos(PlaneAngle(3))-YI*sin(PlaneAngle(3));%corresponding coordinates in the original system
1187        %         YI=ObjectData.Coord(1,2)+(X)*sin(PlaneAngle(3))+YI*cos(PlaneAngle(3));
1188    else% we use the existing grid from field cell #icell_grid
1189        NbDim=NbDimArray(icell_grid);
1190        AYName=FieldData.ListVarName{CellInfo{icell_grid}.CoordIndex(NbDim-1)};%name of input x coordinate (name preserved on projection)
1191        AXName=FieldData.ListVarName{CellInfo{icell_grid}.CoordIndex(NbDim)};%name of input y coordinate (name preserved on projection)
1192        AYDimName=FieldData.VarDimName{CellInfo{icell_grid}.CoordIndex(NbDim-1)};%
1193        AXDimName=FieldData.VarDimName{CellInfo{icell_grid}.CoordIndex(NbDim)};%
1194        ProjData.VarDimName={AYDimName,AXDimName};
1195        ProjData.(AYName)=FieldData.(AYName); % new (projected ) y coordinates
1196        ProjData.(AXName)=FieldData.(AXName); % new (projected ) y coordinates
1197    end
1198    ProjData.ListVarName={AYName,AXName};
1199   
1200    ProjData.VarAttribute{1}.Role='coord_y';
1201    ProjData.VarAttribute{2}.Role='coord_x';
1202end
1203
1204%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1205% LOOP ON FIELD CELLS, PROJECT VARIABLES
1206% CellVarIndex=cells of variable index arrays
1207%ivar_new=0; % index of the current variable in the projected field
1208% icoord=0;
1209nbcoord=0;%number of added coordinate variables brought by projection
1210%nbvar=0;
1211vector_x_proj=[];
1212vector_y_proj=[];
1213for icell=1:length(CellInfo)
1214    NbDim=NbDimArray(icell);
1215    if NbDim<2
1216        continue % only cells represnting 2D or 3D fields are involved
1217    end
1218    VarIndex= CellInfo{icell}.VarIndex;%  indices of the selected variables in the list FieldData.ListVarName
1219    %dimensions
1220    DimCell=FieldData.VarDimName{VarIndex(1)};
1221    if ischar(DimCell)
1222        DimCell={DimCell};%name of dimensions
1223    end
1224    coord_z=0;%default
1225    ListVarName={};% initiate list of projected variables for cell # icell
1226    VarDimName={};% initiate coresponding list of dimensions for cell # icell
1227    VarAttribute={};% initiate coresponding list of var attributes  for cell # icell
1228    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1229    switch CellInfo{icell}.CoordType
1230       
1231        case 'scattered'
1232            %% case of input fields with unstructured coordinates (applies for projMode ='projection' or 'interp_lin')
1233            if strcmp(ProjMode{icell},'interp_tps')
1234                continue %skip for next cell (needs tps field cell)
1235            end
1236            coord_x=FieldData.(CellInfo{icell}.XName);% initial x coordinates
1237            coord_y=FieldData.(CellInfo{icell}.YName);% initial y coordinates
1238            check3D=(numel(CellInfo{icell}.CoordIndex)==3);
1239            if check3D
1240                coord_z=FieldData.(CellInfo{icell}.ZName);
1241            end
1242           
1243            % translate  initial coordinates to account for the new origin
1244            coord_x=coord_x-ObjectData.Coord(1,1);
1245            coord_y=coord_y-ObjectData.Coord(1,2);
1246            if check3D
1247                coord_z=coord_z-ObjectData.Coord(1,3);
1248            end
1249           
1250            % selection of the vectors in the projection range (3D case)
1251            if check3D &&  width > 0
1252                %components of the unitiy vector normal to the projection plane
1253                fieldZ=norm_plane(1)*coord_x + norm_plane(2)*coord_y+ norm_plane(3)*coord_z;% distance to the plane
1254                indcut=find(abs(fieldZ) <= width);
1255                for ivar=[CellInfo{icell}.CoordIndex CellInfo{icell}.VarIndex]
1256                    VarName=FieldData.ListVarName{ivar};
1257                    FieldData.(VarName)=FieldData.(VarName)(indcut);
1258                end
1259                coord_x=coord_x(indcut);
1260                coord_y=coord_y(indcut);
1261                coord_z=coord_z(indcut);
1262            end
1263           
1264            %rotate coordinates if needed: coord_X,coord_Y= = coordinates in the new plane
1265            Phi=PlaneAngle(1);
1266            %             Theta=PlaneAngle(2);
1267            % Phi=PlaneAngle(3);
1268            if testangle && ~test90y && ~test90x;%=1 for slanted plane
1269                coord_X=coord_x *cos(Phi) + coord_y* sin(Phi);
1270                coord_Y=-coord_x *sin(Phi) + coord_y *cos(Phi);
1271                if checkM2
1272                    coord_Y=coord_Y*cos(PlaneAngle(2));
1273                    coord_Y=coord_Y+coord_z *sin(PlaneAngle(2));
1274                    coord_X=(coord_X *cos(Psi) - coord_Y* sin(Psi));%A VERIFIER
1275                    coord_Y=(coord_X *sin(Psi) + coord_Y* cos(Psi));
1276                end
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=[CellInfo{icell}.CoordIndex CellInfo{icell}.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=[CellInfo{icell}.CoordIndex CellInfo{icell}.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 strcmp(CellInfo{icell}.VarType,'vector')
1404                    FieldVar=cat(3,FieldData.(FieldData.ListVarName{CellInfo{icell}.VarIndex_vector_x}),FieldData.(FieldData.ListVarName{CellInfo{icell}.VarIndex_vector_y}));
1405                    checkUV=1;
1406                end
1407               
1408                %rotate coordinates if needed: coord_X,coord_Y= = coordinates in the new plane
1409                Phi=PlaneAngle(1);
1410                if testangle && ~test90y && ~test90x;%=1 for slanted plane
1411                    new_XI=XI *cos(Phi) - YI* sin(Phi)+ObjectData.Coord(1);
1412                    YI=XI *sin(Phi) + YI *cos(Phi)+ObjectData.Coord(2);
1413                    XI=new_XI;
1414                end
1415               
1416                % interpolate data using thin plate spline
1417                [DataOut,VarAttribute,errormsg]=calc_field_tps(Coord,NbCentres,SubRange,FieldVar,CellInfo{icell}.FieldName,cat(3,XI,YI));
1418               
1419                % set to NaN interpolation points which are too far from any initial data (more than 2 CoordMesh)
1420                Coord=permute(Coord,[1 3 2]);
1421                Coord=reshape(Coord,size(Coord,1)*size(Coord,2),2);
1422                if exist('scatteredInterpolant','file')%recent Matlab versions
1423                    F=scatteredInterpolant(Coord,Coord(:,1),'nearest');
1424                    G=scatteredInterpolant(Coord,Coord(:,2),'nearest');
1425                else
1426                    F=TriScatteredInterp(Coord,Coord(:,1),'nearest');
1427                    G=TriScatteredInterp(Coord,Coord(:,2),'nearest');
1428                end
1429                Distx=F(XI,YI)-XI;% diff of x coordinates with the nearest measurement point
1430                Disty=G(XI,YI)-YI;% diff of y coordinates with the nearest measurement point
1431                Dist=Distx.*Distx+Disty.*Disty;
1432                ListVarName=(fieldnames(DataOut))';
1433                VarDimName=cell(size(ListVarName));
1434                for ilist=1:numel(ListVarName)% reshape data, excluding coordinates (ilist=1-2), TODO: rationalise
1435                    VarName=ListVarName{ilist};
1436                    VarDimName{ilist}={'coord_y','coord_x'};
1437                    ProjData.(VarName)=DataOut.(VarName);
1438                    if ~isempty(thresh2)
1439                        ProjData.(VarName)(Dist>thresh2)=NaN;% put to NaN interpolated positions further than RangeInterp from initial data
1440                    end
1441                end
1442            end
1443           
1444        case 'grid'
1445            %% case of input fields defined on a structured  grid
1446            VarName=FieldData.ListVarName{VarIndex(1)};%get the first variable of the cell to get the input matrix dimensions
1447            DimValue=size(FieldData.(VarName));%input matrix dimensions
1448            DimValue(DimValue==1)=[];%remove singleton dimensions
1449            NbDim=numel(DimValue);%update number of space dimensions
1450            % nbcolor=1; %default number of 'color' components: third matrix index without corresponding coordinate
1451            if NbDim>=3
1452                if NbDim>3
1453                    errormsg='matrices with more than 3 dimensions not handled';
1454                    return
1455                else
1456                    if numel(CellInfo{icell}.CoordIndex)==2% the third matrix dimension does not correspond to a space coordinate
1457                        nbcolor=DimValue(3);
1458                        DimValue(3)=[]; %number of 'color' components updated
1459                        NbDim=2;% space dimension set to 2
1460                    end
1461                end
1462            end
1463            Coord_z=[];
1464            Coord_y=[];
1465            Coord_x=[];
1466           
1467            if testangle
1468                ProjMode{icell}='interp_lin'; %request linear interpolation for projection on a tilted plane
1469            end
1470           
1471            if isequal(ProjMode{icell},'projection')% && (~testangle || test90y || test90x)
1472                if  NbDim==2 && ~testXMin && ~testXMax && ~testYMin && ~testYMax% no range restriction
1473                    ListVarName=[ListVarName FieldData.ListVarName(VarIndex)];
1474                    VarDimName=[VarDimName FieldData.VarDimName(VarIndex)];
1475                    if isfield(FieldData,'VarAttribute')
1476                        VarAttribute=[VarAttribute FieldData.VarAttribute(VarIndex)];
1477                    end
1478                    ProjData.(AYName)=FieldData.(AYName);
1479                    ProjData.(AXName)=FieldData.(AXName);
1480                    for ivar=VarIndex
1481                        VarName=FieldData.ListVarName{ivar};
1482                        ProjData.(VarName)=FieldData.(VarName);% no change by projection
1483                    end
1484                else
1485                    Coord{1}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(1)});
1486                    Coord{2}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(2)});
1487                    if NbDim==3
1488                        Coord{3}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(3)});
1489                    end
1490                    if numel(Coord{NbDim-1})==2% case of coordinate defined only by the first and last values
1491                        DY=(Coord{NbDim-1}(2)-Coord{NbDim-1}(1))/(DimValue(1)-1);
1492                    end
1493                    if numel(Coord{NbDim})==2% case of coordinate defined only by the first and last values
1494                        DX=(Coord{NbDim}(2)-Coord{NbDim}(1))/(DimValue(2)-1);
1495                    end
1496                    if testYMax
1497                        YIndexMax=(YMax-Coord{NbDim-1}(1))/DY+1;% matrix index corresponding to the max y value for the new field
1498                        if testYMin%test_direct(indY)
1499                            YIndexMin=(YMin-Coord{NbDim-1}(1))/DY+1;% matrix index corresponding to the min x value for the new field
1500                        else
1501                            YIndexMin=1;
1502                        end
1503                    else
1504                        YIndexMax=numel(Coord{NbDim-1});
1505                        YIndexMin=1;
1506                    end
1507                    if testXMax
1508                        XIndexMax=(XMax-Coord{NbDim}(1))/DX+1;% matrix index corresponding to the max y value for the new field
1509                        if testYMin%test_direct(indY)
1510                            XIndexMin=(XMin-Coord{NbDim}(1))/DX+1;% matrix index corresponding to the min x value for the new field
1511                        else
1512                            XIndexMin=1;
1513                        end
1514                    else
1515                        XIndexMax=numel(Coord{NbDim});
1516                        XIndexMin=1;
1517                    end
1518                    YIndexRange(1)=ceil(min(YIndexMin,YIndexMax));%first y index to select from the previous field
1519                    YIndexRange(1)=max(YIndexRange(1),1);% avoid bound lower than the first index
1520                    YIndexRange(2)=floor(max(YIndexMin,YIndexMax));%last y index to select from the previous field
1521                    YIndexRange(2)=min(YIndexRange(2),DimValue(NbDim-1));% limit to the last available index
1522                    XIndexRange(1)=ceil(min(XIndexMin,XIndexMax));%first x index to select from the previous field
1523                    XIndexRange(1)=max(XIndexRange(1),1);% avoid bound lower than the first index
1524                    XIndexRange(2)=floor(max(XIndexMin,XIndexMax));%last x index to select from the previous field
1525                    XIndexRange(2)=min(XIndexRange(2),DimValue(NbDim));% limit to the last available index
1526                    if test90y
1527                        ind_new=[3 2 1];
1528                        DimCell={AYProjName,AXProjName};
1529                        iz=ceil((ObjectData.Coord(1,1)-Coord{3}(1))/DX)+1;
1530                        for ivar=VarIndex
1531                            VarName=FieldData.ListVarName{ivar};
1532                            ListVarName=[ListVarName VarName];
1533                            VarDimName=[VarDimName {DimCell}];
1534                            VarAttribute{length(ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes
1535                            ProjData.(VarName)=permute(FieldData.(VarName),ind_new);% permute x and z indices for 90 degree rotation
1536                            ProjData.(VarName)=squeeze(ProjData.(VarName)(iz,:,:));% select the z index iz
1537                        end
1538                        ProjData.(AYName)=[Ybound(1) Ybound(2)]; %record the new (projected ) y coordinates
1539                        ProjData.(AXName)=[Coord{1}(end),Coord{1}(1)]; %record the new (projected ) x coordinates
1540                    else
1541                        if NbDim==3
1542                            DZ=(Coord{1}(end)-Coord{1}(1))/(numel(Coord{1})-1);
1543                            DimCell(1)=[]; %suppress z variable
1544                            DimValue(1)=[];
1545                            test_direct=1;%TOdo; GENERALIZE, SEE CASE OF points
1546                            if test_direct(1)
1547                                iz=ceil((ObjectData.Coord(1,3)-Coord{1}(1))/DZ)+1;
1548                            else
1549                                iz=ceil((Coord{1}(1)-ObjectData.Coord(1,3))/DZ)+1;
1550                            end
1551                        end
1552                        for ivar=VarIndex% loop on non coordinate variables
1553                            VarName=FieldData.ListVarName{ivar};
1554                            ListVarName=[ListVarName VarName];
1555                            VarDimName=[VarDimName {DimCell}];
1556                            if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute)>=ivar
1557                                VarAttribute{length(ListVarName)}=FieldData.VarAttribute{ivar};
1558                            end
1559                            if NbDim==3
1560                                ProjData.(VarName)=squeeze(FieldData.(VarName)(iz,YIndexRange(1):YIndexRange(end),XIndexRange(1):XIndexRange(end)));
1561                            else
1562                                ProjData.(VarName)=FieldData.(VarName)(YIndexRange(1):YIndexRange(end),XIndexRange(1):XIndexRange(end),:);
1563                            end
1564                        end
1565                        if testXMax
1566                            ProjData.(AXName)=Coord{NbDim}(1)+DX*(XIndexRange-1); %record the new (projected ) x coordinates
1567                        else
1568                            ProjData.(AXName)=FieldData.(AXName);
1569                        end
1570                        if testYMax
1571                            ProjData.(AYName)=Coord{NbDim-1}(1)+DY*(YIndexRange-1); %record the new (projected ) x coordinates
1572                        else
1573                            ProjData.(AYName)=FieldData.(AYName);
1574                        end
1575                    end
1576                end
1577            else       % case with interpolation on a grid
1578                if NbDim==2 %2D case
1579                    if isequal(ProjMode{icell},'interp_tps')
1580                        npx_interp_tps=ceil(abs(DX/DAX));
1581                        npy_interp_tps=ceil(abs(DY/DAY));
1582                        Minterp_tps=ones(npy_interp_tps,npx_interp_tps)/(npx_interp_tps*npy_interp_tps);
1583                        test_interp_tps=1;
1584                    else
1585                        test_interp_tps=0;
1586                    end
1587                    Coord{1}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(1)});
1588                    Coord{2}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(2)});
1589                    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
1590                        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
1591                        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
1592                        xcor_new=xcorner*cos(PlaneAngle(3))+ycorner*sin(PlaneAngle(3));%coordinates of the corners in new frame
1593                        ycor_new=-xcorner*sin(PlaneAngle(3))+ycorner*cos(PlaneAngle(3));
1594                        if ~testXMin
1595                            XMin=min(xcor_new);
1596                        end
1597                        if ~testXMax
1598                            XMax=max(xcor_new);
1599                        end
1600                        if ~testYMin
1601                            YMin=min(ycor_new);
1602                        end
1603                        if ~testYMax
1604                            YMax=max(ycor_new);
1605                        end
1606                    end
1607                    coord_x_proj=XMin:DX:XMax;
1608                    coord_y_proj=YMin:DY:YMax;
1609                    ProjData.(AYName)=[coord_y_proj(1) coord_y_proj(end)]; %record the new (projected ) y coordinates
1610                    ProjData.(AXName)=[coord_x_proj(1) coord_x_proj(end)]; %record the new (projected ) x coordinates
1611                    [X,YI]=meshgrid(coord_x_proj,coord_y_proj);%grid in the new coordinates
1612                    XI=ObjectData.Coord(1,1)+(X)*cos(PlaneAngle(2))-YI*sin(PlaneAngle(1));%corresponding coordinates in the original system
1613                    YI=ObjectData.Coord(1,2)+(X)*sin(PlaneAngle(2))+YI*cos(PlaneAngle(1));
1614                   
1615                    if numel(Coord{1})==2% x coordinate defined by its bounds, get the whole set
1616                        Coord{1}=linspace(Coord{1}(1),Coord{1}(2),CellInfo{icell}.CoordSize(1));
1617                    end
1618                    if numel(Coord{2})==2% y coordiante defiend by its bounds, get the whole set
1619                        Coord{2}=linspace(Coord{2}(1),Coord{2}(2),CellInfo{icell}.CoordSize(2));
1620                    end
1621                    [X,Y]=meshgrid(Coord{2},Coord{1});%initial coordinates
1622                    %name of error flag variable
1623                    FFName='FF';%default name (if not already used)
1624                    if isfield(ProjData,'FF')
1625                        ind=1;
1626                        while isfield(ProjData,['FF_' num2str(ind)])
1627                            ind=ind+1;
1628                        end
1629                        FFName=['FF_' num2str(ind)];% append an index to the name of error flag, FF_1,FF_2...
1630                    end
1631                    % project all variables in the cell
1632                    for ivar=VarIndex
1633                        VarName=FieldData.ListVarName{ivar};
1634                        if size(FieldData.(VarName),3)==1
1635                            ProjData.(VarName)=interp2(X,Y,double(FieldData.(VarName)),XI,YI,'*linear');%interpolation fct
1636                        else
1637                            ProjData.(VarName)=interp2(X,Y,double(FieldData.(VarName)(:,:,1)),XI,YI,'*linear');
1638                            for icolor=2:size(FieldData.(VarName),3)% project 'color' components
1639                                ProjData.(VarName)=cat(3,ProjData.(VarName),interp2(X,Y,double(FieldData.(VarName)(:,:,icolor)),XI,YI,'*linear'));
1640                            end
1641                        end
1642                        if isa(FieldData.(VarName),'uint8')
1643                            ProjData.(VarName)=uint8(ProjData.(VarName));%put result to integer 8 bits if the initial field is integer (image)
1644                        elseif isa(FieldData.(VarName),'uint16')
1645                            ProjData.(VarName)=uint16(ProjData.(VarName));%put result to integer 16 bits if the initial field is integer (image)
1646                        end
1647                        ListVarName=[ListVarName VarName];
1648                        DimCell(1:2)={AYName,AXName};
1649                        VarDimName=[VarDimName {DimCell}];
1650                        if isfield(FieldData,'VarAttribute')&&length(FieldData.VarAttribute)>=ivar
1651                            VarAttribute{length(ListVarName)+nbcoord}=FieldData.VarAttribute{ivar};
1652                        end;
1653                        ProjData.(FFName)=isnan(ProjData.(VarName));%detact NaN (points outside the interpolation range)
1654                        ProjData.(VarName)(ProjData.(FFName))=0; %set to 0 the NaN data
1655                    end
1656                    %update list of variables with error flag
1657                    ListVarName=[ListVarName FFName];
1658                    VarDimName=[VarDimName {DimCell}];
1659                    VarAttribute{numel(ListVarName)}.Role='errorflag';
1660                elseif ~testangle
1661                    % unstructured z coordinate
1662                    test_sup=(Coord{1}>=ObjectData.Coord(1,3));
1663                    iz_sup=find(test_sup);
1664                    iz=iz_sup(1);
1665                    if iz>=1 & iz<=npz
1666                        %ProjData.ListDimName=[ProjData.ListDimName ListDimName(2:end)];
1667                        %ProjData.DimValue=[ProjData.DimValue npY npX];
1668                        for ivar=VarIndex
1669                            VarName=FieldData.ListVarName{ivar};
1670                            ListVarName=[ListVarName VarName];
1671                            VarAttribute{length(ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes
1672                            ProjData.(VarName)=squeeze(FieldData.(VarName)(iz,:,:));% select the z index iz
1673                            %TODO : do a vertical average for a thick plane
1674                            if test_interp(2) || test_interp(3)
1675                                ProjData.(VarName)=interp2(Coord{3},Coord{2},ProjData.(VarName),Coord_x,Coord_y);
1676                            end
1677                        end
1678                    end
1679                else   %projection of structured coordinates on oblique plane
1680                    % determine the boundaries of the projected field,
1681                    % first find the 8 summits of the initial volume in the
1682                    PlaneAngle=ObjectData.Angle*pi/180;
1683                    % new coordinates
1684                    Coord{1}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(1)});%initial z coordinates
1685                    Coord{2}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(2)});%initial y coordinates
1686                    Coord{3}=FieldData.(FieldData.ListVarName{CellInfo{icell}.CoordIndex(3)});%initial x coordinates
1687                    summit=zeros(3,8);% initialize summit coordinates
1688                    summit(1,1:4)=[Coord{3}(1) Coord{3}(end) Coord{3}(1) Coord{3}(end)];%square
1689                    summit(2,1:4)=[Coord{2}(1) Coord{2}(1) Coord{2}(end) Coord{2}(end)];% square at z= Coord{1}(1)
1690                    summit(1:2,5:8)=summit(1:2,1:4);
1691                    summit(3,:)=[Coord{1}(1)*ones(1,4) Coord{1}(end)*ones(1,4)];
1692                    %Mrot_inv=rodrigues(-PlaneAngle);
1693                    newsummit=zeros(3,8);% initialize the rotated summit coordinates
1694                    ObjectData.Coord=ObjectData.Coord';% set ObjectData.Coord as a vertical vector
1695                    if size(ObjectData.Coord,1)<3
1696                        ObjectData.Coord=[ObjectData.Coord; 0];%add z origin at z=0 by default
1697                    end
1698                   
1699                    M1=[cos(PlaneAngle(1)) sin(PlaneAngle(1)) 0;-sin(PlaneAngle(1)) cos(PlaneAngle(1)) 0;0 0 1];
1700                    M2=[1 0 0;0 cos(PlaneAngle(2)) sin(PlaneAngle(2));0 -sin(PlaneAngle(2)) cos(PlaneAngle(2))];
1701                    M=M2*M1;
1702                    M_inv=inv(M);
1703                   
1704                    for isummit=1:8% TODO: introduce a function for rotation of n points (to use also for scattered data)
1705                        newsummit(:,isummit)=M*(summit(:,isummit)-(ObjectData.Coord));
1706                    end
1707                    coord_x_proj=min(newsummit(1,:)):InterpMesh: max(newsummit(1,:));% set of coordinqtes in the projection plane
1708                    coord_y_proj=min(newsummit(2,:)):InterpMesh: max(newsummit(2,:));
1709                    coord_z_proj=-width:width;
1710                    %Mrot=rodrigues(PlaneAngle);% inverse rotation matrix
1711                    Origin=M_inv*[coord_x_proj(1);coord_y_proj(1);coord_z_proj(1)]+ObjectData.Coord;
1712                    npx=numel(coord_x_proj);
1713                    npy=numel(coord_y_proj);
1714                    npz=numel(coord_z_proj);
1715                   
1716                    %modangle=sqrt(PlaneAngle(1)*PlaneAngle(1)+PlaneAngle(2)*PlaneAngle(2));
1717                    %                     cosphi=PlaneAngle(1)/modangle;
1718                    %                     sinphi=PlaneAngle(2)/modangle;
1719                    iX=[coord_x_proj(end)-coord_x_proj(1);0;0]/(npx-1);
1720                    iY=[0;coord_y_proj(end)-coord_y_proj(1);0]/(npy-1);
1721                    iZ=[0;0;coord_z_proj(end)-coord_z_proj(1)]/(npz-1);
1722                    %                     iX(1:2)=[cosphi -sinphi;sinphi cosphi]*iX(1:2);
1723                    %                     iY(1:2)=[-cosphi -sinphi;sinphi cosphi]*iY(1:2);
1724                   
1725                    ix=M_inv*iX;%  vector along the new x coordinates transformed into old coordinates
1726                    iy=M_inv*iY;% vector along y coordinates
1727                    iz=M_inv*iZ;% vector along z coordinates
1728                   
1729                    [Grid_x,Grid_y,Grid_z]=meshgrid(0:npx-1,0:npy-1,0:npz-1);
1730                    if ismatrix(Grid_x)% add a singleton in case of a single z value
1731                        Grid_x=shiftdim(Grid_x,-1);
1732                        Grid_y=shiftdim(Grid_y,-1);
1733                        Grid_z=shiftdim(Grid_z,-1);
1734                    end
1735                    XI=Origin(1)+ix(1)*Grid_x+iy(1)*Grid_y+iz(1)*Grid_z;
1736                    YI=Origin(2)+ix(2)*Grid_x+iy(2)*Grid_y+iz(2)*Grid_z;
1737                    ZI=Origin(3)+ix(3)*Grid_x+iy(3)*Grid_y+iz(3)*Grid_z;
1738                    [X,Y,Z]=meshgrid(Coord{3},Coord{2},Coord{1});% mesh in the initial coordinates
1739                    for ivar=VarIndex
1740                        VarName=FieldData.ListVarName{ivar};
1741                        ListVarName=[ListVarName VarName];
1742                        VarDimName=[VarDimName {{'coord_y','coord_x'}}];
1743                        VarAttribute{length(ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes
1744                        FieldData.(VarName)=permute(FieldData.(VarName),[2 3 1]);
1745                        ProjData.coord_x=coord_x_proj;
1746                        ProjData.coord_y=coord_y_proj;
1747                        ProjData.(VarName)=interp3(X,Y,Z,double(FieldData.(VarName)),XI,YI,ZI,'*linear');
1748                        ProjData.(VarName)=nanmean(ProjData.(VarName),3);
1749                        ProjData.(VarName)=squeeze(ProjData.(VarName));
1750                    end
1751                end
1752            end
1753    end
1754    % update the global list of projected variables:
1755    ProjData.ListVarName=[ProjData.ListVarName ListVarName];
1756    ProjData.VarDimName=[ProjData.VarDimName VarDimName];
1757    ProjData.VarAttribute=[ProjData.VarAttribute VarAttribute];
1758   
1759    %% projection of  velocity components in the rotated coordinates
1760    if testangle
1761        ivar_U=[];ivar_V=[];ivar_W=[];
1762        for ivar=1:numel(VarAttribute)
1763            if isfield(VarAttribute{ivar},'Role')
1764                if strcmp(VarAttribute{ivar}.Role,'vector_x')
1765                    ivar_U=ivar;
1766                elseif strcmp(VarAttribute{ivar}.Role,'vector_y')
1767                    ivar_V=ivar;
1768                elseif strcmp(VarAttribute{ivar}.Role,'vector_z')
1769                    ivar_W=ivar;
1770                end
1771            end
1772        end
1773        if ~isempty(ivar_U)
1774            if isempty(ivar_V)
1775                msgbox_uvmat('ERROR','v velocity component missing in proj_field.m')
1776                return
1777            else
1778                UName=ListVarName{ivar_U};
1779                VName=ListVarName{ivar_V};
1780                if checkM2
1781                    UValue=cos(PlaneAngle(1))*ProjData.(UName)+ sin(PlaneAngle(1))*ProjData.(VName);
1782                    ProjData.(VName)=(-sin(PlaneAngle(1))*ProjData.(UName)+ cos(PlaneAngle(1))*ProjData.(VName));
1783                else
1784                    UValue=cos(PlaneAngle(1))*ProjData.(UName)+ sin(PlaneAngle(1))*ProjData.(VName);
1785                    ProjData.(VName)=(-sin(PlaneAngle(1))*ProjData.(UName)+ cos(PlaneAngle(1))*ProjData.(VName));
1786                end
1787                ProjData.(UName)=UValue;
1788                if ~isempty(ivar_W)
1789                    WName=FieldData.ListVarName{ivar_W};
1790                    VValue=ProjData.(VName)+ ProjData.(WName)*sin(Theta);%
1791                    ProjData.(WName)=NormVec_X*ProjData.(UName)+ NormVec_Y*ProjData.(VName)+ NormVec_Z* ProjData.(WName);
1792                    ProjData.(VName)=VValue;
1793                end
1794            end
1795        end
1796    end
1797end
1798% %prepare substraction in case of two input fields
1799% SubData.ListVarName={};
1800% SubData.VarDimName={};
1801% SubData.VarAttribute={};
1802% check_remove=zeros(size(ProjData.ListVarName));
1803% for iproj=1:numel(ProjData.VarAttribute)
1804%     if isfield(ProjData.VarAttribute{iproj},'CheckSub')&&isequal(ProjData.VarAttribute{iproj}.CheckSub,1)
1805%         VarName=ProjData.ListVarName{iproj};
1806%         SubData.ListVarName=[SubData.ListVarName {VarName}];
1807%         SubData.VarDimName=[SubData.VarDimName ProjData.VarDimName{iproj}];
1808%         SubData.VarAttribute=[SubData.VarAttribute ProjData.VarAttribute{iproj}];
1809%         SubData.(VarName)=ProjData.(VarName);
1810%         check_remove(iproj)=1;
1811%     end
1812% end
1813% if ~isempty(find(check_remove))
1814%     ind_remove=find(check_remove);
1815%     ProjData.ListVarName(ind_remove)=[];
1816%     ProjData.VarDimName(ind_remove)=[];
1817%     ProjData.VarAttribute(ind_remove)=[];
1818%     ProjData=sub_field(ProjData,[],SubData);
1819% end
1820
1821%-----------------------------------------------------------------
1822%projection in a volume
1823function  [ProjData,errormsg] = proj_volume(FieldData, ObjectData)
1824
1825%-----------------------------------------------------------------
1826ProjData=FieldData;%default output
1827
1828%% axis origin
1829if isempty(ObjectData.Coord)
1830    ObjectData.Coord(1,1)=0;%origin of the plane set to [0 0] by default
1831    ObjectData.Coord(1,2)=0;
1832    ObjectData.Coord(1,3)=0;
1833end
1834
1835%% rotation angles
1836VolumeAngle=[0 0 0];
1837norm_plane=[0 0 1];
1838if isfield(ObjectData,'Angle')&& isequal(size(ObjectData.Angle),[1 3])&& ~isequal(ObjectData.Angle,[0 0 0])
1839    PlaneAngle=ObjectData.Angle;
1840    VolumeAngle=ObjectData.Angle;
1841    om=norm(VolumeAngle);%norm of rotation angle in radians
1842    OmAxis=VolumeAngle/om; %unit vector marking the rotation axis
1843    cos_om=cos(pi*om/180);
1844    sin_om=sin(pi*om/180);
1845    coeff=OmAxis(3)*(1-cos_om);
1846    %components of the unity vector norm_plane normal to the projection plane
1847    norm_plane(1)=OmAxis(1)*coeff+OmAxis(2)*sin_om;
1848    norm_plane(2)=OmAxis(2)*coeff-OmAxis(1)*sin_om;
1849    norm_plane(3)=OmAxis(3)*coeff+cos_om;
1850end
1851testangle=~isequal(VolumeAngle,[0 0 0]);
1852
1853%% mesh sizes DX, DY, DZ
1854DX=0;
1855DY=0; %default
1856DZ=0;
1857if isfield(ObjectData,'DX')&~isempty(ObjectData.DX)
1858     DX=abs(ObjectData.DX);%mesh of interpolation points
1859end
1860if isfield(ObjectData,'DY')&~isempty(ObjectData.DY)
1861     DY=abs(ObjectData.DY);%mesh of interpolation points
1862end
1863if isfield(ObjectData,'DZ')&~isempty(ObjectData.DZ)
1864     DZ=abs(ObjectData.DZ);%mesh of interpolation points
1865end
1866if  ~strcmp(ProjMode,'projection') && (DX==0||DY==0||DZ==0)
1867        errormsg='grid mesh DX , DY or DZ is missing';
1868        return
1869end
1870
1871%% extrema along each axis
1872testXMin=0;
1873testXMax=0;
1874testYMin=0;
1875testYMax=0;
1876if isfield(ObjectData,'RangeX')
1877        XMin=min(ObjectData.RangeX);
1878        XMax=max(ObjectData.RangeX);
1879        testXMin=XMax>XMin;
1880        testXMax=1;
1881end
1882if isfield(ObjectData,'RangeY')
1883        YMin=min(ObjectData.RangeY);
1884        YMax=max(ObjectData.RangeY);
1885        testYMin=YMax>YMin;
1886        testYMax=1;
1887end
1888width=0;%default width of the projection band
1889if isfield(ObjectData,'RangeZ')
1890        ZMin=min(ObjectData.RangeZ);
1891        ZMax=max(ObjectData.RangeZ);
1892        testZMin=ZMax>ZMin;
1893        testZMax=1;
1894end
1895
1896%% initiate Matlab  structure for physical field
1897[ProjData,errormsg]=proj_heading(FieldData,ObjectData);
1898if ~isempty(errormsg)
1899    return
1900end
1901
1902ProjData.NbDim=3;
1903ProjData.ListVarName={};
1904ProjData.VarDimName={};
1905if ~isequal(DX,0)&& ~isequal(DY,0)
1906    ProjData.CoordMesh=sqrt(DX*DY);%define typical data mesh, useful for mouse selection in plots
1907elseif isfield(FieldData,'CoordMesh')
1908    ProjData.CoordMesh=FieldData.CoordMesh;
1909end
1910
1911error=0;%default
1912flux=0;
1913testfalse=0;
1914ListIndex={};
1915
1916%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1917%% group the variables (fields of 'FieldData') in cells of variables with the same dimensions
1918%-----------------------------------------------------------------
1919idimvar=0;
1920% LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
1921% CellVarIndex=cells of variable index arrays
1922ivar_new=0; % index of the current variable in the projected field
1923icoord=0;
1924nbcoord=0;%number of added coordinate variables brought by projection
1925nbvar=0;
1926for icell=1:length(CellVarIndex)
1927    NbDim=NbDimVec(icell);
1928    if NbDim<3
1929        continue
1930    end
1931    VarIndex=CellVarIndex{icell};%  indices of the selected variables in the list FieldData.ListVarName
1932    VarType=VarTypeCell{icell};
1933    ivar_X=VarType.coord_x;
1934    ivar_Y=VarType.coord_y;
1935    ivar_Z=VarType.coord_z;
1936    ivar_U=VarType.vector_x;
1937    ivar_V=VarType.vector_y;
1938    ivar_W=VarType.vector_z;
1939    ivar_C=VarType.scalar ;
1940    ivar_Anc=VarType.ancillary;
1941    test_anc=zeros(size(VarIndex));
1942    test_anc(ivar_Anc)=ones(size(ivar_Anc));
1943    ivar_F=VarType.warnflag;
1944    ivar_FF=VarType.errorflag;
1945    check_unstructured_coord=~isempty(ivar_X) && ~isempty(ivar_Y);
1946    DimCell=FieldData.VarDimName{VarIndex(1)};
1947    if ischar(DimCell)
1948        DimCell={DimCell};%name of dimensions
1949    end
1950
1951%% case of input fields with unstructured coordinates
1952    if check_unstructured_coord
1953        XName=FieldData.ListVarName{ivar_X};
1954        YName=FieldData.ListVarName{ivar_Y};
1955        eval(['coord_x=FieldData.' XName ';'])
1956        eval(['coord_y=FieldData.' YName ';'])
1957        if length(ivar_Z)==1
1958            ZName=FieldData.ListVarName{ivar_Z};
1959            eval(['coord_z=FieldData.' ZName ';'])
1960        end
1961
1962        % translate  initial coordinates
1963        coord_x=coord_x-ObjectData.Coord(1,1);
1964        coord_y=coord_y-ObjectData.Coord(1,2);
1965        if ~isempty(ivar_Z)
1966            coord_z=coord_z-ObjectData.Coord(1,3);
1967        end
1968       
1969        % selection of the vectors in the projection range
1970%         if length(ivar_Z)==1 &&  width > 0
1971%             %components of the unitiy vector normal to the projection plane
1972%             fieldZ=NormVec_X*coord_x + NormVec_Y*coord_y+ NormVec_Z*coord_z;% distance to the plane           
1973%             indcut=find(abs(fieldZ) <= width);
1974%             for ivar=VarIndex
1975%                 VarName=FieldData.ListVarName{ivar};
1976%                 eval(['FieldData.' VarName '=FieldData.' VarName '(indcut);']) 
1977%                     % A VOIR : CAS DE VAR STRUCTUREE MAIS PAS GRILLE REGULIERE : INTERPOLER SUR GRILLE REGULIERE             
1978%             end
1979%             coord_x=coord_x(indcut);
1980%             coord_y=coord_y(indcut);
1981%             coord_z=coord_z(indcut);
1982%         end
1983
1984       %rotate coordinates if needed: TODO modify
1985       if testangle
1986           coord_X=(coord_x *cos(Phi) + coord_y* sin(Phi));
1987           coord_Y=(-coord_x *sin(Phi) + coord_y *cos(Phi))*cos(Theta);
1988           if ~isempty(ivar_Z)
1989               coord_Y=coord_Y+coord_z *sin(Theta);
1990           end
1991           
1992           coord_X=(coord_X *cos(Psi) - coord_Y* sin(Psi));%A VERIFIER
1993           coord_Y=(coord_X *sin(Psi) + coord_Y* cos(Psi));
1994           
1995       else
1996           coord_X=coord_x;
1997           coord_Y=coord_y;
1998           coord_Z=coord_z;
1999       end
2000        %restriction to the range of x and y if imposed
2001        testin=ones(size(coord_X)); %default
2002        testbound=0;
2003        if testXMin
2004            testin=testin & (coord_X >= XMin);
2005            testbound=1;
2006        end
2007        if testXMax
2008            testin=testin & (coord_X <= XMax);
2009            testbound=1;
2010        end
2011        if testYMin
2012            testin=testin & (coord_Y >= YMin);
2013            testbound=1;
2014        end
2015        if testYMax
2016            testin=testin & (coord_Y <= YMax);
2017            testbound=1;
2018        end
2019        if testbound
2020            indcut=find(testin);
2021            for ivar=VarIndex
2022                VarName=FieldData.ListVarName{ivar};
2023                eval(['FieldData.' VarName '=FieldData.' VarName '(indcut);'])           
2024            end
2025            coord_X=coord_X(indcut);
2026            coord_Y=coord_Y(indcut);
2027            if length(ivar_Z)==1
2028                coord_Z=coord_Z(indcut);
2029            end
2030        end
2031        % different cases of projection
2032        if isequal(ObjectData.ProjMode,'projection')%%%%%%%   NOT USED %%%%%%%%%%
2033            for ivar=VarIndex %transfer variables to the projection plane
2034                VarName=FieldData.ListVarName{ivar};
2035                if ivar==ivar_X %x coordinate
2036                    eval(['ProjData.' VarName '=coord_X;'])
2037                elseif ivar==ivar_Y % y coordinate
2038                    eval(['ProjData.' VarName '=coord_Y;'])
2039                elseif isempty(ivar_Z) || ivar~=ivar_Z % other variables (except Z coordinate wyhich is not reproduced)
2040                    eval(['ProjData.' VarName '=FieldData.' VarName ';'])
2041                end
2042                if isempty(ivar_Z) || ivar~=ivar_Z
2043                    ProjData.ListVarName=[ProjData.ListVarName VarName];
2044                    ProjData.VarDimName=[ProjData.VarDimName DimCell];
2045                    nbvar=nbvar+1;
2046                    if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute) >=ivar
2047                        ProjData.VarAttribute{nbvar}=FieldData.VarAttribute{ivar};
2048                    end
2049                end
2050            end 
2051        elseif isequal(ObjectData.ProjMode,'interp_lin')||isequal(ObjectData.ProjMode,'interp_tps')%interpolate data on a regular grid
2052            coord_x_proj=XMin:DX:XMax;
2053            coord_y_proj=YMin:DY:YMax;
2054            coord_z_proj=ZMin:DZ:ZMax;
2055            DimCell={'coord_z','coord_y','coord_x'};
2056            ProjData.ListVarName={'coord_z','coord_y','coord_x'};
2057            ProjData.VarDimName={'coord_z','coord_y','coord_x'};   
2058            nbcoord=2; 
2059            ProjData.coord_z=[ZMin ZMax];
2060            ProjData.coord_y=[YMin YMax];
2061            ProjData.coord_x=[XMin XMax];
2062            if isempty(ivar_X), ivar_X=0; end;
2063            if isempty(ivar_Y), ivar_Y=0; end;
2064            if isempty(ivar_Z), ivar_Z=0; end;
2065            if isempty(ivar_U), ivar_U=0; end;
2066            if isempty(ivar_V), ivar_V=0; end;
2067            if isempty(ivar_W), ivar_W=0; end;
2068            if isempty(ivar_F), ivar_F=0; end;
2069            if isempty(ivar_FF), ivar_FF=0; end;
2070            if ~isequal(ivar_FF,0)
2071                VarName_FF=FieldData.ListVarName{ivar_FF};
2072                eval(['indsel=find(FieldData.' VarName_FF '==0);'])
2073                coord_X=coord_X(indsel);
2074                coord_Y=coord_Y(indsel);
2075            end
2076            FF=zeros(1,length(coord_y_proj)*length(coord_x_proj));
2077            testFF=0;
2078            [X,Y,Z]=meshgrid(coord_y_proj,coord_z_proj,coord_x_proj);%grid in the new coordinates
2079            for ivar=VarIndex
2080                VarName=FieldData.ListVarName{ivar};
2081                if ~( ivar==ivar_X || ivar==ivar_Y || ivar==ivar_Z || ivar==ivar_F || ivar==ivar_FF || test_anc(ivar)==1)                 
2082                    ivar_new=ivar_new+1;
2083                    ProjData.ListVarName=[ProjData.ListVarName {VarName}];
2084                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2085                    if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute) >=ivar
2086                        ProjData.VarAttribute{ivar_new+nbcoord}=FieldData.VarAttribute{ivar};
2087                    end
2088                    if  ~isequal(ivar_FF,0)
2089                        eval(['FieldData.' VarName '=FieldData.' VarName '(indsel);'])
2090                    end
2091                    % linear interpolation
2092                    InterpFct=TriScatteredInterp(double(coord_X),double(coord_Y),double(coord_Z),double(FieldData.(VarName)));
2093                    ProjData.(VarName)=InterpFct(X,Y,Z);
2094%                     eval(['varline=reshape(ProjData.' VarName ',1,length(coord_y_proj)*length(coord_x_proj));'])
2095%                     FFlag= isnan(varline); %detect undefined values NaN
2096%                     indnan=find(FFlag);
2097%                     if ~isempty(indnan)
2098%                         varline(indnan)=zeros(size(indnan));
2099%                         eval(['ProjData.' VarName '=reshape(varline,length(coord_y_proj),length(coord_x_proj));'])
2100%                         FF(indnan)=ones(size(indnan));
2101%                         testFF=1;
2102%                     end
2103                    if ivar==ivar_U
2104                        ivar_U=ivar_new;
2105                    end
2106                    if ivar==ivar_V
2107                        ivar_V=ivar_new;
2108                    end
2109                    if ivar==ivar_W
2110                        ivar_W=ivar_new;
2111                    end
2112                end
2113            end
2114            if testFF
2115                ProjData.FF=reshape(FF,length(coord_y_proj),length(coord_x_proj));
2116                ProjData.ListVarName=[ProjData.ListVarName {'FF'}];
2117               ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2118                ProjData.VarAttribute{ivar_new+1+nbcoord}.Role='errorflag';
2119            end
2120        end
2121       
2122%% case of input fields defined on a structured  grid
2123    else
2124        VarName=FieldData.ListVarName{VarIndex(1)};%get the first variable of the cell to get the input matrix dimensions
2125        eval(['DimValue=size(FieldData.' VarName ');'])%input matrix dimensions
2126        DimValue(DimValue==1)=[];%remove singleton dimensions       
2127        NbDim=numel(DimValue);%update number of space dimensions
2128        nbcolor=1; %default number of 'color' components: third matrix index without corresponding coordinate
2129        if NbDim>=3
2130            if NbDim>3
2131                errormsg='matrices with more than 3 dimensions not handled';
2132                return
2133            else
2134                if numel(find(VarType.coord))==2% the third matrix dimension does not correspond to a space coordinate
2135                    nbcolor=DimValue(3);
2136                    DimValue(3)=[]; %number of 'color' components updated
2137                    NbDim=2;% space dimension set to 2
2138                end
2139            end
2140        end
2141        AYName=FieldData.ListVarName{VarType.coord(NbDim-1)};%name of input x coordinate (name preserved on projection)
2142        AXName=FieldData.ListVarName{VarType.coord(NbDim)};%name of input y coordinate (name preserved on projection)   
2143        eval(['AX=FieldData.' AXName ';'])
2144        eval(['AY=FieldData.' AYName ';'])
2145        ListDimName=FieldData.VarDimName{VarIndex(1)};
2146        ProjData.ListVarName=[ProjData.ListVarName {AYName} {AXName}]; %TODO: check if it already exists in Projdata (several cells)
2147        ProjData.VarDimName=[ProjData.VarDimName {AYName} {AXName}];
2148
2149%         for idim=1:length(ListDimName)
2150%             DimName=ListDimName{idim};
2151%             if strcmp(DimName,'rgb')||strcmp(DimName,'nb_coord')||strcmp(DimName,'nb_coord_i')
2152%                nbcolor=DimValue(idim);
2153%                DimValue(idim)=[];
2154%             end
2155%             if isequal(DimName,'nb_coord_j')% NOTE: CASE OF TENSOR NOT TREATED
2156%                 DimValue(idim)=[];
2157%             end
2158%         end 
2159        Coord_z=[];
2160        Coord_y=[];
2161        Coord_x=[];   
2162
2163        for idim=1:NbDim %loop on space dimensions
2164            test_interp(idim)=0;%test for coordiate interpolation (non regular grid), =0 by default
2165            ivar=VarType.coord(idim);% index of the variable corresponding to the current dimension
2166            if ~isequal(ivar,0)%  a variable corresponds to the dimension #idim
2167                eval(['Coord{idim}=FieldData.' FieldData.ListVarName{ivar} ';']) ;% coord values for the input field
2168                if numel(Coord{idim})==2 %input array defined on a regular grid
2169                   DCoord_min(idim)=(Coord{idim}(2)-Coord{idim}(1))/DimValue(idim);
2170                else
2171                    DCoord=diff(Coord{idim});%array of coordinate derivatives for the input field
2172                    DCoord_min(idim)=min(DCoord);
2173                    DCoord_max=max(DCoord);
2174                %    test_direct(idim)=DCoord_max>0;% =1 for increasing values, 0 otherwise
2175                    if abs(DCoord_max-DCoord_min(idim))>abs(DCoord_max/1000)
2176                        msgbox_uvmat('ERROR',['non monotonic dimension variable # ' num2str(idim)  ' in proj_field.m'])
2177                                return
2178                    end               
2179                    test_interp(idim)=(DCoord_max-DCoord_min(idim))> 0.0001*abs(DCoord_max);% test grid regularity
2180                end
2181                test_direct(idim)=(DCoord_min(idim)>0);
2182            else  % no variable associated with the  dimension #idim, the coordinate value is set equal to the matrix index by default
2183                Coord_i_str=['Coord_' num2str(idim)];
2184                DCoord_min(idim)=1;%default
2185                Coord{idim}=[0.5 DimValue(idim)-0.5];
2186                test_direct(idim)=1;
2187            end
2188        end
2189        if DY==0
2190            DY=abs(DCoord_min(NbDim-1));
2191        end
2192        npY=1+round(abs(Coord{NbDim-1}(end)-Coord{NbDim-1}(1))/DY);%nbre of points after interpol
2193        if DX==0
2194            DX=abs(DCoord_min(NbDim));
2195        end
2196        npX=1+round(abs(Coord{NbDim}(end)-Coord{NbDim}(1))/DX);%nbre of points after interpol
2197        for idim=1:NbDim
2198            if test_interp(idim)
2199                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
2200            end
2201        end       
2202        Coord_y=linspace(Coord{NbDim-1}(1),Coord{NbDim-1}(end),npY);
2203        test_direct_y=test_direct(NbDim-1);
2204        Coord_x=linspace(Coord{NbDim}(1),Coord{NbDim}(end),npX);
2205        test_direct_x=test_direct(NbDim);
2206        DAX=DCoord_min(NbDim);
2207        DAY=DCoord_min(NbDim-1); 
2208        minAX=min(Coord_x);
2209        maxAX=max(Coord_x);
2210        minAY=min(Coord_y);
2211        maxAY=max(Coord_y);
2212        xcorner=[minAX maxAX minAX maxAX]-ObjectData.Coord(1,1);
2213        ycorner=[maxAY maxAY minAY minAY]-ObjectData.Coord(1,2);
2214        xcor_new=xcorner*cos(Phi)+ycorner*sin(Phi);%coord new frame
2215        ycor_new=-xcorner*sin(Phi)+ycorner*cos(Phi);
2216        if ~testXMax
2217            XMax=max(xcor_new);
2218        end
2219        if ~testXMin
2220            XMin=min(xcor_new);
2221        end
2222        if ~testYMax
2223            YMax=max(ycor_new);
2224        end
2225        if ~testYMin
2226            YMin=min(ycor_new);
2227        end
2228        DXinit=(maxAX-minAX)/(DimValue(NbDim)-1);
2229        DYinit=(maxAY-minAY)/(DimValue(NbDim-1)-1);
2230        if DX==0
2231            DX=DXinit;
2232        end
2233        if DY==0
2234            DY=DYinit;
2235        end
2236        if NbDim==3
2237            DZ=(Coord{1}(end)-Coord{1}(1))/(DimValue(1)-1);
2238            if ~test_direct(1)
2239                DZ=-DZ;
2240            end
2241            Coord_z=linspace(Coord{1}(1),Coord{1}(end),DimValue(1));
2242            test_direct_z=test_direct(1);
2243        end
2244        npX=floor((XMax-XMin)/DX+1);
2245        npY=floor((YMax-YMin)/DY+1);   
2246        if test_direct_y
2247            coord_y_proj=linspace(YMin,YMax,npY);%abscissa of the new pixels along the line
2248        else
2249            coord_y_proj=linspace(YMax,YMin,npY);%abscissa of the new pixels along the line
2250        end
2251        if test_direct_x
2252            coord_x_proj=linspace(XMin,XMax,npX);%abscissa of the new pixels along the line
2253        else
2254            coord_x_proj=linspace(XMax,XMin,npX);%abscissa of the new pixels along the line
2255        end
2256       
2257        % case with no rotation and interpolation
2258        if isequal(ProjMode,'projection') && isequal(Phi,0) && isequal(Theta,0) && isequal(Psi,0)
2259            if ~testXMin && ~testXMax && ~testYMin && ~testYMax && NbDim==2
2260                ProjData=FieldData;
2261            else
2262                indY=NbDim-1;
2263                if test_direct(indY)
2264                    min_indy=ceil((YMin-Coord{indY}(1))/DYinit)+1;
2265                    YIndexFirst=floor((YMax-Coord{indY}(1))/DYinit)+1;
2266                    Ybound(1)=Coord{indY}(1)+DYinit*(min_indy-1);
2267                    Ybound(2)=Coord{indY}(1)+DYinit*(YIndexFirst-1);
2268                else
2269                    min_indy=ceil((Coord{indY}(1)-YMax)/DYinit)+1;
2270                    max_indy=floor((Coord{indY}(1)-YMin)/DYinit)+1;
2271                    Ybound(2)=Coord{indY}(1)-DYinit*(max_indy-1);
2272                    Ybound(1)=Coord{indY}(1)-DYinit*(min_indy-1);
2273                end   
2274                if test_direct(NbDim)==1
2275                    min_indx=ceil((XMin-Coord{NbDim}(1))/DXinit)+1;
2276                    max_indx=floor((XMax-Coord{NbDim}(1))/DXinit)+1;
2277                    Xbound(1)=Coord{NbDim}(1)+DXinit*(min_indx-1);
2278                    Xbound(2)=Coord{NbDim}(1)+DXinit*(max_indx-1);
2279                else
2280                    min_indx=ceil((Coord{NbDim}(1)-XMax)/DXinit)+1;
2281                    max_indx=floor((Coord{NbDim}(1)-XMin)/DXinit)+1;
2282                    Xbound(2)=Coord{NbDim}(1)+DXinit*(max_indx-1);
2283                    Xbound(1)=Coord{NbDim}(1)+DXinit*(min_indx-1);
2284                end
2285                if NbDim==3
2286                    DimCell(1)=[]; %suppress z variable
2287                    DimValue(1)=[];
2288                                        %structured coordinates
2289                    if test_direct(1)
2290                        iz=ceil((ObjectData.Coord(1,3)-Coord{1}(1))/DZ)+1;
2291                    else
2292                        iz=ceil((Coord{1}(1)-ObjectData.Coord(1,3))/DZ)+1;
2293                    end
2294                end
2295                min_indy=max(min_indy,1);% deals with margin (bound lower than the first index)
2296                min_indx=max(min_indx,1);
2297                max_indy=min(max_indy,DimValue(1));
2298                max_indx=min(max_indx,DimValue(2));
2299                for ivar=VarIndex% loop on non coordinate variables
2300                    VarName=FieldData.ListVarName{ivar};
2301                    ProjData.ListVarName=[ProjData.ListVarName VarName];
2302                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2303                    if isfield(FieldData,'VarAttribute') && length(FieldData.VarAttribute)>=ivar
2304                        ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar};
2305                    end
2306                    if NbDim==3
2307                        eval(['ProjData.' VarName '=squeeze(FieldData.' VarName '(iz,min_indy:max_indy,min_indx:max_indx));']);
2308                    else
2309                        eval(['ProjData.' VarName '=FieldData.' VarName '(min_indy:max_indy,min_indx:max_indx,:);']);
2310                    end
2311                end 
2312                eval(['ProjData.' AYName '=[Ybound(1) Ybound(2)];']) %record the new (projected ) y coordinates
2313                eval(['ProjData.' AXName '=[Xbound(1) Xbound(2)];']) %record the new (projected ) x coordinates
2314            end
2315        elseif isfield(FieldData,'A') %TO GENERALISE       % case with rotation and/or interpolation
2316            if NbDim==2 %2D case
2317                [X,Y]=meshgrid(coord_x_proj,coord_y_proj);%grid in the new coordinates
2318                XIMA=ObjectData.Coord(1,1)+(X)*cos(Phi)-Y*sin(Phi);%corresponding coordinates in the original image
2319                YIMA=ObjectData.Coord(1,2)+(X)*sin(Phi)+Y*cos(Phi);
2320                XIMA=(XIMA-minAX)/DXinit+1;% image index along x
2321                YIMA=(-YIMA+maxAY)/DYinit+1;% image index along y
2322                XIMA=reshape(round(XIMA),1,npX*npY);%indices reorganized in 'line'
2323                YIMA=reshape(round(YIMA),1,npX*npY);
2324                flagin=XIMA>=1 & XIMA<=DimValue(2) & YIMA >=1 & YIMA<=DimValue(1);%flagin=1 inside the original image
2325                if isequal(ObjectData.ProjMode,'interp_tps')
2326                    npx_interp_tps=ceil(abs(DX/DAX));
2327                    npy_interp_tps=ceil(abs(DY/DAY));
2328                    Minterp_tps=ones(npy_interp_tps,npx_interp_tps)/(npx_interp_tps*npy_interp_tps);
2329                    test_interp_tps=1;
2330                else
2331                    test_interp_tps=0;
2332                end
2333                eval(['ProjData.' AYName '=[coord_y_proj(1) coord_y_proj(end)];']) %record the new (projected ) y coordinates
2334                eval(['ProjData.' AXName '=[coord_x_proj(1) coord_x_proj(end)];']) %record the new (projected ) x coordinates
2335                for ivar=VarIndex
2336                    VarName=FieldData.ListVarName{ivar};
2337                    if test_interp(1) || test_interp(2)%interpolate on a regular grid       
2338                          eval(['ProjData.' VarName '=interp2(Coord{2},Coord{1},FieldData.' VarName ',Coord_x,Coord_y'');']) %TO TEST
2339                    end
2340                    %filter the field (image) if option 'interp_tps' is used
2341                    if test_interp_tps 
2342                         Aclass=class(FieldData.A);
2343                         ProjData.(VarName)=interp_tps2(Minterp_tps,FieldData.(VarName),'valid');
2344                         if ~isequal(Aclass,'double')
2345                             ProjData.(VarName)=Aclass(FieldData.(VarName));%revert to integer values
2346                         end
2347                    end
2348                    eval(['vec_A=reshape(FieldData.' VarName ',[],nbcolor);'])%put the original image in line             
2349                    %ind_in=find(flagin);
2350                    ind_out=find(~flagin);
2351                    ICOMB=(XIMA-1)*DimValue(1)+YIMA;
2352                    ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
2353                    vec_B(flagin,1:nbcolor)=vec_A(ICOMB,:);
2354                    for icolor=1:nbcolor
2355                        vec_B(ind_out,icolor)=zeros(size(ind_out));
2356                    end
2357                    ProjData.ListVarName=[ProjData.ListVarName VarName];
2358                    ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2359                    if isfield(FieldData,'VarAttribute')&&length(FieldData.VarAttribute)>=ivar
2360                        ProjData.VarAttribute{length(ProjData.ListVarName)+nbcoord}=FieldData.VarAttribute{ivar};
2361                    end     
2362                    eval(['ProjData.' VarName '=reshape(vec_B,npY,npX,nbcolor);']);
2363                end
2364                ProjData.FF=reshape(~flagin,npY,npX);%false flag A FAIRE: tenir compte d'un flga ant???rieur 
2365                ProjData.ListVarName=[ProjData.ListVarName 'FF'];
2366                ProjData.VarDimName=[ProjData.VarDimName {DimCell}];
2367                ProjData.VarAttribute{length(ProjData.ListVarName)}.Role='errorflag';
2368            else %3D case
2369                if ~testangle     
2370                    % unstructured z coordinate
2371                    test_sup=(Coord{1}>=ObjectData.Coord(1,3));
2372                    iz_sup=find(test_sup);
2373                    iz=iz_sup(1);
2374                    if iz>=1 & iz<=npz
2375                        %ProjData.ListDimName=[ProjData.ListDimName ListDimName(2:end)];
2376                        %ProjData.DimValue=[ProjData.DimValue npY npX];
2377                        for ivar=VarIndex
2378                            VarName=FieldData.ListVarName{ivar};
2379                            ProjData.ListVarName=[ProjData.ListVarName VarName];
2380                            ProjData.VarAttribute{length(ProjData.ListVarName)}=FieldData.VarAttribute{ivar}; %reproduce the variable attributes 
2381                            eval(['ProjData.' VarName '=squeeze(FieldData.' VarName '(iz,:,:));'])% select the z index iz
2382                            %TODO : do a vertical average for a thick plane
2383                            if test_interp(2) || test_interp(3)
2384                                eval(['ProjData.' VarName '=interp2(Coord{3},Coord{2},ProjData.' VarName ',Coord_x,Coord_y'');'])
2385                            end
2386                        end
2387                    end
2388                else
2389                    RotMatrix=rodrigues(om);
2390                   
2391                    errormsg='projection of structured coordinates on oblique plane not yet implemented';
2392                    %TODO: use interp3
2393                    return
2394                end
2395            end
2396        end
2397    end
2398
2399    %% projection of  velocity components in the rotated coordinates
2400    if testangle
2401        if isempty(ivar_V)
2402            msgbox_uvmat('ERROR','v velocity component missing in proj_field.m')
2403            return
2404        end
2405        UName=FieldData.ListVarName{ivar_U};
2406        VName=FieldData.ListVarName{ivar_V};   
2407        eval(['ProjData.' UName  '=cos(Phi)*ProjData.' UName '+ sin(Phi)*ProjData.' VName ';'])
2408        eval(['ProjData.' VName  '=cos(Theta)*(-sin(Phi)*ProjData.' UName '+ cos(Phi)*ProjData.' VName ');'])
2409        if ~isempty(ivar_W)
2410            WName=FieldData.ListVarName{ivar_W};
2411            eval(['ProjData.' VName '=ProjData.' VName '+ ProjData.' WName '*sin(Theta);'])%
2412            eval(['ProjData.' WName '=NormVec_X*ProjData.' UName '+ NormVec_Y*ProjData.' VName '+ NormVec_Z* ProjData.' WName ';']);
2413        end
2414        if ~isequal(Psi,0)
2415            eval(['ProjData.' UName '=cos(Psi)* ProjData.' UName '- sin(Psi)*ProjData.' VName ';']);
2416            eval(['ProjData.' VName '=sin(Psi)* ProjData.' UName '+ cos(Psi)*ProjData.' VName ';']);
2417        end
2418    end
2419end
2420
2421%------------------------------------------------------------------------
2422%--- transfer the global attributes
2423function [ProjData,errormsg]=proj_heading(FieldData,ObjectData)
2424%------------------------------------------------------------------------
2425ProjData=[];%default
2426errormsg='';%default
2427
2428%% transfer error
2429if isfield(FieldData,'Txt')
2430    errormsg=FieldData.Txt; %transmit erreur message
2431    return;
2432end
2433
2434%% transfer global attributes
2435if ~isfield(FieldData,'ListGlobalAttribute')
2436    ProjData.ListGlobalAttribute={};
2437else
2438    ProjData.ListGlobalAttribute=FieldData.ListGlobalAttribute;
2439end
2440for iattr=1:length(ProjData.ListGlobalAttribute)
2441    AttrName=ProjData.ListGlobalAttribute{iattr};
2442    if isfield(FieldData,AttrName)
2443        ProjData.(AttrName)=FieldData.(AttrName);
2444    end
2445end
2446
2447%% transfer coordinate unit
2448if isfield(ProjData,'CoordUnit')
2449    ProjData=rmfield(ProjData,'CoordUnit');% do not transfer by default (to avoid x/y=1 for profiles)
2450end
2451if isfield(FieldData,'CoordUnit')
2452    if isfield(ObjectData,'CoordUnit') && ~strcmp(FieldData.CoordUnit,ObjectData.CoordUnit)
2453        errormsg=[ObjectData.Type ' in ' ObjectData.CoordUnit ' coordinates, while field in ' FieldData.CoordUnit ];
2454        return
2455    elseif strcmp(ObjectData.Type,'plane')|| strcmp(ObjectData.Type,'volume')
2456         ProjData.CoordUnit=FieldData.CoordUnit;
2457    end
2458end
2459
2460%% store the properties of the projection object
2461ListObject={'Name','Type','ProjMode','angle','RangeX','RangeY','RangeZ','DX','DY','DZ','Coord'};
2462for ilist=1:length(ListObject)
2463    if isfield(ObjectData,ListObject{ilist})
2464        val=ObjectData.(ListObject{ilist});
2465        if ~isempty(val)
2466            ProjData.(['ProjObject' ListObject{ilist}])=val;
2467            ProjData.ListGlobalAttribute=[ProjData.ListGlobalAttribute {['ProjObject' ListObject{ilist}]}];
2468        end
2469    end   
2470end
2471
Note: See TracBrowser for help on using the repository browser.