source: trunk/src/proj_field.m @ 839

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