source: trunk/src/proj_field.m @ 653

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

bugs corrected for displaying small rgb color images.
proj_field/proj_plane imrpoved
browser changed to a more standard GUI presentaton

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