source: trunk/src/proj_field.m @ 1071

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