source: trunk/src/proj_field.m @ 1187

Last change on this file since 1187 was 1187, checked in by sommeria, 12 days ago

mask accessory updated

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