source: trunk/src/proj_field.m @ 863

Last change on this file since 863 was 863, checked in by sommeria, 9 years ago

civ2vel3C_introduced

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