source: trunk/src/proj_field.m @ 985

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