source: trunk/src/proj_field.m @ 1086

Last change on this file since 1086 was 1085, checked in by sommeria, 4 years ago

aver_spectral added andsmall bug repairs

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