source: trunk/src/proj_field.m @ 675

Last change on this file since 675 was 675, checked in by sommeria, 11 years ago

various bugs corrected

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