diff --git a/TBM/Alternative_OT/VOT3D.m b/TBM/Alternative_OT/VOT3D.m new file mode 100644 index 0000000..60c3b89 --- /dev/null +++ b/TBM/Alternative_OT/VOT3D.m @@ -0,0 +1,232 @@ +%Shinjini VOT (c) 2015 +%VOT et al approach to solving for mass-preserving mapping + + +function [results] = VOT3D(I0,I1,f1,f2,f3,penalty,tot,sigma,level,scale,gamma) + +%addpath /afs/.ece.cmu.edu/project/cbi/users/gustavor/Shinjini/Autism/TBM_features +%addpath /afs/.ece.cmu.edu/project/cbi/users/gustavor/Shinjini/Autism/TBM_features/DGradient + +%step_size = 5*10^-5; %10^9; +cutoff = 10^-4; +cutoff0 = 2*10^-4; +%sigma = 1; +DC_level = 0.1; %Create Gaussian kernel in 3D +%tot = 10^7; %integrates to total level +it = 0; +lambda = 0; +p = 1; %generate plots + +I0 = gen_pdf(I0,DC_level,sigma); +I1 = gen_pdf(I1,DC_level,sigma); + +[M,N,K]=size(I1); +[X,Y,Z]=meshgrid(1:N,1:M,1:K); +figure(1) + +mask = ones(size(I0)); +for i = 1:size(I0,3) + mask(:,:,i) = im2bw(I0(:,:,i),min(I0(:))); +end + +I0 = I0*tot; +I1 = I1*tot; + +iter = 1; +converged = 0; + +results.f1 = f1; +results.f2 = f2; +results.f3 = f3; + +[C1,C2,C3] = curl(f1,f2,f3); +C = mean(C1(:).^2 + C2(:).^2 + C3(:).^2); +results.curl = C; + + +while(true) + if ~p + fprintf('Now on interation %d \n', iter); + end + if iter ==1 + [ f1t,f2t,f3t,I0_recon,Ierror,flag ] = compVOTGradients( f1,f2,f3,I0,I1,lambda,gamma ); + err3(iter) = mean((Ierror(:)./I0(:)).^2); %relative MSE reported + results.MSE3(iter) = err3; + results.mass(iter) = sum(sum(sum(((f1 - X).^2 + (f2 - Y).^2 + (f3 - Z).^2).*I0))); + err1(iter)=.5*sum(((Ierror(:)./I0(:)).*mask(:)).^2)/nnz(mask(:)); %in the area of the brain %numel(I0(:)); %relative MSE + results.MSE1(iter) = err1; + results.I0_recon = I0_recon; results.I0 = I0; results.I1 = I1; + %step_size = (10^-2/10^scale)/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + if scale==0 || scale>2 + step_size = (10^-(scale+2))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + else + step_size = (10^-(scale+1))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + end + if (flag) + error('The initial deformation field is not diffeomorphic'); + else + xk1_temp = f1-step_size*f1t; xk2_temp = f2-step_size*f2t; xk3_temp = f3-step_size*f3t; + yk1_temp = xk1_temp; yk2_temp = xk2_temp; yk3_temp = xk3_temp; + + %check to make sure that the updated fields are diffeomorphic + [~,~,~,~,~,flag] = compVOTGradients(yk1_temp,yk2_temp,yk3_temp,I0,I1,lambda,gamma); + %if not diffeomorphic, need to take a smaller stepsize + while(flag && ~converged) + step_size = step_size/2; + if step_size < (10^-8) %if there is no stepsize that will enable a diffeomorphic deformation, you have converged + converged = 1; + step_size = 0; + results.f1 = f1; + results.f2 = f2; + results.f3 = f3; + end + xk1_temp = f1-step_size*f1t; xk2_temp = f2-step_size*f2t; xk3_temp = f3-step_size*f3t; + yk1_temp = xk1_temp; yk2_temp = xk2_temp; yk3_temp = xk3_temp; + [~,~,~,~,~,flag] = compVOTGradients(yk1_temp,yk2_temp,yk3_temp,I0,I1,lambda,gamma); + end + xk1 = xk1_temp; xk2 = xk2_temp; xk3 = xk3_temp; + yk1 = yk1_temp; yk2 = yk2_temp; yk3 = yk3_temp; + %fprintf('the stepsize is %d \n', step_size); + + yk1minus1 = zeros(size(I0)); yk2minus1 = zeros(size(I0)); yk3minus1 = zeros(size(I0)); + xk1minus1 = zeros(size(I0)); xk2minus1 = zeros(size(I0)); xk3minus1 = zeros(size(I0)); + end + end + + + if iter > 1 + [ f1t,f2t,f3t,I0_recon,Ierror ] = compVOTGradients( yk1minus1,yk2minus1,yk3minus1,I0,I1,lambda,gamma ); + xk1_temp = yk1minus1-step_size*f1t; xk2_temp = yk2minus1-step_size*f2t; xk3_temp = yk3minus1-step_size*f3t; + yk1_temp = xk1_temp + (iter-2)/(iter+1)*(xk1_temp - xk1minus1); yk2_temp = xk2_temp + (iter-2)/(iter+1)*(xk2_temp - xk2minus1); yk3_temp = xk3_temp + (iter-2)/(iter+1)*(xk3_temp - xk3minus1); + %step_size = (10^-2/10^scale)/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + if scale>2 + step_size = (10^-(scale+2.5))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + elseif scale ==0 + step_size = (10^-(scale+1.5))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + elseif scale < 2 + step_size = (10^-(scale+2.5))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + elseif scale ==2 + step_size = (10^-(scale+1.5))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); + end +% % % if scale > 3 || scale == 0 +% % % step_size = (10^-(scale+2))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); +% % % elseif scale ==3 || scale ==1 +% % % step_size = (10^-(scale+1))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); +% % % else +% % % step_size = (10^-(scale+0.5))/(max(sqrt(f1(:).^2 + f2(:).^2 + f3(:).^2))); +% % % end + %check whether updated fields are diffeomorphic + [~,~,~,~,~,flag] = compVOTGradients(yk1_temp,yk2_temp,yk3_temp,I0,I1,lambda,gamma); + while (flag && ~converged) + step_size = step_size/2; + if step_size < (10^-8) %if there is no stepsize that will enable a diffeomorphic deformation, you have converged + converged = 1; + step_size = 0; + if iter==2 + results.f1 = f1; + results.f2 = f2; + results.f3 = f3; + end + end + xk1_temp = yk1minus1-step_size*f1t; xk2_temp = yk2minus1-step_size*f2t; xk3_temp = yk3minus1-step_size*f3t; + yk1_temp = xk1_temp + (iter-2)/(iter+1)*(xk1_temp - xk1minus1); yk2_temp = xk2_temp + (iter-2)/(iter+1)*(xk2_temp - xk2minus1); yk3_temp = xk3_temp + (iter-2)/(iter+1)*(xk3_temp - xk3minus1); + [~,~,~,~,~,flag] = compVOTGradients(yk1_temp,yk2_temp,yk3_temp,I0,I1,lambda,gamma); + end + xk1 = xk1_temp; xk2 = xk2_temp; xk3 = xk3_temp; + yk1 = yk1_temp; yk2 = yk2_temp; yk3 = yk3_temp; + % fprintf('the stepsize is %d \n', step_size); + end + + if (~converged) + yk1minus2 = yk1minus1; yk2minus2 = yk2minus1; yk3minus2 = yk3minus1; + yk1minus1 = yk1; yk2minus1 = yk2; yk3minus1 = yk3; + xk1minus1 = xk1; xk2minus1 = xk2; xk3minus1 = xk3; + end + + %plotting code + if (p) + subplot(221) + %imshow(squeeze(sum(I0_recon,1)),[]); + imshow(I0_recon(:,:,round(K/2)),[]); %shows the middle section of the image + title('$$det(D{\bf f})I_1({\bf f})$$','interpreter','latex','fontsize',20) + freezeColors + subplot(222) + if iter==1 + showgrid(squeeze(X(:,:,round(K/2))-f1(:,:,round(K/2))),squeeze(Y(:,:,round(K/2))-f2(:,:,round(K/2))),3) + else + showgrid(squeeze(X(:,:,round(K/2))-yk1minus2(:,:,round(K/2))),squeeze(Y(:,:,round(K/2))-yk2minus2(:,:,round(K/2))),3) + end + title('$${\bf x}-{\bf f}({\bf x})$$','interpreter','latex','fontsize',20) + subplot(2,2,3) + end + %%err(iter)=.5*sum(((Ierror(:)./I0(:))).^2)/numel(I0(:)); + err1(iter)=.5*sum(((Ierror(:)./I0(:)).*mask(:)).^2)/nnz(mask(:)); %in the area of the brain %numel(I0(:)); %relative MSE + err2(iter)=.5*sum(((Ierror(:)./I0(:))).^2)/numel(I0(:)); %relative MSE + err3(iter) = mean((Ierror(:)./I0(:)).^2); %relative MSE reported + err4(iter) = 0.5*sum(Ierror(:).^2); %the data term in the update equation + if err1(end)/err1(1) > level %when the MSE is reduced to a quarter of its original value, start penalizing the solution + if it==0 + it = iter; + end + lambda = penalty; %*(1.03)^(iter-it); + end + if (p) + plot(err3,'linewidth',2) + title('MSE: $$\frac{1}{2}\|det(D{\bf f})I_1({\bf f})-I_0\|^2$$','interpreter','latex','fontsize',20) + grid on + subplot(2,2,4) + end + mass(iter) = sum(sum(sum(((yk1minus2 - X).^2 + (yk2minus2 - Y).^2 + (yk3minus2 - Z).^2).*I0))); + if iter==1 + [C1,C2,C3] = curl(f1,f2,f3); + else + [C1,C2,C3] = curl(yk1minus2,yk2minus2,yk3minus2); + end + C = sum(C1(:).^2 + C2(:).^2 + C3(:).^2); %L2 norm + errorcurl(iter)=0.5*C; + objective = err4 + lambda*errorcurl; + %fprintf('The objective value is %d \n', objective(end)); + if iter > 50 && (objective(iter-1) < objective(iter))% || (errorcurl(iter)-errorcurl(iter-1))/errorcurl(iter) > 0.05) %prevents curl or objective value from shooting up at the end + return + end + if p + plot(errorcurl,'r','linewidth',2) + title('Curl: $$\frac{1}{2}\|\nabla\times {\bf f}\|^2$$','interpreter','latex','fontsize',20) + grid on + drawnow + end + %%end of plotting code + + if (converged || iter>500 && (scale ==1) && (round(err3(iter))-round(err3(iter-1)))*10^6 ==0 || (scale ==0 &&(round(err3(iter)*10^3))/10^3 <= cutoff) || (scale~=0 && err3(iter) <= cutoff0) ) %|| (scale ==1 &&(round(err3(iter)*10^3))/10^3 <= cutoff0*10) + return; + end + I0_recon = I0_recon./sum(I0_recon(:))*10^6; + results.f1 = yk1minus2; + results.f2 = yk2minus2; + results.f3 = yk3minus2; + results.I0_recon = I0_recon; + results.mass = mass; + results.MSE2 = err2; + results.MSE1 = err1; + results.MSE3 = err3; + results.curl = 2*errorcurl/(numel(C)); + results.I0 = I0; + results.I1 = I1; + results.objective = objective; + iter = iter + 1; + + + +end + + +end + + +% [ f1t,f2t,f3t,I0_recon,Ierror ] = compVOTGradients( f1,f2,f3,I0,I1 ); +% +% % step_size=.05/(max(sqrt(f1t(:).^2+f2t(:).^2+f3t(:).^2))); +% f1=f1-step_size*f1t; +% f2=f2-step_size*f2t; +% f3=f3-step_size*f3t; + diff --git a/TBM/Alternative_OT/checkLocalMin.m b/TBM/Alternative_OT/checkLocalMin.m new file mode 100644 index 0000000..89f01bc --- /dev/null +++ b/TBM/Alternative_OT/checkLocalMin.m @@ -0,0 +1,36 @@ +%Shinjini Kundu (c) 2015 +%Transport-Based Morphometry + +function [ new_lambda, flag ] = checkLocalMin( results, lambda ) +%Checks whether the curl and MSE that the code converges to is too far from the global minimum. +%if so, instructs the gradient descent to keep going. +%Input: results results from the Haber3D code +% lambda parameter from Haber3D code +%Output: new_lambda new value for lambda +% flag indicates whether the solution appears to be a global minimum + + + +CURL = results.curl(end); +MSE = results.MSE2(end); +flag = 0; + +if CURL > 5 + flag = 1; + new_lambda = lambda*1.5; +elseif MSE > 7*10^-3 + flag = 1; + new_lambda = lambda/1.5; +end + + + +end + + + + + + + + diff --git a/TBM/Alternative_OT/compVOTGradients.asv b/TBM/Alternative_OT/compVOTGradients.asv new file mode 100644 index 0000000..9bf385e --- /dev/null +++ b/TBM/Alternative_OT/compVOTGradients.asv @@ -0,0 +1,76 @@ +%Shinjini VOT (c) 2015 +%Transport-Based Morphometry + +function [ f1t,f2t,f3t,I0_recon,Ierror,flag ] = compVOTGradients( f1,f2,f3,I0,I1,lambda,gamma ) +%Computes the gradients required in VOT et al's variation optimization approach +%inputs: f1,f2,f3 current deformation fields +% I0,I1 original images +% lambda penalty for curl term +% gamma penalty for mass transport term +% +%outputs: f1t,f2t,f3t gradients to update in the next iteration +% flag 1 if current deformation is not diffeomorphic + +[X,Y,Z] = meshgrid(1:size(f1,2),1:size(f1,1),1:size(f1,3)); + +[f1x,f1y,f1z]=gradient(f1); +[f2x,f2y,f2z]=gradient(f2); +[f3x,f3y,f3z]=gradient(f3); + +[f1yx,f1yy,~] = gradient(f1y); +[f1zx,~,f1zz] = gradient(f1z); +[f2xx,f2xy,~] = gradient(f2x); +[~,f2zy,f2zz] = gradient(f2z); +[f3xx,~,f3xz] = gradient(f3x); +[~,f3yy,f3yz] = gradient(f3y); + +detf = (f1x.*f2y.*f3z + f1y.*f2z.*f3x + f1z.*f2x.*f3y - f1x.*f2z.*f3y - f1y.*f2x.*f3z - f1z.*f2y.*f3x); + +%check to make sure that the current deformation is diffeomorphic +if sum(detf(:)<0) ~=0 %if there are any nonzero values in the determinant, + flag = 1; + %fprintf('Warning: mapping is not diffeomorphic. There are %d negative values in the determinant \n', sum(detf(:)<0) ); +else + flag = 0; +end + +It=abs(interp3(I1,f1,f2,f3,'cubic',min(I1(:)))); %linear interpolation does not produce unwanted negative values +Ierror=detf.*It-I0; +[Itx,Ity,Itz]=gradient(It); + +[g11x,~,~]=gradient((f2y.*f3z-f2z.*f3y).*Ierror.*It); +[~,g12y,~]=gradient(-(f2x.*f3z-f2z.*f3x).*Ierror.*It); +[~,~,g13z]=gradient((f2x.*f3y-f2y.*f3x).*Ierror.*It); + +[g21x,~,~]=gradient(-(f1y.*f3z-f1z.*f3y).*Ierror.*It); +[~,g22y,~]=gradient((f1x.*f3z-f1z.*f3x).*Ierror.*It); +[~,~,g23z]=gradient(-(f1x.*f3y-f1y.*f3x).*Ierror.*It); + +[g31x,~,~]=gradient((f1y.*f2z-f1z.*f2y).*Ierror.*It); +[~,g32y,~]=gradient(-(f1x.*f2z-f1z.*f2x).*Ierror.*It); +[~,~,g33z]=gradient((f1x.*f2y-f1y.*f2x).*Ierror.*It); + +divD1=g11x+g12y+g13z; +divD2=g21x+g22y+g23z; +divD3=g31x+g32y+g33z; + +curlC1 = f2xy - f1yy - f1zz + f3xz; +curlC2 = f3yz - f2zz - f2xx + f1yx; +curlC3 = f1zx - f3xx - f3yy + f2zy; + +f1t=detf.*Itx.*Ierror-divD1 + lambda*curlC1 - gamma*(X-f1).*I0; +f2t=detf.*Ity.*Ierror-divD2 + lambda*curlC2 - gamma*(Y-f2).*I0; +f3t=detf.*Itz.*Ierror-divD3 + lambda*curlC3 - gamma*(Z-f3).*I0; + +%in order to keep with the assumptions necessary in deriving the equations, +%we need to zero out the directional derivative at the boundary + +Z = padarray(ones([size(Ierror,1)-2,size(Ierror,2)-2,size(Ierror,3)-2]),[1,1,1]); + +f1t = f1t.*Z; +f2t = f2t.*Z; +f3t = f3t.*Z; + +I0_recon = detf.*It; +end + diff --git a/TBM/Alternative_OT/compVOTGradients.m b/TBM/Alternative_OT/compVOTGradients.m new file mode 100644 index 0000000..1f432f9 --- /dev/null +++ b/TBM/Alternative_OT/compVOTGradients.m @@ -0,0 +1,76 @@ +%Shinjini VOT (c) 2015 +%Transport-Based Morphometry + +function [ f1t,f2t,f3t,I0_recon,Ierror,flag ] = compVOTGradients( f1,f2,f3,I0,I1,lambda,gamma ) +%Computes the gradients required in VOT et al's variation optimization approach +%inputs: f1,f2,f3 current deformation fields +% I0,I1 original images +% lambda penalty for curl term +% gamma penalty for mass transport term +% +%outputs: f1t,f2t,f3t gradients to update in the next iteration +% flag 1 if current deformation is not diffeomorphic + +[X,Y,Z] = meshgrid(1:size(f1,2),1:size(f1,1),1:size(f1,3)); + +[f1x,f1y,f1z]=gradient(f1); +[f2x,f2y,f2z]=gradient(f2); +[f3x,f3y,f3z]=gradient(f3); + +[f1yx,f1yy,~] = gradient(f1y); +[f1zx,~,f1zz] = gradient(f1z); +[f2xx,f2xy,~] = gradient(f2x); +[~,f2zy,f2zz] = gradient(f2z); +[f3xx,~,f3xz] = gradient(f3x); +[~,f3yy,f3yz] = gradient(f3y); + +detf = (f1x.*f2y.*f3z + f1y.*f2z.*f3x + f1z.*f2x.*f3y - f1x.*f2z.*f3y - f1y.*f2x.*f3z - f1z.*f2y.*f3x); + +%check to make sure that the current deformation is diffeomorphic +if sum(detf(:)<0) ~=0 %if there are any nonzero values in the determinant, + flag = 1; + %fprintf('Warning: mapping is not diffeomorphic. There are %d negative values in the determinant \n', sum(detf(:)<0) ); +else + flag = 0; +end + +It=abs(interp3(I1,f1,f2,f3,'cubic',min(I1(:)))); %linear interpolation does not produce unwanted negative values +Ierror=detf.*It-I0; +[Itx,Ity,Itz]=gradient(It); + +[g11x,~,~]=gradient((f2y.*f3z-f2z.*f3y).*Ierror.*It); +[~,g12y,~]=gradient(-(f2x.*f3z-f2z.*f3x).*Ierror.*It); +[~,~,g13z]=gradient((f2x.*f3y-f2y.*f3x).*Ierror.*It); + +[g21x,~,~]=gradient(-(f1y.*f3z-f1z.*f3y).*Ierror.*It); +[~,g22y,~]=gradient((f1x.*f3z-f1z.*f3x).*Ierror.*It); +[~,~,g23z]=gradient(-(f1x.*f3y-f1y.*f3x).*Ierror.*It); + +[g31x,~,~]=gradient((f1y.*f2z-f1z.*f2y).*Ierror.*It); +[~,g32y,~]=gradient(-(f1x.*f2z-f1z.*f2x).*Ierror.*It); +[~,~,g33z]=gradient((f1x.*f2y-f1y.*f2x).*Ierror.*It); + +divD1=g11x+g12y+g13z; +divD2=g21x+g22y+g23z; +divD3=g31x+g32y+g33z; + +curlC1 = f2xy - f1yy - f1zz + f3xz; +curlC2 = f3yz - f2zz - f2xx + f1yx; +curlC3 = f1zx - f3xx - f3yy + f2zy; + +f1t=detf.*Itx.*Ierror-divD1 + lambda*curlC1 - gamma*(X-f1).*I0; +f2t=detf.*Ity.*Ierror-divD2 + lambda*curlC2 - gamma*(Y-f2).*I0; +f3t=detf.*Itz.*Ierror-divD3 + lambda*curlC3 - gamma*(Z-f3).*I0; + +%in order to keep with the assumptions necessary in deriving the equations, +%we need to zero out the directional derivative at the boundary + +Z = padarray(ones([size(Ierror,1)-2,size(Ierror,2)-2,size(Ierror,3)-2]),[1,1,1]); + +f1t = f1t.*Z; +f2t = f2t.*Z; +f3t = f3t.*Z; + +I0_recon = detf.*It; +end + diff --git a/TBM/Alternative_OT/freezeColors.m b/TBM/Alternative_OT/freezeColors.m new file mode 100644 index 0000000..6c7b465 --- /dev/null +++ b/TBM/Alternative_OT/freezeColors.m @@ -0,0 +1,275 @@ +function freezeColors(varargin) +% freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) +% +% Problem: There is only one colormap per figure. This function provides +% an easy solution when plots using different colomaps are desired +% in the same figure. +% +% freezeColors freezes the colors of graphics objects in the current axis so +% that subsequent changes to the colormap (or caxis) will not change the +% colors of these objects. freezeColors works on any graphics object +% with CData in indexed-color mode: surfaces, images, scattergroups, +% bargroups, patches, etc. It works by converting CData to true-color rgb +% based on the colormap active at the time freezeColors is called. +% +% The original indexed color data is saved, and can be restored using +% unfreezeColors, making the plot once again subject to the colormap and +% caxis. +% +% +% Usage: +% freezeColors applies to all objects in current axis (gca), +% freezeColors(axh) same, but works on axis axh. +% +% Example: +% subplot(2,1,1); imagesc(X); colormap hot; freezeColors +% subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... +% +% Note: colorbars must also be frozen. Due to Matlab 'improvements' this can +% no longer be done with freezeColors. Instead, please +% use the function CBFREEZE by Carlos Adrian Vargas Aguilera +% that can be downloaded from the MATLAB File Exchange +% (http://www.mathworks.com/matlabcentral/fileexchange/24371) +% +% h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) +% +% For additional examples, see test/test_main.m +% +% Side effect on render mode: freezeColors does not work with the painters +% renderer, because Matlab doesn't support rgb color data in +% painters mode. If the current renderer is painters, freezeColors +% changes it to zbuffer. This may have unexpected effects on other aspects +% of your plots. +% +% See also unfreezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI (iversen@nsi.edu) 4/19/06 Correctly handles scaled integer cdata +% JRI 9/1/06 should now handle all objects with cdata: images, surfaces, +% scatterplots. (v 2.1) +% JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) +% JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) +% JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. +% JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) +% JRI 4/7/10 Change documentation for colorbars + +% Hidden option for NaN colors: +% Missing data are often represented by NaN in the indexed color +% data, which renders transparently. This transparency will be preserved +% when freezing colors. If instead you wish such gaps to be filled with +% a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. +% freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), +% where [r g b] is a color vector. This works on images & pcolor, but not on +% surfaces. +% Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes +% attributed in the code. + +% Free for all uses, but please retain the following: +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +appdatacode = 'JRI__freezeColorsData'; + +[h, nancolor] = checkArgs(varargin); + +%gather all children with scaled or indexed CData +cdatah = getCDataHandles(h); + +%current colormap +cmap = colormap; +nColors = size(cmap,1); +cax = caxis; + +% convert object color indexes into colormap to true-color data using +% current colormap +for hh = cdatah', + g = get(hh); + + %preserve parent axis clim + parentAx = getParentAxes(hh); + originalClim = get(parentAx, 'clim'); + + % Note: Special handling of patches: For some reason, setting + % cdata on patches created by bar() yields an error, + % so instead we'll set facevertexcdata instead for patches. + if ~strcmp(g.Type,'patch'), + cdata = g.CData; + else + cdata = g.FaceVertexCData; + end + + %get cdata mapping (most objects (except scattergroup) have it) + if isfield(g,'CDataMapping'), + scalemode = g.CDataMapping; + else + scalemode = 'scaled'; + end + + %save original indexed data for use with unfreezeColors + siz = size(cdata); + setappdata(hh, appdatacode, {cdata scalemode}); + + %convert cdata to indexes into colormap + if strcmp(scalemode,'scaled'), + %4/19/06 JRI, Accommodate scaled display of integer cdata: + % in MATLAB, uint * double = uint, so must coerce cdata to double + % Thanks to O Yamashita for pointing this need out + idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); + else %direct mapping + idx = cdata; + %10/8/09 in case direct data is non-int (e.g. image;freezeColors) + % (Floor mimics how matlab converts data into colormap index.) + % Thanks to D Armyr for the catch + idx = floor(idx); + end + + %clamp to [1, nColors] + idx(idx<1) = 1; + idx(idx>nColors) = nColors; + + %handle nans in idx + nanmask = isnan(idx); + idx(nanmask)=1; %temporarily replace w/ a valid colormap index + + %make true-color data--using current colormap + realcolor = zeros(siz); + for i = 1:3, + c = cmap(idx,i); + c = reshape(c,siz); + c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) + realcolor(:,:,i) = c; + end + + %apply new true-color color data + + %true-color is not supported in painters renderer, so switch out of that + if strcmp(get(gcf,'renderer'), 'painters'), + set(gcf,'renderer','zbuffer'); + end + + %replace original CData with true-color data + if ~strcmp(g.Type,'patch'), + set(hh,'CData',realcolor); + else + set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) + end + + %restore clim (so colorbar will show correct limits) + if ~isempty(parentAx), + set(parentAx,'clim',originalClim) + end + +end %loop on indexed-color objects + + +% ============================================================================ % +% Local functions + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getCDataHandles -- get handles of all descendents with indexed CData +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function hout = getCDataHandles(h) +% getCDataHandles Find all objects with indexed CData + +%recursively descend object tree, finding objects with indexed CData +% An exception: don't include children of objects that themselves have CData: +% for example, scattergroups are non-standard hggroups, with CData. Changing +% such a group's CData automatically changes the CData of its children, +% (as well as the children's handles), so there's no need to act on them. + +error(nargchk(1,1,nargin,'struct')) + +hout = []; +if isempty(h),return;end + +ch = get(h,'children'); +for hh = ch' + g = get(hh); + if isfield(g,'CData'), %does object have CData? + %is it indexed/scaled? + if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, + hout = [hout; hh]; %#ok %yes, add to list + end + else %no CData, see if object has any interesting children + hout = [hout; getCDataHandles(hh)]; %#ok + end +end + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% getParentAxes -- return handle of axes object to which a given object belongs +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +function hAx = getParentAxes(h) +% getParentAxes Return enclosing axes of a given object (could be self) + +error(nargchk(1,1,nargin,'struct')) +%object itself may be an axis +if strcmp(get(h,'type'),'axes'), + hAx = h; + return +end + +parent = get(h,'parent'); +if (strcmp(get(parent,'type'), 'axes')), + hAx = parent; +else + hAx = getParentAxes(parent); +end + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% checkArgs -- Validate input arguments +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +function [h, nancolor] = checkArgs(args) +% checkArgs Validate input arguments to freezeColors + +nargs = length(args); +error(nargchk(0,3,nargs,'struct')) + +%grab handle from first argument if we have an odd number of arguments +if mod(nargs,2), + h = args{1}; + if ~ishandle(h), + error('JRI:freezeColors:checkArgs:invalidHandle',... + 'The first argument must be a valid graphics handle (to an axis)') + end + % 4/2010 check if object to be frozen is a colorbar + if strcmp(get(h,'Tag'),'Colorbar'), + if ~exist('cbfreeze.m'), + warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... + ['You seem to be attempting to freeze a colorbar. This no longer'... + 'works. Please read the help for freezeColors for the solution.']) + else + cbfreeze(h); + return + end + end + args{1} = []; + nargs = nargs-1; +else + h = gca; +end + +%set nancolor if that option was specified +nancolor = [nan nan nan]; +if nargs == 2, + if strcmpi(args{end-1},'nancolor'), + nancolor = args{end}; + if ~all(size(nancolor)==[1 3]), + error('JRI:freezeColors:checkArgs:badColorArgument',... + 'nancolor must be [r g b] vector'); + end + nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; + else + error('JRI:freezeColors:checkArgs:unrecognizedOption',... + 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) + end +end + + diff --git a/TBM/Alternative_OT/gaussian_bf.m b/TBM/Alternative_OT/gaussian_bf.m new file mode 100644 index 0000000..1e16996 --- /dev/null +++ b/TBM/Alternative_OT/gaussian_bf.m @@ -0,0 +1,11 @@ +function [phi] = gaussian_bf(X,Y,Z,sigma) + + +phi = 1/(2*pi*sigma^2)*exp( - (X.^2 + Y.^2 + Z.^2)/(2*sigma^2) ); +% phi_x = -phi.*X/(sigma^2); +% phi_y = -phi.*Y/(sigma^2); + +sp=sum(phi(:)); +phi=phi/sp; +% phi_x=fliplr(phi_x/sp); +% phi_y=flipud(phi_y/sp); \ No newline at end of file diff --git a/TBM/Alternative_OT/gen_pdf.m b/TBM/Alternative_OT/gen_pdf.m new file mode 100644 index 0000000..35a58f8 --- /dev/null +++ b/TBM/Alternative_OT/gen_pdf.m @@ -0,0 +1,36 @@ +% Shinjini Kundu (c) 2014 +% Transport-Based Morphometry project (TBM) + +function [I_out]=gen_pdf(I_in,dc,sigma) + +%Preprocessing of 3D image + +%Inputs: I_in 3D input image +% dc a positive constant +% phi kernel for filtering image +% +%Outputs: I_out 3D output image + +% %use this code for 2015 matlab version +if sigma ~=0 + I = mat2gray(imgaussfilt3(I_in,sigma)) + dc; +elseif sigma==0 + I = mat2gray(I_in) + dc; +end +%%%%%% + +% %else, can use this 2014 version of the code +%if sigma ~=0 + % [Xt,Yt,Zt]=meshgrid(-3*sigma:3*sigma,-3*sigma:3*sigma,-3*sigma:3*sigma); + % phi = gaussian_bf(Xt,Yt,Zt,sigma); %normalized gaussian kernel in 3D + % I = mat2gray(convn(I_in,phi,'same')) + dc; +%else +% I = mat2gray(I_in) + dc; +%end +%%%%%% + +I_out = I./sum(I(:)); + +end + + diff --git a/TBM/Alternative_OT/gradient.m b/TBM/Alternative_OT/gradient.m new file mode 100644 index 0000000..8a2a7aa --- /dev/null +++ b/TBM/Alternative_OT/gradient.m @@ -0,0 +1,11 @@ +%Shinjini Kundu (c) 2015 + +function [dx,dy,dz] = gradient(I) +%wrapper code that uses DGradient for fast gradient computation + +dy = DGradient(I,1,1,'2ndOrder'); +dx = DGradient(I,1,2,'2ndOrder'); +dz = DGradient(I,1,3,'2ndOrder'); + +end + diff --git a/TBM/Alternative_OT/inpaint_nans3.m b/TBM/Alternative_OT/inpaint_nans3.m new file mode 100644 index 0000000..b61e2e3 --- /dev/null +++ b/TBM/Alternative_OT/inpaint_nans3.m @@ -0,0 +1 @@ +function B=inpaint_nans3(A,method) % INPAINT_NANS3: in-paints over nans in a 3-D array % usage: B=INPAINT_NANS3(A) % default method (0) % usage: B=INPAINT_NANS3(A,method) % specify method used % % Solves approximation to a boundary value problem to % interpolate and extrapolate holes in a 3-D array. % % Note that if the array is large, and there are many NaNs % to be filled in, this may take a long time, or run into % memory problems. % % arguments (input): % A - n1 x n2 x n3 array with some NaNs to be filled in % % method - (OPTIONAL) scalar numeric flag - specifies % which approach (or physical metaphor to use % for the interpolation.) All methods are capable % of extrapolation, some are better than others. % There are also speed differences, as well as % accuracy differences for smooth surfaces. % % method 0 uses a simple plate metaphor. % method 1 uses a spring metaphor. % % method == 0 --> (DEFAULT) Solves the Laplacian % equation over the set of nan elements in the % array. % Extrapolation behavior is roughly linear. % % method == 1 --+ Uses a spring metaphor. Assumes % springs (with a nominal length of zero) % connect each node with every neighbor % (horizontally, vertically and diagonally) % Since each node tries to be like its neighbors, % extrapolation is roughly a constant function where % this is consistent with the neighboring nodes. % % There are only two different methods in this code, % chosen as the most useful ones (IMHO) from my % original inpaint_nans code. % % % arguments (output): % B - n1xn2xn3 array with NaNs replaced % % % Example: % % A linear function of 3 independent variables, % % used to test whether inpainting will interpolate % % the missing elements correctly. % [x,y,z] = ndgrid(-10:10,-10:10,-10:10); % W = x + y + z; % % % Pick a set of distinct random elements to NaN out. % ind = unique(ceil(rand(3000,1)*numel(W))); % Wnan = W; % Wnan(ind) = NaN; % % % Do inpainting % Winp = inpaint_nans3(Wnan,0); % % % Show that the inpainted values are essentially % % within eps of the originals. % std(Winp(ind) - W(ind)) % ans = % 4.3806e-15 % % % See also: griddatan, inpaint_nans % % Author: John D'Errico % e-mail address: woodchips@rochester.rr.com % Release: 1 % Release date: 8/21/08 % Need to know which elements are NaN, and % what size is the array. Unroll A for the % inpainting, although inpainting will be done % fully in 3-d. NA = size(A); A = A(:); nt = prod(NA); k = isnan(A(:)); % list the nodes which are known, and which will % be interpolated nan_list=find(k); known_list=find(~k); % how many nans overall nan_count=length(nan_list); % convert NaN indices to (r,c) form % nan_list==find(k) are the unrolled (linear) indices % (row,column) form [n1,n2,n3]=ind2sub(NA,nan_list); % both forms of index for all the nan elements in one array: % column 1 == unrolled index % column 2 == index 1 % column 3 == index 2 % column 4 == index 3 nan_list=[nan_list,n1,n2,n3]; % supply default method if (nargin<2) || isempty(method) method = 0; elseif ~ismember(method,[0 1]) error 'If supplied, method must be one of: {0,1}.' end % alternative methods switch method case 0 % The same as method == 1, except only work on those % elements which are NaN, or at least touch a NaN. % horizontal and vertical neighbors only talks_to = [-1 0 0;1 0 0;0 -1 0;0 1 0;0 0 -1;0 0 1]; neighbors_list=identify_neighbors(NA,nan_list,talks_to); % list of all nodes we have identified all_list=[nan_list;neighbors_list]; % generate sparse array with second partials on row % variable for each element in either list, but only % for those nodes which have a row index > 1 or < n L = find((all_list(:,2) > 1) & (all_list(:,2) < NA(1))); nL=length(L); if nL>0 fda=sparse(repmat(all_list(L,1),1,3), ... repmat(all_list(L,1),1,3)+repmat([-1 0 1],nL,1), ... repmat([1 -2 1],nL,1),nt,nt); else fda=spalloc(nt,nt,size(all_list,1)*7); end % 2nd partials on column index L = find((all_list(:,3) > 1) & (all_list(:,3) < NA(2))); nL=length(L); if nL>0 fda=fda+sparse(repmat(all_list(L,1),1,3), ... repmat(all_list(L,1),1,3)+repmat([-NA(1) 0 NA(1)],nL,1), ... repmat([1 -2 1],nL,1),nt,nt); end % 2nd partials on third index L = find((all_list(:,4) > 1) & (all_list(:,4) < NA(3))); nL=length(L); if nL>0 ntimesm = NA(1)*NA(2); fda=fda+sparse(repmat(all_list(L,1),1,3), ... repmat(all_list(L,1),1,3)+repmat([-ntimesm 0 ntimesm],nL,1), ... repmat([1 -2 1],nL,1),nt,nt); end % eliminate knowns rhs=-fda(:,known_list)*A(known_list); k=find(any(fda(:,nan_list(:,1)),2)); % and solve... B=A; B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k); case 1 % Spring analogy % interpolating operator. % list of all springs between a node and a horizontal % or vertical neighbor hv_list=[-1 -1 0 0;1 1 0 0;-NA(1) 0 -1 0;NA(1) 0 1 0; ... -NA(1)*NA(2) 0 0 -1;NA(1)*NA(2) 0 0 1]; hv_springs=[]; for i=1:size(hv_list,1) hvs=nan_list+repmat(hv_list(i,:),nan_count,1); k=(hvs(:,2)>=1) & (hvs(:,2)<=NA(1)) & ... (hvs(:,3)>=1) & (hvs(:,3)<=NA(2)) & ... (hvs(:,4)>=1) & (hvs(:,4)<=NA(3)); hv_springs=[hv_springs;[nan_list(k,1),hvs(k,1)]]; end % delete replicate springs hv_springs=unique(sort(hv_springs,2),'rows'); % build sparse matrix of connections nhv=size(hv_springs,1); springs=sparse(repmat((1:nhv)',1,2),hv_springs, ... repmat([1 -1],nhv,1),nhv,prod(NA)); % eliminate knowns rhs=-springs(:,known_list)*A(known_list); % and solve... B=A; B(nan_list(:,1))=springs(:,nan_list(:,1))\rhs; end % all done, make sure that B is the same shape as % A was when we came in. B=reshape(B,NA); % ==================================================== % end of main function % ==================================================== % ==================================================== % begin subfunctions % ==================================================== function neighbors_list=identify_neighbors(NA,nan_list,talks_to) % identify_neighbors: identifies all the neighbors of % those nodes in nan_list, not including the nans % themselves % % arguments (input): % NA - 1x3 vector = size(A), where A is the % array to be interpolated % nan_list - array - list of every nan element in A % nan_list(i,1) == linear index of i'th nan element % nan_list(i,2) == row index of i'th nan element % nan_list(i,3) == column index of i'th nan element % nan_list(i,4) == third index of i'th nan element % talks_to - px2 array - defines which nodes communicate % with each other, i.e., which nodes are neighbors. % % talks_to(i,1) - defines the offset in the row % dimension of a neighbor % talks_to(i,2) - defines the offset in the column % dimension of a neighbor % % For example, talks_to = [-1 0;0 -1;1 0;0 1] % means that each node talks only to its immediate % neighbors horizontally and vertically. % % arguments(output): % neighbors_list - array - list of all neighbors of % all the nodes in nan_list if ~isempty(nan_list) % use the definition of a neighbor in talks_to nan_count=size(nan_list,1); talk_count=size(talks_to,1); nn=zeros(nan_count*talk_count,3); j=[1,nan_count]; for i=1:talk_count nn(j(1):j(2),:)=nan_list(:,2:4) + ... repmat(talks_to(i,:),nan_count,1); j=j+nan_count; end % drop those nodes which fall outside the bounds of the % original array L = (nn(:,1)<1) | (nn(:,1)>NA(1)) | ... (nn(:,2)<1) | (nn(:,2)>NA(2)) | ... (nn(:,3)<1) | (nn(:,3)>NA(3)); nn(L,:)=[]; % form the same format 4 column array as nan_list neighbors_list=[sub2ind(NA,nn(:,1),nn(:,2),nn(:,3)),nn]; % delete replicates in the neighbors list neighbors_list=unique(neighbors_list,'rows'); % and delete those which are also in the list of NaNs. neighbors_list=setdiff(neighbors_list,nan_list,'rows'); else neighbors_list=[]; end \ No newline at end of file diff --git a/TBM/Alternative_OT/multVOT.m b/TBM/Alternative_OT/multVOT.m new file mode 100644 index 0000000..3a03b1a --- /dev/null +++ b/TBM/Alternative_OT/multVOT.m @@ -0,0 +1,80 @@ +%Shinjini VOT (c) 2015 +%wrapper code to run VOT method + +function final_results = multVOT(I0,I1,lambda,tot,sigma,numScales,level,gamma) + +%addpath /afs/.ece.cmu.edu/project/cbi/users/gustavor/Shinjini/Autism/TBM_features/DGradient; +%addpath /afs/.ece.cmu.edu/project/cbi/users/gustavor/Shinjini/Autism/TBM_features/codegen/mex/GPExpand; +%addpath /afs/.ece.cmu.edu/project/cbi/users/gustavor/Shinjini/Autism/TBM_features/codegen/mex/GPReduce; + +%numScales = 4; %can set the number of multi-resolution scales for initialization +%lambda = 150; %50; %3.5*10^-12; %tradeoff between minimizing MSE and curl + +%2. Initial potential field of curl-free map (the identity) +[~,~,K]=size(I1); +[sx,sy,sz] = size(I0); + +globalIter = 1; + +tic +for scale = numScales:-1:0 + fprintf('Now starting scale %d \n', scale); + I0_down = I0; + I1_down = I1; + + if scale~=0 + for i = 1:scale + [X_down1,~,~] = meshgrid(1:2^(i-1):sy,1:2^(i-1):sx,1:2^(i-1):sz); + I0_down = GPReduce(I0_down); + I1_down = GPReduce(I1_down); + newdim = size(X_down1); + end + end + [X,Y,Z] = meshgrid(1:size(I0_down,2),1:size(I0_down,1),1:size(I0_down,3)); + if globalIter==1 + f0 = X; + g0 = Y; + h0 = Z; + end + results = VOT3D(I0_down,I1_down,f0,g0,h0,lambda,tot,sigma,level,scale,gamma); + if globalIter == numScales + 1 + t = toc + final_results = results + final_results.time = t; + fprintf('the final curl is %d \n', results.curl(end)); + fprintf('the final MSE overall is %d \n', final_results.MSE3(end)); + fprintf('the final MSE in the tissue is %d \n', final_results.MSE1(end)); + fprintf('the final time it took was %d minutes \n', t/60); + figure; imagesc(results.I0_recon(:,:,round(K/2))); colorbar; title('morphed'); + figure; imagesc(results.I0(:,:,round(K/2))); colorbar; title('target'); + figure; imagesc(results.I1(:,:,round(K/2))); colorbar; title('source'); + return; + else +% [ ~,~,~,~,~,flag ] = compVOTGradients( results.f1,results.f2,results.f3,zeros(size(I0_down)),zeros(size(I0_down)),0 ); +% if (flag) +% fprintf('I am not diffeomorphic! \n'); +% else +% fprintf('I am diffeomorphic \n'); +% end + [X2,Y2,Z2] = meshgrid(1:size(X_down1,2),1:size(X_down1,1),1:size(X_down1,3)); + f0 = 2*GPExpand(results.f1-X,newdim)+X2; + g0 = 2*GPExpand(results.f2-Y,newdim)+Y2; + h0 = 2*GPExpand(results.f3-Z,newdim)+Z2; + [ ~,~,~,~,~,flag ] = compVOTGradients( f0,g0,h0,zeros(size(f0)),zeros(size(f0)),0,gamma ); + sigma_f = 2; + if (flag) + %fprintf('I am not diffeomorphic! \n'); + [Xt,Yt,Zt]=meshgrid(-3*sigma_f:3*sigma_f,-3*sigma_f:3*sigma_f,-3*sigma_f:3*sigma_f); + phi = gaussian_bf(Xt,Yt,Zt,sigma_f); %normalized gaussian kernel in 3D + f0 = 2*GPExpand(convn(results.f1-X,phi,'same'),newdim)+X2; + g0 = 2*GPExpand(convn(results.f2-Y,phi,'same'),newdim)+Y2; + h0 = 2*GPExpand(convn(results.f3-Z,phi,'same'),newdim)+Z2; +% else +% fprintf('I am diffeomorphic \n'); + end + globalIter = globalIter + 1; + end +end + + +end \ No newline at end of file diff --git a/TBM/Alternative_OT/showgrid.m b/TBM/Alternative_OT/showgrid.m new file mode 100644 index 0000000..c1665bd --- /dev/null +++ b/TBM/Alternative_OT/showgrid.m @@ -0,0 +1,23 @@ +function showgrid(ux,uy,downsample,lim) + + if nargin<3; downsample = 1; end; + + sizex = size(ux,1); + sizey = size(uy,2); + + ux = ux(1:downsample:end, 1:downsample:end); + uy = uy(1:downsample:end, 1:downsample:end); + + if nargin<4; scale = 3; end; % Scale vector to show small ones + if nargin<5; lim = [0 sizex-1 0 sizey-1]; end; % Display whole image + + [y,x] = ndgrid((0:downsample:(sizex-1))+downsample/2, (0:downsample:(sizey-1))+downsample/2); % coordinate image + z = zeros(size(x)); + mesh(x+ux,y+uy,z); view(2); + daspect([1 1 1]); + colormap([0 0 0]) + axis([lim(3) lim(4) lim(1) lim(2)] + .5 + [downsample 0 downsample 0]/2); % which vector to show + axis off; + set(gca,'YDir','reverse'); + +end \ No newline at end of file diff --git a/TBM/Alternative_OT/unfreezeColors.m b/TBM/Alternative_OT/unfreezeColors.m new file mode 100644 index 0000000..0334f4f --- /dev/null +++ b/TBM/Alternative_OT/unfreezeColors.m @@ -0,0 +1,106 @@ +function unfreezeColors(h) +% unfreezeColors Restore colors of a plot to original indexed color. (v2.3) +% +% Useful if you want to apply a new colormap to plots whose +% colors were previously frozen with freezeColors. +% +% Usage: +% unfreezeColors unfreezes all objects in current axis, +% unfreezeColors(axh) same, but works on axis axh. axh can be vector. +% unfreezeColors(figh) same, but for all objects in figure figh. +% +% Has no effect on objects on which freezeColors was not already called. +% (Note: if colorbars were frozen using cbfreeze, use cbfreeze('off') to +% unfreeze them. See freezeColors for information on cbfreeze.) +% +% +% See also freezeColors, freezeColors_pub.html, cbfreeze. +% +% +% John Iversen (iversen@nsi.edu) 3/23/05 +% + +% Changes: +% JRI 9/1/06 now restores any object with frozen CData; +% can unfreeze an entire figure at once. +% JRI 4/7/10 Change documentation for colorbars + +% Free for all uses, but please retain the following: +% +% Original Author: +% John Iversen, 2005-10 +% john_iversen@post.harvard.edu + +error(nargchk(0,1,nargin,'struct')) + +appdatacode = 'JRI__freezeColorsData'; + +%default: operate on gca +if nargin < 1, + h = gca; +end + +if ~ishandle(h), + error('JRI:unfreezeColors:invalidHandle',... + 'The argument must be a valid graphics handle to a figure or axis') +end + +%if h is a figure, loop on its axes +if strcmp(get(h,'type'),'figure'), + h = get(h,'children'); +end + +for h1 = h', %loop on axes + + %process all children, acting only on those with saved CData + % ( in appdata JRI__freezeColorsData) + ch = findobj(h1); + + for hh = ch', + + %some object handles may be invalidated when their parent changes + % (e.g. restoring colors of a scattergroup unfortunately changes + % the handles of all its children). So, first check to make sure + % it's a valid handle + if ishandle(hh) + if isappdata(hh,appdatacode), + ad = getappdata(hh,appdatacode); + %get oroginal cdata + %patches have to be handled separately (see note in freezeColors) + if ~strcmp(get(hh,'type'),'patch'), + cdata = get(hh,'CData'); + else + cdata = get(hh,'faceVertexCData'); + cdata = permute(cdata,[1 3 2]); + end + indexed = ad{1}; + scalemode = ad{2}; + + %size consistency check + if all(size(indexed) == size(cdata(:,:,1))), + %ok, restore indexed cdata + if ~strcmp(get(hh,'type'),'patch'), + set(hh,'CData',indexed); + else + set(hh,'faceVertexCData',indexed); + end + %restore cdatamapping, if needed + g = get(hh); + if isfield(g,'CDataMapping'), + set(hh,'CDataMapping',scalemode); + end + %clear appdata + rmappdata(hh,appdatacode) + else + warning('JRI:unfreezeColors:internalCdataInconsistency',... + ['Could not restore indexed data: it is the wrong size. ' ... + 'Were the axis contents changed since the call to freezeColors?']) + end + + end %test if has our appdata + end %test ishandle + + end %loop on children + +end %loop on axes + diff --git a/TBM/Calculate_Alpha.m b/TBM/Calculate_Alpha.m new file mode 100644 index 0000000..7cf2420 --- /dev/null +++ b/TBM/Calculate_Alpha.m @@ -0,0 +1,69 @@ +%Shinjini Kundu (c) 2016 +%Transport-Based Morphometry analysis codes + +function [ Thresh, error_subspace ] = Calculate_Alpha( FINAL_FEATS, EIGENV1, labels, Curveoption ) +%This piece of code runs the PLDA function with different values of alpha +%and plots two error curves +%The projection metric distance of two consequent subspaces +%written originally by Soheil Kolouri, modified by Shinjini Kundu + +nPLDA = Curveoption.nPLDA; +counter = 0; + +x = Curveoption.low:Curveoption.step:Curveoption.high; + +for i = 1:size(FINAL_FEATS,2) + %load(char(strcat('eigenvector_',num2str(i)))); + VecPCA(:,i) = EIGENV1(:,i); +end + +VecPCA = double(VecPCA); + +for Alpha = x + Alpha; + counter = counter + 1; + [PLDA_directions] = PLDA(FINAL_FEATS', labels, Alpha, nPLDA); + Vec(:,:,counter) = VecPCA*PLDA_directions; + if counter > 1 + Vec(:,:,counter) = Vec(:,:,counter)*diag(sign(diag(Vec(:,:,counter)'*Vec(:,:,counter-1)))); + error_subspace(counter-1) = Projection_metric(Vec(:,:,counter),Vec(:,:,counter-1)); + end +end + +%Choose alpha such that the absolute value of the relative change does not exceed 0.2% +cutoff = 0.5; %0.015; +change = abs(gradient(double(error_subspace))); +ind = min(find(change*100 < cutoff)); + +%Calculate twice the half life of Alpha, + +% % % % %Fit an exponential to log(error_subspace) +% % % % f = @(a,b,x) log(a) - b*x; +% % % % options = fitoptions('Method','LinearLeastSquares'); +% % % % F_fitted = fit(x(1:end-1)',log(error_subspace)',f, ... +% % % % 'StartPoint', [1,x(1)], ... +% % % % 'Lower', [0,0], 'Robust', 'LAR'); +% % % % coeff = coeffvalues(F_fitted); %Get coefficients of fitted function +% % % % Thresh = log(2)*(1/coeff(2)); %Calculate twice the half life = 2(log(2)/b) + +Thresh = x(ind); +%Thresh = 1; %default value + +figure; +plot(x(1:end-1),error_subspace,'linewidth',2) +title({'Stability of subspace', 'with respect to \alpha'}, 'fontsize',24) +ylabel({'Projection metric between', 'two consequent subspaces'}, 'fontsize', 20); +xlabel('\alpha','fontsize',20); +grid on; +set(gca,'fontsize',20); +set(gca,'FontName','Times New Roman'); +yL = get(gca, 'YLim'); +hold on; +line([Thresh Thresh],yL,'Color','r','linewidth',2); + +% grid on; +% plot(x,coeff(1)*exp(- coeff(2)*x),'k'); %plot the exponential + + +end + diff --git a/TBM/DGradient/DGradient.c b/TBM/DGradient/DGradient.c new file mode 100644 index 0000000..5c31126 --- /dev/null +++ b/TBM/DGradient/DGradient.c @@ -0,0 +1,826 @@ +// DGradient.c +// Gradient along a dimension +// Y = DGradient(X, Dim, Spacing, Method) +// INPUT: +// X: Real DOUBLE array. +// Spacing: Scalar or vector of the length SIZE(X, Dim). +// A scalar value is the distance between all points, while a vector +// contains all coordinates, such that DIFF(Spacing) are the distances. +// For equally spaced input a scalar Spacing is much faster. +// Optional, default: 1.0 +// Dim: Dimension to operate on. +// Optional, default: [] (1st non-singelton dimension). +// Method: String, order of the applied method for unevenly spaced X: +// '1stOrder', faster centered differences as in Matlab's GRADIENT. +// '2ndOrder', 2nd order accurate centered differences. +// On the edges forward and backward difference are used. +// Optional, default: '1stOrder'. +// +// OUTPUT: +// Y: Gradient of X, same size as X. +// +// EXAMPLES: +// t = cumsum(rand(1, 100)) + 0.01; t = 2*pi * t ./ max(t); +// x = sin(t); +// dx1 = DGradient(x, t, 2, '1stOrder'); +// dx2 = DGradient(x, t, 2, '2ndOrder'); +// dx = cos(t); % Analytic solution +// h = plot(t, dx, t, dx1, 'or', t, dx2, 'og'); axis('tight'); +// title('cos(x) and DGradient(sin(x))'); +// legend(h, {'analytic', '1st order', '2nd order'}, 'location', 'best'); +// +// NOTES: +// - There are a lot of other derivation tools in the FEX. This function is +// faster, e.g. 25% faster than dqdt.c and 10 to 16 times faster than Matlab's +// GRADIENT. In addition it works with multi-dim arrays, on a speicifc +// dimension only and can use a 2nd order method for unevenly spaced data. +// - This function does not use temporary memory for evenly spaced data and if +// a single vector is processed. Otherwise the 1st-order method needs one and +// the 2nd-order method 3 temporary vectors of the length of the processed +// dimension. +// - Matlab's GRADIENT processes all dimensions ever, while DGradient operates on +// the specified dimension only. +// - 1st order centered difference: +// y(i) = (x(i+1) - x(i-1) / (s(i+1) - s(i-1)) +// - 2nd order centered difference: +// y(i) = ((x(i+1) * (s(i)-s(i-1)) / (s(i+1)-s(i))) - +// (x(i-1) * (s(i+1)-s(i)) / (s(i)-s(i-1)))) / (s(i+1)-s(i-1)) +// + x(i) * (1.0 / (s(i)-s(i-1)) - 1.0 / (s(i+1)-s(i))) +// For evenly spaced X, both methods reply equal values. +// +// COMPILE: +// mex -O DGradient.c +// Consider C99 comments on Linux: +// mex -O CFLAGS="\$CFLAGS -std=c99" DGradient.c +// Pre-compiled Mex: http://www.n-simon.de/mex +// Run the unit test uTest_DGradient after compiling. +// +// Tested: Matlab 6.5, 7.7, 7.8, WinXP, 32bit +// Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008 +// Assumed Compatibility: higher Matlab versions, Mac, Linux, 64bit +// Author: Jan Simon, Heidelberg, (C) 2011 matlab.THISYEAR(a)nMINUSsimon.de +// +// See also GRADIENT, DIFF. +// FEX: central_diff (#12 Robert A. Canfield) +// derivative (#28920, Scott McKinney) +// movingslope (#16997, John D'Errico) +// diffxy (#29312, Darren Rowland) +// dqdt (#11965, Geoff Wawrzyniak) + +// Todo: SSE2 instructions +// Newton polynomials for 2nd order edges +// Multi-threading + +/* +% $JRev: R0d V:004 Sum:sHhGcnzMMNaA Date:02-Jan-2008 17:46:05 $ +% $License: BSD $ +% $File: Tools\Mex\Source\DGradient.c $ +% History: +% 001: 30-Dec-2010 22:42, First version published under BSD license. +*/ + +// Includes: +#include "mex.h" +#include +#include +#include +#include + +// Assume 32 bit addressing for Matlab 6.5: +// See MEX option "compatibleArrayDims" for MEX in Matlab >= 7.7. +#ifndef MWSIZE_MAX +#define mwSize int32_T // Defined in tmwtypes.h +#define mwIndex int32_T +#define MWSIZE_MAX MAX_int32_T +#endif + +// There is an undocumented method to create a shared data copy. This is much +// faster, if the replied object is not changed, because it does not duplicate +// the contents of the array in the memory. +mxArray *mxCreateSharedDataCopy(const mxArray *mx); +#define COPY_ARRAY mxCreateSharedDataCopy +// #define COPY_ARRAY mxDuplicateArray // slower, but documented + +// Disable the /fp:precise flag to increase the speed on MSVC compiler: +#ifdef _MSC_VER +#pragma float_control(except, off) // disable exception semantics +#pragma float_control(precise, off) // disable precise semantics +#pragma fp_contract(on) // enable contractions +// #pragma fenv_access(off) // disable fpu environment sensitivity +#endif + +// Error messages do not contain the function name in Matlab 6.5! This is not +// necessary in Matlab 7, but it does not bother: +#define ERR_HEAD "*** DGradient[mex]: " +#define ERR_ID "JSimon:DGradient:" + +// Prototypes: ----------------------------------------------------------------- +void CoreDim1Space1(double *X, const mwSize M, const mwSize nDX, double Space, + double *Y); +void CoreDimNSpace1(double *X, const mwSize step, const mwSize nX, + const mwSize nDX, double Space, double *Y); + +void WrapSpaceN(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Factor, double *Y); +void GetFactor(double *Space, mwSize nDX, double *Factor); +void CoreDim1SpaceN(double *X, const mwSize M, const mwSize nDX, + double *Space, double *Y); +// void CoreDimNSpaceN(double *X, const mwSize step, const mwSize nX, +// const mwSize nDX, double *Space, double *Y); +void CoreDim1FactorN(double *X, const mwSize M, const mwSize nDX, + double *Factor, double *Y); +void CoreDimNFactorN(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Factor, double *Y); + +void WrapSpaceNOrder2(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Space, double *Y); +void GetFactorOrder2(double *Space, const mwSize nDX, + double *A, double *B, double *C); +void CoreDim1SpaceNOrder2(double *X, const mwSize nX, const mwSize nDX, + double *Space, double *Y); +void CoreDimNSpaceNOrder2(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Space, double *Y); +void CoreDim1FactorNOrder2(double *X, const mwSize nX, const mwSize nDX, + double *A, double *B, double *C, double *Y); +void CoreDimNFactorNOrder2(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *A, double *B, double *C, double *Y); + +mwSize FirstNonSingeltonDim(const mwSize Xndim, const mwSize *Xdim); +mwSize GetStep(const mwSize *Xdim, const mwSize N); + +// Main function =============================================================== +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) +{ + double *X, *Y, Nd, *Space, UnitSpace = 1.0; + mwSize nX, nDX, ndimX, N, Step, nSpace; + const mwSize *dimX; + int Order2 = 0; + + // Check number and type of inputs and outputs: ------------------------------ + if (nrhs == 0 || nrhs > 4) { + mexErrMsgIdAndTxt(ERR_ID "BadNInput", + ERR_HEAD "1 or 4 inputs required."); + } + if (nlhs > 1) { + mexErrMsgIdAndTxt(ERR_ID "BadNOutput", + ERR_HEAD "1 output allowed."); + } + + if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0])) { + mexErrMsgIdAndTxt(ERR_ID "BadTypeInput1", + ERR_HEAD "Input must be a full real double array."); + } + + // Pointers and dimension to input array: ------------------------------------ + X = mxGetPr(prhs[0]); + nX = mxGetNumberOfElements(prhs[0]); + ndimX = mxGetNumberOfDimensions(prhs[0]); + dimX = mxGetDimensions(prhs[0]); + + // Return fast on empty input matrix: + if (nX == 0) { + plhs[0] = COPY_ARRAY(prhs[0]); + return; + } + + // Get spacing, if defined: -------------------------------------------------- + if (nrhs < 2) { // No 2nd input defined - scalar unit spacing: + nSpace = 1; + Space = &UnitSpace; + + } else { // Get pointer to spacing vector: + if (!mxIsDouble(prhs[1])) { + mexErrMsgIdAndTxt(ERR_ID "BadTypeInput2", + ERR_HEAD "2nd input [Spacing] must be a DOUBLE."); + } + Space = mxGetPr(prhs[1]); + nSpace = mxGetNumberOfElements(prhs[1]); + if (nSpace == 0) { + nSpace = 1; + Space = &UnitSpace; + } + } + + // Determine dimension to operate on: ---------------------------------------- + if (nrhs < 3) { + N = FirstNonSingeltonDim(ndimX, dimX); // Zero based + Step = 1; + nDX = dimX[N]; + + } else if (mxIsNumeric(prhs[2])) { // 3rd input used: + switch (mxGetNumberOfElements(prhs[2])) { + case 0: // Use 1st non-singelton dim if 3rd input is []: + N = FirstNonSingeltonDim(ndimX, dimX); + Step = 1; + nDX = dimX[N]; + break; + + case 1: // Numerical scalar: + Nd = mxGetScalar(prhs[2]); + N = (mwSize) Nd - 1; + if (Nd < 1.0 || Nd != floor(Nd)) { + mexErrMsgIdAndTxt(ERR_ID "BadValueInput3", + ERR_HEAD "Dimension must be a positive integer scalar."); + } + + if (N < ndimX) { + Step = GetStep(dimX, N); + nDX = dimX[N]; + } else { + // Treat imaginated trailing dimensions as singelton, as usual in + // Matlab: + Step = nX; + nDX = 1; + } + break; + + default: + mexErrMsgIdAndTxt(ERR_ID "BadSizeInput3", + ERR_HEAD "3rd input [Dim] must be scalar index."); + } + + } else { // 2nd input is not numeric: + mexErrMsgIdAndTxt(ERR_ID "BadTypeInput3", + ERR_HEAD "3rd input must be scalar index."); + } + + // Check matching sizes of X and Spacing: + if (nSpace != 1 && nSpace != nDX) { + mexErrMsgIdAndTxt(ERR_ID "BadSizeInput2", + ERR_HEAD "2nd input [Spacing] does not match the dimensions."); + } + + // Check 4th input: ---------------------------------------------------------- + if (nrhs >= 4) { + // "2ndOrder", but accept everything starting with "2": + if (mxIsChar(prhs[3]) && !mxIsEmpty(prhs[3])) { + Order2 = (*(mxChar *) mxGetData(prhs[3]) == L'2'); + } else { + mexErrMsgIdAndTxt(ERR_ID "BadTypeInput4", + ERR_HEAD "4th input must be a string."); + } + } + + // Create output matrix: ----------------------------------------------------- + plhs[0] = mxCreateNumericArray(ndimX, dimX, mxDOUBLE_CLASS, mxREAL); + Y = mxGetPr(plhs[0]); + + // Reply ZEROS, if the length of the processed dimension is 1: + if (nDX == 1) { + return; + } + + // Calculate the gradient: --------------------------------------------------- + if (nSpace == 1) { // Scalar spacing + if (Step == 1) { // Operate on 1st dimension + CoreDim1Space1(X, nX, nDX, *Space, Y); + } else { // Step >= 1, operate on any dimension + CoreDimNSpace1(X, Step, nX, nDX, *Space, Y); + } + + } else if (Order2) { // Spacing defined as vector, 2nd order method: + if (nX == nDX) { // Single vector only - dynamic spacing factors: + CoreDim1SpaceNOrder2(X, nX, nDX, Space, Y); + } else { + WrapSpaceNOrder2(X, Step, nX, nDX, Space, Y); + } + + } else { // Spacing defined as vector, 1st order method: + if (nX == nDX) { // Single vector only - dynamic spacing factors: + CoreDim1SpaceN(X, nX, nDX, Space, Y); + } else { + WrapSpaceN(X, Step, nX, nDX, Space, Y); + } + } + + return; +} + +// Subroutines: ================================================================ +mwSize FirstNonSingeltonDim(const mwSize Xndim, const mwSize *Xdim) +{ + // Get first non-singelton dimension - zero based. + + mwSize N; + + for (N = 0; N < Xndim; N++) { + if (Xdim[N] != 1) { + return (N); + } + } + + return (0); // Use the first dimension if all dims are 1 +} + +// ============================================================================= +mwSize GetStep(const mwSize *Xdim, const mwSize N) +{ + // Get step size between elements of a subvector in the N'th dimension. + // This is the product of the leading dimensions. + + const mwSize *XdimEnd, *XdimP; + mwSize Step; + + Step = 1; + XdimEnd = Xdim + N; + for (XdimP = Xdim; XdimP < XdimEnd; Step *= *XdimP++) ; // empty loop + + return (Step); +} + +// ============================================================================= +void CoreDim1Space1(double *X, const mwSize nX, const mwSize nDX, double Space, + double *Y) +{ + // Operate on first dimension, scalar spacing, 1st order method. + + double x0, x1, x2, *Xf, *Xc, fac1, fac2; + + // Multiplication is faster than division: + fac1 = 1.0 / Space; + fac2 = 1.0 / (2.0 * Space); + + Xf = X + nX; // End of input array + while (X < Xf) { + Xc = X + nDX; + + x0 = *X++; // Forward difference: + x1 = *X++; + *Y++ = (x1 - x0) * fac1; + + while (X < Xc) { // Central differences: + x2 = *X++; + *Y++ = (x2 - x0) * fac2; + x0 = x1; + x1 = x2; + } + + *Y++ = (x1 - x0) * fac1; // Backward difference + } + + return; +} + +// ============================================================================= +void CoreDimNSpace1(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double Space, double *Y) +{ + // Operate on any dimension, scalar spacing, 1st order method. + // Column oriented approach: Process contiguous memory blocks of input and + // output. + + double *Xf, *X1, *X2, *Xc, fac1, fac2; + mwSize nDXStep; + + // Multiplication is faster than division: + fac1 = 1.0 / Space; + fac2 = 1.0 / (2.0 * Space); + + // Distance between first and last element of X in specified dim: + nDXStep = nDX * Step; + + Xf = X + nX; // End of the input array + while (X < Xf) { + X1 = X; // Forward differences: + X2 = X1 + Step; + Xc = X2; + while (X1 < Xc) { + *Y++ = (*X2++ - *X1++) * fac1; + } + + X1 = X; // Central differences: + Xc = X + nDXStep; + while (X2 < Xc) { + *Y++ = (*X2++ - *X1++) * fac2; + } + + X2 = X1 + Step; // Backward differences: + while (X2 < Xc) { + *Y++ = (*X2++ - *X1++) * fac1; + } + + X = Xc; // Move input pointer to the next chunk + } + + return; +} + +// ============================================================================= +void WrapSpaceN(double *X, const mwSize Step, const mwSize nX, const mwSize nDX, + double *Space, double *Y) +{ + // Call different methods depending of the dimensions ofthe input. + // X has more than 1 vector. Therefore precalculating the spacing factors is + // cheaper. + + double *Factor; + + // Precalculate spacing factors: + if ((Factor = (double *) mxMalloc(nDX * sizeof(double))) == NULL) { + mexErrMsgIdAndTxt(ERR_ID "NoMemory", + ERR_HEAD "No memory for Factor vector."); + } + GetFactor(Space, nDX, Factor); + + if (Step == 1) { // Operate on 1st dimension: + CoreDim1FactorN(X, nX, nDX, Factor, Y); + } else { // Operate on any dimension: + CoreDimNFactorN(X, Step, nX, nDX, Factor, Y); + } + + mxFree(Factor); + + return; +} + +// ============================================================================= +void CoreDim1SpaceN(double *X, const mwSize nX, const mwSize nDX, + double *Space, double *Y) +{ + // Operate on the first dimension, spacing is a vector, order 1 method. + // The spacing factors are calculated dynamically. This is efficient for + // a single vector, but slower for matrices. No temporary vector is needed. + + double x0, x1, x2, *Xf, *Xg, *Sp, s0, s1, s2; + + Xf = X + nX; + while (X < Xf) { + Xg = X + nDX; // Forward difference + x0 = *X++; + x1 = *X++; + Sp = Space; + s0 = *Sp++; + s1 = *Sp++; + *Y++ = (x1 - x0) / (s1 - s0); + + while (X < Xg) { // Central differences + x2 = *X++; + s2 = *Sp++; + *Y++ = (x2 - x0) / (s2 - s0); + x0 = x1; + x1 = x2; + s0 = s1; + s1 = s2; + } + + *Y++ = (x1 - x0) / (s1 - s0); // Backward difference + } + + return; +} + +// ============================================================================= +void GetFactor(double *Space, mwSize nDX, double *F) +{ + // If more than one vector is processed, it is cheaper to calculate the spacing + // factors once. This needs the memory for a temporary vector. + // INPUT: + // Space: Pointer to DOUBLE vector from the inputs. + // nDX: Length of the Space vector. + // OUTPUT: + // F: Factors, pointer to DOUBLE vector: + // [ 1/(S[1]-S[0]), 1/(S[i+1]-S[i-1]), 1/(S[nDX-1]-S[nDX-2]) ] + + double s0, s1, s2, *Ff; + + Ff = F + nDX - 1; + s0 = *Space++; + s1 = *Space++; + *F++ = 1.0 / (s1 - s0); + + while (F < Ff) { + s2 = *Space++; + *F++ = 1.0 / (s2 - s0); + s0 = s1; + s1 = s2; + } + + *F = 1.0 / (s1 - s0); + + return; +} + +// ============================================================================= +void CoreDim1FactorN(double *X, const mwSize nX, const mwSize nDX, + double *Factor, double *Y) +{ + // Operate on first dimension, spacing is a vector, 1st order method. + // The spacing factors are calculated before. This needs a temporary vector + // of nDX elements. It is faster than the dynamically calculated spacing + // factors. + + double x0, x1, x2, *Xf, *Xc, *Fp; + + Xf = X + nX; + while (X < Xf) { + Xc = X + nDX; // End of column + x0 = *X++; // Forward difference + x1 = *X++; + Fp = Factor; + *Y++ = (x1 - x0) * *Fp++; + + while (X < Xc) { // Central differences + x2 = *X++; + *Y++ = (x2 - x0) * *Fp++; + x0 = x1; + x1 = x2; + } + + *Y++ = (x1 - x0) * *Fp; // Backward difference + } + + return; +} + +// ============================================================================= +void CoreDimNFactorN(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Factor, double *Y) +{ + // Operate on any dimension, spacing is a vector, 1st order method. + // The spacing factors are calculated before. This needs a temporary vector + // of nDX elements. This is faster than the dynamically calculated spacing + // factors, if more than one vector is processed. + + double *Xf, *X1, *X2, *Xc, *Fp, *Ff; + + Ff = Factor + nDX - 1; // Zero-based indexing! + + Xf = X + nX; // End of the array + while (X < Xf) { + X1 = X; // Forward differences: + X2 = X1 + Step; // Element of second column + Xc = X2; // End of first column + Fp = Factor; + while (X1 < Xc) { + *Y++ = (*X2++ - *X1++) * *Fp; + } + + X1 = X; // Central differences: + Xc += Step; + while (++Fp < Ff) { + Xc += Step; + while (X2 < Xc) { + *Y++ = (*X2++ - *X1++) * *Fp; + } + } + + X2 = X1 + Step; // Backward differences: + while (X2 < Xc) { + *Y++ = (*X2++ - *X1++) * *Fp; + } + + X = Xc; // Move input pointer to the next chunk + } + + return; +} + +// ============================================================================= +void WrapSpaceNOrder2(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Space, double *Y) +{ + // Call different methods depending of the dimensions ofthe input. + // X has more than one vector. Therefore it is cheaper to calculate the + // spacing factors once only. + + double *A, *B, *C; + + // Precalculate spacing factors: + A = (double *) mxMalloc(nDX * sizeof(double)); + B = (double *) mxMalloc(nDX * sizeof(double)); + C = (double *) mxMalloc(nDX * sizeof(double)); + + if (A == NULL || B == NULL || C == NULL) { + mexErrMsgIdAndTxt(ERR_ID "NoMemory", + ERR_HEAD "No memory for Factor vectors."); + } + + GetFactorOrder2(Space, nDX, A, B, C); + + if (Step == 1) { // Operate on first dimension: + //CoreDim1FactorNOrder2(X, nX, nDX, A, B, C, Y); + CoreDim1SpaceNOrder2(X, nX, nDX, Space, Y); + } else { // Operate on any dimension: + //CoreDimNFactorNOrder2(X, Step, nX, nDX, A, B, C, Y); + CoreDimNSpaceNOrder2(X, Step, nX, nDX, Space, Y); + } + + mxFree(A); + mxFree(B); + mxFree(C); + + return; +} + +// ============================================================================= +void GetFactorOrder2(double *Space, const mwSize nDX, + double *A, double *B, double *C) +{ + // Calculate spacing factors for 2nd order method. + + double s0, s1, s2, s10, s21, *Sf; + + Sf = Space + nDX; + + s0 = *Space++; + s1 = *Space++; + s10 = s1 - s0; + *A++ = 1.0 / s10; + B++; + C++; + + while (Space < Sf) { + s2 = *Space++; + s21 = s2 - s1; + *A++ = s10 / (s21 * (s2 - s0)); + *B++ = 1.0 / s10 - 1.0 / s21; + *C++ = s21 / (s10 * (s2 - s0)); + s0 = s1; + s1 = s2; + s10 = s21; + } + + *A = 1.0 / s10; + + return; +} + +// ============================================================================= +void CoreDim1SpaceNOrder2(double *X, const mwSize nX, const mwSize nDX, + double *Space, double *Y) +{ + // Operate on first dimension, spacing is a vector, 2nd order method. + // For unevenly spaced data this algorithm is 2nd order accurate. + // This is fast for a single vector, while for arrays with more dimensions + // is is cheaper to calculate the spacing factors once externally. + + double x0, x1, x2, *Xf, *Xc, *Sp, s0, s1, s2, s10, s21; + + Xf = X + nX; + while (X < Xf) { + Xc = X + nDX; // Forward difference (same as for evenly spaced X) + x0 = *X++; + x1 = *X++; + Sp = Space; + s0 = *Sp++; + s1 = *Sp++; + s10 = s1 - s0; + *Y++ = (x1 - x0) / s10; + + while (X < Xc) { // Central differences, 2nd order method + x2 = *X++; + s2 = *Sp++; + s21 = s2 - s1; + *Y++ = ((x2 * s10 / s21) - (x0 * s21 / s10)) / (s2 - s0) + + x1 * (1.0 / s10 - 1.0 / s21); + x0 = x1; + x1 = x2; + s0 = s1; + s1 = s2; + s10 = s21; + } + + *Y++ = (x1 - x0) / s10; // Backward difference + } + + return; +} + +// ============================================================================= +void CoreDimNSpaceNOrder2(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *Space, double *Y) +{ + // Operate on any dimension, spacing is a vector, 2nd order method. + // The spacing factors are calculated dynamically. This is about 50% slower + // than calculating the spacing factors at first. I assume the number of + // registers are exhausted. Therefore this method is useful only, if the + // memory is nearly full. + + double *Xf, *X0, *X1, *X2, *Xc, *Sp, *Sb; + register double a, b, c; + double s0, s1, s2; + + Sb = Space + nDX; + + Xf = X + nX; // End of the array + while (X < Xf) { + X0 = X; // Forward differences for first column: + X1 = X; + X2 = X0 + Step; // Element of second column + Xc = X2; // End of first column + Sp = Space; + s0 = *Sp++; + s1 = *Sp++; + c = 1.0 / (s1 - s0); + while (X1 < Xc) { + *Y++ = (*X2++ - *X1++) * c; + } + + Xc += Step; // Central differences: + while (Sp < Sb) { + s2 = *Sp++; + a = (s1 - s0) / ((s2 - s1) * (s2 - s0)); + b = 1.0 / (s1 - s0) - 1.0 / (s2 - s1); + c = (s2 - s1) / ((s1 - s0) * (s2 - s0)); + Xc += Step; + while (X2 < Xc) { + *Y++ = *X2++ * a + *X1++ * b - *X0++ * c; + } + s0 = s1; + s1 = s2; + } + + c = 1.0 / (s1 - s0); // Backward differences: + while (X1 < Xc) { + *Y++ = (*X1++ - *X0++) * c; + } + + X = Xc; // Move input pointer to the next chunk + } + + return; +} + +// ============================================================================= +void CoreDim1FactorNOrder2(double *X, const mwSize nX, const mwSize nDX, + double *A, double *B, double *C, double *Y) +{ + // Operate on first dimension, spacing is a vector, 2nd order method. + // For unevenly spaced data this algorithm is 2nd order accurate. + // This is fast for a single vector, while for arrays with more dimensions + // is is cheaper to calculate the spacing factors once externally. + + double x0, x1, x2, *Xf, *Xc, *a, *b, *c; + + Xf = X + nX; + while (X < Xf) { + Xc = X + nDX; // Forward difference (same as for evenly spaced X) + x0 = *X++; + x1 = *X++; + a = A; + b = B + 1; + c = C + 1; + *Y++ = (x1 - x0) * *a++; + + while (X < Xc) { // Central differences, 2nd order method + x2 = *X++; + *Y++ = x2 * *a++ + x1 * *b++ - x0 * *c++; + x0 = x1; + x1 = x2; + } + + *Y++ = (x1 - x0) * *a; // Backward difference + } + + return; +} + +// ============================================================================= +void CoreDimNFactorNOrder2(double *X, const mwSize Step, const mwSize nX, + const mwSize nDX, double *A, double *B, double *C, + double *Y) +{ + // Operate on any dimension, spacing is a vector, 2nd order method. + // The spacing factors are calculated externally once only. + + double *Xf, *X0, *X1, *X2, *Xc, *Af, *a, *b, *c; + register double a_, b_, c_; + + Af = A + nDX - 1; + + Xf = X + nX; // End of the array + while (X < Xf) { + X0 = X; // Forward differences for first column: + X1 = X; + X2 = X0 + Step; // Element of second column + Xc = X2; // End of first column + a = A; + b = B + 1; + c = C + 1; + a_ = *a; + while (X1 < Xc) { + *Y++ = (*X2++ - *X1++) * a_; + } + + Xc += Step; // Central differences: + a++; + while (a < Af) { + Xc += Step; + a_ = *a++; + b_ = *b++; + c_ = *c++; + while (X2 < Xc) { + *Y++ = *X2++ * a_ + *X1++ * b_ - *X0++ * c_; + } + } + + a_ = *a; // Backward differences: + while (X1 < Xc) { + *Y++ = (*X1++ - *X0++) * a_; + } + + X = Xc; // Move input pointer to the next chunk + } + + return; +} diff --git a/TBM/DGradient/DGradient.m b/TBM/DGradient/DGradient.m new file mode 100644 index 0000000..e9e16b3 --- /dev/null +++ b/TBM/DGradient/DGradient.m @@ -0,0 +1,79 @@ +function Y = DGradient(X, Dim, Spacing, Method) %#ok +% Gradient along a dimension +% Y = DGradient(X, Dim, Spacing, Method) +% INPUT: +% X: Real DOUBLE array. +% Spacing: Scalar or vector of the length SIZE(X, Dim). +% A scalar value is the distance between all points, while a vector +% contains all time points, such that DIFF(Spacing) are the distances. +% For equally spaced input a scalar Spacing is much faster. +% Optional, default: 1.0 +% Dim: Dimension to operate on. +% Optional, default: [] (1st non-singelton dimension). +% Method: String, order of the applied method for unevenly spaced X: +% '1stOrder', faster centered differences as in Matlab's GRADIENT. +% '2ndOrder', 2nd order accurate centered differences. +% On the edges forward and backward difference are used. +% Optional, default: '1stOrder'. +% +% OUTPUT: +% Y: Gradient of X, same size as X. +% +% EXAMPLES: +% t = cumsum(rand(1, 100)) + 0.01; t = 2*pi * t ./ max(t); +% x = sin(t); +% dx1 = DGradient(x, t, 2, '1stOrder'); +% dx2 = DGradient(x, t, 2, '2ndOrder'); +% dx = cos(t); % Analytic solution +% h = plot(t, dx, t, dx1, 'or', t, dx2, 'og'); axis('tight'); +% title('cos(x) and DGradient(sin(x))'); +% legend(h, {'analytic', '1st order', '2nd order'}, 'location', 'best'); +% +% NOTES: +% - There are a lot of other derivation tools in the FEX. This function is +% faster, e.g. 25% faster than dqdt and 10 to 16 times faster than Matlab's +% GRADIENT. In addition it works with multi-dim arrays, on a specific +% dimension only, and can use a 2nd order method for unevenly spaced data. +% - This function does not use temporary memory for evenly spaced data and if +% a single vector is processed. Otherwise the 1st-order method needs one and +% the 2nd-order method 3 temporary vectors of the length of the processed +% dimension. +% - Matlab's GRADIENT processes all dimensions ever, while DGradient operates on +% the specified dimension only. +% - 1st order centered difference: +% y(i) = (x(i+1) - x(i-1) / (s(i+1) - s(i-1)) +% - 2nd order centered difference: +% y(i) = ((x(i+1) * (s(i)-s(i-1)) / (s(i+1)-s(i))) - +% (x(i-1) * (s(i+1)-s(i)) / (s(i)-s(i-1)))) / (s(i+1)-s(i-1)) +% + x(i) * (1.0 / (s(i)-s(i-1)) - 1.0 / (s(i+1)-s(i))) +% For evenly spaced X, both methods reply equal values. +% +% COMPILE: +% mex -O DGradient.c +% Consider C99 comments on Linux: +% mex -O CFLAGS="\$CFLAGS -std=c99" DGradient.c +% Pre-compiled Mex: http://www.n-simon.de/mex +% Run the unit test uTest_DGradient after compiling. +% +% Tested: Matlab 6.5, 7.7, 7.8, WinXP, 32bit +% Compiler: LCC2.4/3.8, BCC5.5, OWC1.8, MSVC2008 +% Assumed Compatibility: higher Matlab versions, Mac, Linux, 64bit +% Author: Jan Simon, Heidelberg, (C) 2011 matlab.THISYEAR(a)nMINUSsimon.de +% +% See also GRADIENT, DIFF. +% FEX: central_diff (#12 Robert A. Canfield) +% derivative (#28920, Scott McKinney) +% movingslope (#16997, John D'Errico) +% diffxy (#29312, Darren Rowland) +% dqdt (#11965, Geoff Wawrzyniak) + +% $JRev: R0c V:003 Sum:RkNcmbCGEJGT Date:02-Jan-2010 02:41:46 $ +% $License: BSD $ +% $File: Tools\Mex\Source\DGradient.c $ +% History: +% 001: 30-Dec-2010 22:42, First version published under BSD license. + +% This is a dummy file to support Matlab's HELP. + +error(['JSimon:', mfilename, ':NoMex'], ... + 'Cannot find compiled Mex.\nPlease compile at first: mex -O DGradient.c'); diff --git a/TBM/DGradient/DGradient.mexmaci64 b/TBM/DGradient/DGradient.mexmaci64 new file mode 100644 index 0000000..d03b872 Binary files /dev/null and b/TBM/DGradient/DGradient.mexmaci64 differ diff --git a/TBM/DGradient/license.txt b/TBM/DGradient/license.txt new file mode 100644 index 0000000..6b44dae --- /dev/null +++ b/TBM/DGradient/license.txt @@ -0,0 +1,24 @@ +Copyright (c) 2011, Jan Simon +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the distribution + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/TBM/DGradient/uTest_DGradient.m b/TBM/DGradient/uTest_DGradient.m new file mode 100644 index 0000000..a2f6a28 --- /dev/null +++ b/TBM/DGradient/uTest_DGradient.m @@ -0,0 +1,463 @@ +function uTest_DGradient(doSpeed) +% Unit test: DGradient +% This is a routine for automatic testing. It is not needed for processing and +% can be deleted or moved to a folder, where it does not bother. +% +% uTest_DGradient(doSpeed) +% INPUT: +% doSpeed: If ANY(doSpeed) is TRUE, the speed is measured. +% OUTPUT: +% On failure the test stops with an error. +% +% Tested: Matlab 6.5, 7.7, 7.8, WinXP +% Author: Jan Simon, Heidelberg, (C) 2009-2011 matlab.THISYEAR(a)nMINUSsimon.de + +% $JRev: R0k V:010 Sum:jVli3Fk6CFXC Date:02-Jan-2010 02:42:11 $ +% $License: BSD $ +% $File: Tools\UnitTests_\uTest_DGradient.m $ + +% Initialize: ================================================================== +% Global Interface: ------------------------------------------------------------ +ErrID = ['JSimon:', mfilename]; + +hasDerivative = ~isempty(which('derivative')); +hasCentral_Diff = ~isempty(which('central_diff')); +hasDiffXY = ~isempty(which('diffxy')); + +% Initial values: -------------------------------------------------------------- +LF = char(10); + +% Program Interface: ----------------------------------------------------------- +if nargin == 0 + doSpeed = true; +end + +randTestTime = 0.5; % Time for random tests + +% User Interface: -------------------------------------------------------------- +% Do the work: ================================================================= +disp(['==== Test DGradient ', datestr(now, 0)]); +disp([' Version: ', which('DGradient')]); +pause(0.01); % Flush events + +Y = DGradient([]); +Y = DGradient([], 1); +Y = DGradient([], 2); +Y = DGradient([], 3); +disp(' ok: DGradient([])'); + +Y0 = DGradient(1); +Y1 = DGradient(1, 1); +Y2 = DGradient(1, 2); +Y3 = DGradient(1, 3); +if Y0 == 0 && Y1 == 0 && Y2 == 0 && Y3 == 0 + disp(' ok: DGradient(1) is 0') +else + error('*** DGradient(1) ~= 0'); +end + +x = [1, 2; 3, 4]; +Y1 = DGradient(x, 1.0, 1); +Y2 = DGradient(x, 1.0, 2); +if isequal(Y1, 2*ones(2)) && isequal(Y2, ones(2)) + disp(' ok: DGradient([1,2;3,4]) no interior points'); +else + error('*** Bad reply for DGradient([1,2;3,4])'); +end + +x = [1, 2, 3; 4, 5, 6; 7, 8, 9]; +Y1 = DGradient(x, 1.0, 1); +Y2 = DGradient(x, 1.0, 2); +if isequal(Y1, 3*ones(3)) && isequal(Y2, ones(3)) + disp(' ok: DGradient([1:3;4:6,7:9]) one interior point'); +else + error('*** Bad reply for DGradient([1:3;4:6,7:9])'); +end + +x = [1, 4, 9; 16, 25, 36; 49, 64, 81]; +Y1 = DGradient(x, 1.0, 1); +Y2 = DGradient(x, 1.0, 2); +if max(abs(Y1(:) - [15; 24; 33; 21; 30; 39; 27; 36; 45])) < 10*eps && ... + max(abs(Y2(:) - [3; 9; 15; 4; 10; 16; 5; 11; 17])) < 10*eps + disp(' ok: DGradient([1:3;4:6,7:9].^2) one interior point'); +else + error('*** Bad reply for DGradient([1:3;4:6,7:9].^2)'); +end + +x = rand(1, 1000); +y = DGradient(x); +y2 = gradient(x); +if max(abs(y2 - y)) < 10*eps + disp(' ok: DGradient(rand(1, 1000)) equals GRADIENT'); +else + error('*** DGradient(rand(1, 1000)) differs from GRADIENT'); +end + +y = DGradient(x, 1.0, 1); +if isequal(y, zeros(size(x))) + disp(' ok: DGradient(rand(1, 1000), 1.0, 1) equals ZEROS'); +else + error('*** DGradient(rand(1, 1000), 1.0, 1) differs from ZEROS'); +end + +y = DGradient(x); +y2 = DGradient(x, 1.0); +if max(abs(y2 - y)) < 10*eps + disp(' ok: DGradient(X, 1.0) equals DGradient(X)'); +else + error('*** DGradient(X, 1.0) differs DGradient(X)'); +end + +y1 = DGradient(x, 1.0, 2); +y2 = DGradient([x;x], 1.0, 2); +if max(abs(y2(1, :) - y1)) < 10*eps && max(abs(y2(2, :) - y1)) < 10*eps + disp(' ok: DGradient([X; X]) equals [DGradient(X); DGradient(X)]'); +else + error('*** DGradient([X; X]) differs [DGradient(X); DGradient(X)]'); +end + +y2 = DGradient(x', 1.0, 1); +y3 = DGradient([x', x'], 1.0, 1); +if isequal(y1, y2') && ... + max(abs(y3(:, 1)' - y1)) < 10*eps && max(abs(y3(:, 2)' - y1)) < 10*eps + disp(' ok: DGradient([X'', X'']) equals [DGradient(X); DGradient(X)]'''); +else + error('*** DGradient([X'', X'']) differs [DGradient(X); DGradient(X)]'''); +end + +% Get both directions for a matrix - GRADIENT swaps the output! +X = rand(4, 1000); +Y1 = DGradient(X, [], 1); +Y2 = DGradient(X, [], 2); +[G1, G2] = gradient(X); +if max(abs(Y1(:) - G2(:))) < 10*eps && max(abs(Y2(:) - G1(:))) < 10*eps + disp(' ok: DGradient(rand(4, 1000)) equals GRADIENT'); +else + error('*** DGradient(rand(4, 1000)) differs from GRADIENT'); +end + +X = rand(4, 5, 6); +Y1 = DGradient(X, [], 1); +Y2 = DGradient(X, [], 2); +Y3 = DGradient(X, [], 3); +[G1, G2, G3] = gradient(X); +if max(abs(Y1(:) - G2(:))) < 10*eps && max(abs(Y2(:) - G1(:))) < 10*eps ... + && max(abs(Y3(:) - G3(:))) < 10*eps + disp(' ok: DGradient(rand(4, 5, 6)) equals GRADIENT'); +else + error('*** DGradient(rand(4, 5, 6)) differs from GRADIENT'); +end + +% Unevenly spaced data: -------------------------------------------------------- +% Lines or rows must be equal for a [2x2] matrix, because forward and backward +% differences are equal: +x = [1, 7; 11, 19]; +t = [1, 3]; +Y1 = DGradient(x, t, 1); +Y2 = DGradient(x, t, 2); +wantY1 = [5, 6; 5, 6]; +wantY2 = [3, 3; 4, 4]; +if max(abs(Y1(:) - wantY1(:))) < 10*eps && ... + max(abs(Y2(:) - wantY2(:))) < 10*eps + disp(' ok: DGradient([1,7;11,19], [1,3]) no interior point'); +else + error('*** Bad reply for DGradient([1,7;11,19], [1,3])'); +end + +x = [1, 4, 9; 16, 25, 36; 49, 64, 81]; +t = [1, 5, 13]; +Y1 = DGradient(x, t, 1); +Y2 = DGradient(x, t, 2); +wantY1 = [3.75; 4; 4.125; 5.25; 5; 4.875; 6.75; 6; 5.625]; +wantY2 = [2.25; 6.75; 11.25; 2; 5; 8; 1.875; 4.125; 6.375] / 3; +if max(abs(Y1(:) - wantY1)) < 10*eps && ... + max(abs(Y2(:) - wantY2)) < 10*eps + disp(' ok: DGradient([1:3;4:6,7:9].^2, [1,5,13]) one interior point'); +else + error('*** Bad reply for DGradient([1:3;4:6,7:9].^2, [1,5,13])'); +end + +% The method for unevenly spaces input is applied if the Spacing is defined as +% vector, also if it is evenly spaced: +x = rand(50, 50, 50); +t = (1:50) / 2; +Y1 = DGradient(x, t, 1); +Y2 = DGradient(x, t, 2); +Y3 = DGradient(x, t, 3); +E1 = DGradient(x, 0.5, 1); +E2 = DGradient(x, 0.5, 2); +E3 = DGradient(x, 0.5, 3); +if max(abs(Y1(:) - E1(:))) < 10*eps && ... + max(abs(Y2(:) - E2(:))) < 10*eps && ... + max(abs(Y3(:) - E3(:))) < 10*eps + disp(' ok: DGradient(X, ONES(1,N)) equals DGradient(X, 1.0)'); +else + error('*** DGradient(X, ONES(1,N)) differs from DGradient(X, 1.0)'); +end + +% Get mean difference between 1st and 2nd order method for: d/dx(sin(x)) +t = cumsum(rand(1, 100))+0.01; +t = 2*pi * t ./ max(t); +x = sin(t); +dx1 = DGradient(x, t, 2, '1stOrder'); +dx2 = DGradient(x, t, 2, '2ndOrder'); +dx = cos(t); % Analytic solution + +% Plot the diagrams, if the test function was called without inputs: +if nargin == 0 + figure('NumberTitle', 'off', 'Name', [mfilename, ' 1'], 'ToolBar', 'none'); + h1 = plot(t, dx, t, dx1, 'or', t, dx2, 'og'); + axis('tight'); + title('cos(x) and DGradient(sin(x))'); + + Fig2 = figure('NumberTitle', 'off', 'Name', [mfilename, ' 2'], ... + 'ToolBar', 'none'); + set(Fig2, 'Position', get(Fig2, 'Position') + [20, -20, 0, 0]); + h2 = plot(t, dx - dx1, 'r', t, dx- dx2, 'g'); + axis('tight'); + title('cos(x) - DGradient(sin(x))'); + + if sscanf(version, '%d', 1) >= 7 + Location = {'location', 'SouthEast'}; + else + Location = {4}; + end + legend(h1, {'analytic', '1st order', '2nd order'}, Location{:}); + legend(h2, {'1st order', '2nd order'}, Location{:}); + + drawnow; +end + +fprintf('\nCompare DGradient(sin(x)) and cos(x):\n'); +fprintf(' 1st order: mean(abs)=%.8f min=%.8f max=%.8f\n', ... + mean(abs(dx-dx1)), min(dx-dx1), max(dx-dx1)); +fprintf(' 2nd order: mean(abs)=%.8f min=%.8f max=%.8f\n', ... + mean(abs(dx-dx2)), min(dx-dx2), max(dx-dx2)); +if mean(abs(dx-dx1)) / 10 > mean(abs(dx-dx2)) + disp(' ok: mean error(2nd order) < 10 * mean error(1st order)'); +else % A failure is very unlikely, but RAND values are dangerous ever... + % This test fails if t is nearly evenly spaced. + error(['*** Mean error of 2nd order method greater than expected!\n', ... + ' Please run the test again.']); +end + +% Speed comparisons: ----------------------------------------------------------- +if doSpeed + fprintf('\n== Speed comparison:\n'); + LenList = [10, 1000, 2000, 4000, 8000, 16000, 32000, 64000]; + unevenT = cumsum(rand(1, LenList(length(LenList)))) + 0.01; + + HeadFmt = ' %-13s '; + fprintf('%-16s', '[1 x N], N ='); + fprintf('%8d', LenList); + fprintf('\nEvenly spaced:\n'); + fprintf(HeadFmt, 'GRADIENT:'); + for Len = LenList + x = rand(1, Len); + + nLoop = GetNLoop(@gradient, {x}); + tic; + for i = 1:nLoop + dx = gradient(x); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + + if hasDerivative + fprintf(HeadFmt, 'derivative:'); + for Len = LenList + x = rand(1, Len); + + nLoop = GetNLoop(@derivative, {x}); + tic; + for i = 1:nLoop + dx = derivative(x); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + end + + fprintf(HeadFmt, 'DGradient:'); + for Len = LenList + x = rand(1, Len); + + nLoop = GetNLoop(@DGradient, {x}); + tic; + for i = 1:nLoop + dx = DGradient(x); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + + % Unevenly spaced: ---------------------------------------------------------- + fprintf('Unevenly spaced, 1st order:\n'); + fprintf(HeadFmt, 'GRADIENT:'); + for Len = LenList + x = rand(1, Len); + t = unevenT(1:Len); + + nLoop = GetNLoop(@gradient, {x, t}); + tic; + for i = 1:nLoop + dx = gradient(x, t); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + + fprintf(HeadFmt, 'DGradient:'); + for Len = LenList + x = rand(1, Len); + t = unevenT(1:Len); + + nLoop = GetNLoop(@DGradient, {x, t}); + tic; + for i = 1:nLoop + dx = DGradient(x, t); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + + % 2nd order unevenly spaced: ------------------------------------------------ + fprintf('Unevenly spaced, 2nd order:\n'); + if hasCentral_Diff + fprintf(HeadFmt, 'central_diff:'); + for Len = LenList + x = rand(1, Len); + t = unevenT(1:Len); + + nLoop = GetNLoop(@central_diff, {x, t}); + tic; + for i = 1:nLoop + dx = central_diff(x, t); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + end + + if hasDiffXY + fprintf(HeadFmt, 'diffxy:'); + for Len = LenList + x = rand(1, Len); + t = unevenT(1:Len); + + nLoop = GetNLoop(@diffxy, {x, t}); + tic; + for i = 1:nLoop + dx = diffxy(x, t); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + end + + fprintf(HeadFmt, 'DGradient:'); + for Len = LenList + x = rand(1, Len); + t = unevenT(1:Len); + + nLoop = GetNLoop(@DGradient, {x, t, 2, '2ndOrder'}); + tic; + for i = 1:nLoop + dx = DGradient(x, t, 2, '2ndOrder'); + dx(1) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + + % Matrices: ----------------------------------------------------------------- + fprintf('[10 x N]:\n'); + fprintf('Unevenly spaced, 1st order:\n'); + fprintf(HeadFmt, 'GRADIENT:'); + for Len = LenList + x = rand(10, Len); + t1 = unevenT(1:10); + t2 = unevenT(1:Len); + + nLoop = GetNLoop(@gradient, {x, t2, t1}); + tic; + for i = 1:nLoop + [dx2, dx1] = gradient(x, t2, t1); + dx(1) = rand; + dx(2) = rand; % More realistic timings + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); + + fprintf(HeadFmt, 'DGradient:'); + for Len = LenList + x = rand(10, Len); + t1 = unevenT(1:10); + t2 = unevenT(1:Len); + + nLoop = GetNLoop(@DGradient, {x, t2, 2}); + tic; + for i = 1:nLoop + dx1 = DGradient(x, t1, 1); + dx2 = DGradient(x, t2, 2); + dx1(1) = rand; % More realistic timings + dx2(1) = rand; + end + M_time = toc; + fprintf('%8d', round(nLoop / M_time)); + drawnow; + end + fprintf(' loops/sec\n'); +end + +% Ready - successful if this is reached: +fprintf('\n== DGradient passed the tests.\n'); + +return; + +% ****************************************************************************** +function nLoops = GetNLoop(Fcn, Arg) +% Get number of iterations for valid speed measurement: + +iLoop = 0; +startTime = cputime; +while cputime - startTime < 0.5 + E = feval(Fcn, Arg{:}); %#ok<*NASGU> + clear('E'); + iLoop = iLoop + 1; +end +nPerSec = ceil(0.1 * iLoop / (cputime - startTime)); + +% Round loop numbers: +% nDigits = max(1, floor(log10(max(1, nPerSec))) - 1); +% nLoops = max(4, round(nPerSec / 10 ^ nDigits) * 10 ^ nDigits); +nLoops = max(4, nPerSec); + +return; diff --git a/TBM/GP/GPExpand.m b/TBM/GP/GPExpand.m new file mode 100644 index 0000000..f982292 --- /dev/null +++ b/TBM/GP/GPExpand.m @@ -0,0 +1,74 @@ +function IResult = GPExpand(I,newdim) %#codegen + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Expand an image as per the Gaussian Pyramid. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Wt = [0.0500 0.2500 0.4000 0.2500 0.0500]; + +dim = size(I); +% newdim = zeros(1,3); +% newdim(1) = dim(1); newdim(2) = dim(2); newdim(3) = dim(3); +% for i = 1:numel(dim) +% if mod(dim(i),2)==0 +% newdim(i) = dim(i)*2; +% else +% newdim(i) = dim(i)*2-1; +% end +% end + +IResult = zeros(newdim,class(I)); % Initialize the array in the beginning .. +m = [-2:2];n=m; + +switch length(dim) + case 1 + %% Pad the boundaries. + I = [ I(1) ; I ; I(dim(1))]; + for i = 0 : newdim(1) - 1 + pixeli = (i - m)/2 + 2; idxi = find(floor(pixeli)==pixeli); + A = I(pixeli(idxi)) .* Wt(m(idxi)+3); + IResult(i + 1)= 2 * sum(A(:)); + end + case 2 + %% Pad the boundaries. + I = [ I(1,:) ; I ; I(dim(1),:) ]; % Pad the top and bottom rows. + I = [ I(:,1) I I(:,dim(2)) ]; % Pad the left and right columns. + Wt2 = Wt'*Wt; + + for i = 0 : newdim(1) - 1 + for j = 0 : newdim(2) - 1 + pixeli = (i - m)/2 + 2; idxi = find(floor(pixeli)==pixeli); + pixelj = (j - m)/2 + 2; idxj = find(floor(pixelj)==pixelj); + A = I(pixeli(idxi),pixelj(idxj)) .* Wt2(m(idxi)+3,m(idxj)+3); + IResult(i + 1, j + 1)= 4 * sum(A(:)); + end + end + case 3 + Wt3 = ones(5,5,5); + for i = 1:5 + Wt3(i,:,:) = Wt3(i,:,:) * Wt(i); + Wt3(:,i,:) = Wt3(:,i,:) * Wt(i); + Wt3(:,:,i) = Wt3(:,:,i) * Wt(i); + end + + %% Pad the boundaries + I2 = zeros(dim+2,class(I)); + I2(2:1+dim(1),2:1+dim(2),2:1+dim(3)) = I; + I2(1,:,:)=I2(2,:,:);I2(end,:,:)=I2(end-1,:,:); + I2(:,1,:)=I2(:,2,:);I2(:,end,:)=I2(:,end-1,:); + I2(:,:,1)=I2(:,:,2);I2(:,:,end)=I2(:,:,end-1); + I=I2; %clear I2; + + for i = 0 : newdim(1) - 1 + for j = 0 : newdim(2) - 1 + for k = 0 : newdim(3) - 1 + pixeli = (i - m)/2 + 2; idxi = find(floor(pixeli)==pixeli); + pixelj = (j - m)/2 + 2; idxj = find(floor(pixelj)==pixelj); + pixelk = (k - m)/2 + 2; idxk = find(floor(pixelk)==pixelk); + A = I(pixeli(idxi),pixelj(idxj),pixelk(idxk)) .* Wt3(m(idxi)+3,m(idxj)+3,m(idxk)+3); + IResult(i + 1, j + 1,k+1)= 8 * sum(A(:)); + end + end + end +end + diff --git a/TBM/GP/GPExpand.mexmaci64 b/TBM/GP/GPExpand.mexmaci64 new file mode 100644 index 0000000..ef52aed Binary files /dev/null and b/TBM/GP/GPExpand.mexmaci64 differ diff --git a/TBM/GP/GPReduce.m b/TBM/GP/GPReduce.m new file mode 100644 index 0000000..51f6380 --- /dev/null +++ b/TBM/GP/GPReduce.m @@ -0,0 +1,60 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Reduce an image applying Gaussian Pyramid. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +function IResult = GPReduce(I) %#codegen + +Wt = [0.0500 0.2500 0.4000 0.2500 0.0500]; + +dim = size(I); +newdim = ceil(dim*0.5); +IResult = zeros(newdim,class(I)); % Initialize the array in the beginning .. +m = [-2:2];n=m; + +switch length(dim) + case 1 + %% Pad the boundaries. + I = [ I(1) ; I(1) ; I ; I(dim(1)); I(dim(1)) ]; % Add two rows towards the beginning and the end. + for i = 0 : newdim(1) -1 + A = I(2*i+m+3).*Wt; + IResult(i + 1)= sum(A(:)); + end + case 2 + %% Pad the boundaries. + I = [ I(1,:) ; I(1,:) ; I ; I(dim(1),:); I(dim(1),:) ]; % Add two rows towards the beginning and the end. + I = [ I(:,1) I(:,1) I I(:,dim(2)) I(:,dim(2)) ]; % Add two columns towards the beginning and the end. + + Wt2 = Wt'*Wt; + + for i = 0 : newdim(1) -1 + for j = 0 : newdim(2) -1 + A = I(2*i+m+3,2*j+m+3).*Wt2; + IResult(i + 1, j + 1) = sum(A(:)); + end + end + + case 3 + Wt3 = ones(5,5,5); + for i = 1:5 + Wt3(i,:,:) = Wt3(i,:,:) * Wt(i); + Wt3(:,i,:) = Wt3(:,i,:) * Wt(i); + Wt3(:,:,i) = Wt3(:,:,i) * Wt(i); + end + + %% Pad the boundaries. + I2 = zeros(dim+4,class(I)); + I2(3:2+dim(1),3:2+dim(2),3:2+dim(3)) = I; + I2(1,:,:)=I2(3,:,:);I2(1,:,:)=I2(3,:,:);I2(end,:,:)=I2(end-2,:,:);I2(end-1,:,:)=I2(end-2,:,:); + I2(:,1,:)=I2(:,3,:);I2(:,2,:)=I2(:,3,:);I2(:,end,:)=I2(:,end-2,:);I2(:,end-1,:)=I2(:,end-2,:); + I2(:,:,1)=I2(:,:,3);I2(:,:,2)=I2(:,:,3);I2(:,:,end)=I2(:,:,end-2);I2(:,:,end-1)=I2(:,:,end-2); + I=I2; %clear I2; + + for i = 0 : newdim(1) -1 + for j = 0 : newdim(2) -1 + for k = 0 : newdim(3) - 1 + A = I(2*i+m+3,2*j+m+3,2*k+m+3).*Wt3; + IResult(i+1,j+1,k+1) = sum(A(:)); + end + end + end +end + diff --git a/TBM/GP/GPReduce.mexmaci64 b/TBM/GP/GPReduce.mexmaci64 new file mode 100644 index 0000000..e2b51a2 Binary files /dev/null and b/TBM/GP/GPReduce.mexmaci64 differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand.c b/TBM/GP/codegen/mex/GPExpand/GPExpand.c new file mode 100644 index 0000000..c5fbfbb --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand.c @@ -0,0 +1,967 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand.c + * + * Code generation for function 'GPExpand' + * + */ + +/* Include files */ +#include "GPExpand.h" +#include "GPExpand_data.h" +#include "GPExpand_emxutil.h" +#include "GPExpand_types.h" +#include "find.h" +#include "rt_nonfinite.h" +#include "sumMatrixIncludeNaN.h" +#include "mwmathutil.h" +#include + +/* Variable Definitions */ +static emlrtBCInfo emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 56, /* lineNo */ + 8, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo b_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 56, /* lineNo */ + 19, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo c_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 56, /* lineNo */ + 30, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo emlrtECI = { + -1, /* nDims */ + 56, /* lineNo */ + 3, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtECInfo b_emlrtECI = { + -1, /* nDims */ + 57, /* lineNo */ + 3, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtBCInfo d_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 57, /* lineNo */ + 38, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo e_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 57, /* lineNo */ + 26, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo c_emlrtECI = { + -1, /* nDims */ + 57, /* lineNo */ + 23, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtECInfo d_emlrtECI = { + -1, /* nDims */ + 58, /* lineNo */ + 3, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtBCInfo f_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 58, /* lineNo */ + 40, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo g_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 58, /* lineNo */ + 28, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo e_emlrtECI = { + -1, /* nDims */ + 58, /* lineNo */ + 23, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtECInfo f_emlrtECI = { + -1, /* nDims */ + 59, /* lineNo */ + 3, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtBCInfo h_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 59, /* lineNo */ + 42, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo i_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 59, /* lineNo */ + 30, /* colNo */ + "I2", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo g_emlrtECI = { + -1, /* nDims */ + 59, /* lineNo */ + 23, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo emlrtRTEI = { + 62, /* lineNo */ + 11, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo b_emlrtRTEI = { + 63, /* lineNo */ + 12, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo c_emlrtRTEI = { + 64, /* lineNo */ + 13, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtBCInfo j_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 68, /* lineNo */ + 12, /* colNo */ + "I", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtDCInfo emlrtDCI = { + 68, /* lineNo */ + 12, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 1 /* checkKind */ +}; + +static emlrtBCInfo k_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 68, /* lineNo */ + 25, /* colNo */ + "I", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtDCInfo b_emlrtDCI = { + 68, /* lineNo */ + 25, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 1 /* checkKind */ +}; + +static emlrtBCInfo l_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 68, /* lineNo */ + 38, /* colNo */ + "I", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtDCInfo c_emlrtDCI = { + 68, /* lineNo */ + 38, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 1 /* checkKind */ +}; + +static emlrtBCInfo m_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 69, /* lineNo */ + 14, /* colNo */ + "IResult", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo n_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 69, /* lineNo */ + 21, /* colNo */ + "IResult", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo o_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 69, /* lineNo */ + 27, /* colNo */ + "IResult", /* aName */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtDCInfo d_emlrtDCI = { + 55, /* lineNo */ + 14, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 1 /* checkKind */ +}; + +static emlrtDCInfo e_emlrtDCI = { + 20, /* lineNo */ + 17, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 1 /* checkKind */ +}; + +static emlrtDCInfo f_emlrtDCI = { + 20, /* lineNo */ + 17, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m", /* pName */ + 4 /* checkKind */ +}; + +static emlrtRTEInfo e_emlrtRTEI = { + 20, /* lineNo */ + 1, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo f_emlrtRTEI = { + 55, /* lineNo */ + 3, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo g_emlrtRTEI = { + 57, /* lineNo */ + 13, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo h_emlrtRTEI = { + 57, /* lineNo */ + 35, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo i_emlrtRTEI = { + 58, /* lineNo */ + 13, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo j_emlrtRTEI = { + 58, /* lineNo */ + 35, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo k_emlrtRTEI = { + 59, /* lineNo */ + 13, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +static emlrtRTEInfo l_emlrtRTEI = { + 59, /* lineNo */ + 35, /* colNo */ + "GPExpand", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m" /* pName */ +}; + +/* Function Definitions */ +void GPExpand(const emlrtStack *sp, const emxArray_real_T *b_I, + const real_T newdim[3], emxArray_real_T *IResult) +{ + static const real_T dv[5] = {0.05, 0.25, 0.4, 0.25, 0.05}; + emxArray_real_T *I2; + emxArray_real_T *d_I2; + emxArray_real_T *e_I2; + emxArray_real_T *f_I2; + real_T Wt3[125]; + const real_T *I_data; + real_T b; + real_T *I2_data; + real_T *IResult_data; + real_T *b_I2_data; + int32_T idxi_data[5]; + int32_T idxj_data[5]; + int32_T idxk_data[5]; + int32_T A_size[3]; + int32_T c_I2[3]; + int32_T g_I2[2]; + int32_T idxi_size[2]; + int32_T idxj_size[2]; + int32_T iv[2]; + int32_T Wt3_tmp; + int32_T b_I2; + int32_T b_i; + int32_T b_loop_ub; + int32_T i; + int32_T i1; + int32_T i2; + int32_T i3; + int32_T i4; + int32_T i5; + int32_T i6; + int32_T j; + int32_T k; + int32_T loop_ub; + I_data = b_I->data; + emlrtHeapReferenceStackEnterFcnR2012b((emlrtCTX)sp); + /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Expand an image as per the Gaussian Pyramid. */ + /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* newdim = zeros(1,3); */ + /* newdim(1) = dim(1); newdim(2) = dim(2); newdim(3) = dim(3); */ + /* for i = 1:numel(dim) */ + /* if mod(dim(i),2)==0 */ + /* newdim(i) = dim(i)*2; */ + /* else */ + /* newdim(i) = dim(i)*2-1; */ + /* end */ + /* end */ + if (!(newdim[0] >= 0.0)) { + emlrtNonNegativeCheckR2012b(newdim[0], &f_emlrtDCI, (emlrtCTX)sp); + } + if (newdim[0] != (int32_T)muDoubleScalarFloor(newdim[0])) { + emlrtIntegerCheckR2012b(newdim[0], &e_emlrtDCI, (emlrtCTX)sp); + } + if (!(newdim[1] >= 0.0)) { + emlrtNonNegativeCheckR2012b(newdim[1], &f_emlrtDCI, (emlrtCTX)sp); + } + if (newdim[1] != (int32_T)muDoubleScalarFloor(newdim[1])) { + emlrtIntegerCheckR2012b(newdim[1], &e_emlrtDCI, (emlrtCTX)sp); + } + if (!(newdim[2] >= 0.0)) { + emlrtNonNegativeCheckR2012b(newdim[2], &f_emlrtDCI, (emlrtCTX)sp); + } + if (newdim[2] != (int32_T)muDoubleScalarFloor(newdim[2])) { + emlrtIntegerCheckR2012b(newdim[2], &e_emlrtDCI, (emlrtCTX)sp); + } + i = IResult->size[0] * IResult->size[1] * IResult->size[2]; + IResult->size[0] = (int32_T)newdim[0]; + IResult->size[1] = (int32_T)newdim[1]; + IResult->size[2] = (int32_T)newdim[2]; + emxEnsureCapacity_real_T(sp, IResult, i, &e_emlrtRTEI); + IResult_data = IResult->data; + loop_ub = (int32_T)newdim[0] * (int32_T)newdim[1] * (int32_T)newdim[2]; + for (i = 0; i < loop_ub; i++) { + IResult_data[i] = 0.0; + } + /* Initialize the array in the beginning .. */ + for (i = 0; i < 125; i++) { + Wt3[i] = 1.0; + } + for (b_i = 0; b_i < 5; b_i++) { + b = dv[b_i]; + for (i = 0; i < 5; i++) { + for (i1 = 0; i1 < 5; i1++) { + Wt3_tmp = (b_i + 5 * i1) + 25 * i; + Wt3[Wt3_tmp] *= b; + } + for (i1 = 0; i1 < 5; i1++) { + Wt3_tmp = (i1 + 5 * b_i) + 25 * i; + Wt3[Wt3_tmp] *= b; + } + } + for (i = 0; i < 5; i++) { + for (i1 = 0; i1 < 5; i1++) { + Wt3_tmp = (i1 + 5 * i) + 25 * b_i; + Wt3[Wt3_tmp] *= b; + } + } + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + /* %% Pad the boundaries */ + if ((real_T)b_I->size[0] + 2.0 != b_I->size[0] + 2) { + emlrtIntegerCheckR2012b((real_T)b_I->size[0] + 2.0, &d_emlrtDCI, + (emlrtCTX)sp); + } + if ((real_T)b_I->size[1] + 2.0 != b_I->size[1] + 2) { + emlrtIntegerCheckR2012b((real_T)b_I->size[1] + 2.0, &d_emlrtDCI, + (emlrtCTX)sp); + } + if ((real_T)b_I->size[2] + 2.0 != b_I->size[2] + 2) { + emlrtIntegerCheckR2012b((real_T)b_I->size[2] + 2.0, &d_emlrtDCI, + (emlrtCTX)sp); + } + emxInit_real_T(sp, &I2, 3, &f_emlrtRTEI); + i = I2->size[0] * I2->size[1] * I2->size[2]; + I2->size[0] = (int32_T)(uint32_T)((real_T)b_I->size[0] + 2.0); + I2->size[1] = (int32_T)(uint32_T)((real_T)b_I->size[1] + 2.0); + I2->size[2] = (int32_T)(uint32_T)((real_T)b_I->size[2] + 2.0); + emxEnsureCapacity_real_T(sp, I2, i, &f_emlrtRTEI); + I2_data = I2->data; + loop_ub = (int32_T)(uint32_T)((real_T)b_I->size[0] + 2.0) * + (int32_T)(uint32_T)((real_T)b_I->size[1] + 2.0) * + (int32_T)(uint32_T)((real_T)b_I->size[2] + 2.0); + for (i = 0; i < loop_ub; i++) { + I2_data[i] = 0.0; + } + if (b_I->size[0] + 1U < 2U) { + i = 0; + i1 = 0; + } else { + i = 1; + if (((int32_T)(b_I->size[0] + 1U) < 1) || + ((int32_T)(b_I->size[0] + 1U) > + (int32_T)(uint32_T)((real_T)b_I->size[0] + 2.0))) { + emlrtDynamicBoundsCheckR2012b( + (int32_T)(b_I->size[0] + 1U), 1, + (int32_T)(uint32_T)((real_T)b_I->size[0] + 2.0), &emlrtBCI, + (emlrtCTX)sp); + } + i1 = (int32_T)(b_I->size[0] + 1U); + } + if (b_I->size[1] + 1U < 2U) { + b_I2 = 0; + i2 = 0; + } else { + b_I2 = 1; + if (((int32_T)(b_I->size[1] + 1U) < 1) || + ((int32_T)(b_I->size[1] + 1U) > + (int32_T)(uint32_T)((real_T)b_I->size[1] + 2.0))) { + emlrtDynamicBoundsCheckR2012b( + (int32_T)(b_I->size[1] + 1U), 1, + (int32_T)(uint32_T)((real_T)b_I->size[1] + 2.0), &b_emlrtBCI, + (emlrtCTX)sp); + } + i2 = (int32_T)(b_I->size[1] + 1U); + } + if (b_I->size[2] + 1U < 2U) { + i3 = 0; + i4 = 0; + } else { + i3 = 1; + if (((int32_T)(b_I->size[2] + 1U) < 1) || + ((int32_T)(b_I->size[2] + 1U) > + (int32_T)(uint32_T)((real_T)b_I->size[2] + 2.0))) { + emlrtDynamicBoundsCheckR2012b( + (int32_T)(b_I->size[2] + 1U), 1, + (int32_T)(uint32_T)((real_T)b_I->size[2] + 2.0), &c_emlrtBCI, + (emlrtCTX)sp); + } + i4 = (int32_T)(b_I->size[2] + 1U); + } + c_I2[0] = i1 - i; + c_I2[1] = i2 - b_I2; + c_I2[2] = i4 - i3; + emlrtSubAssignSizeCheckR2012b(&c_I2[0], 3, &b_I->size[0], 3, &emlrtECI, + (emlrtCTX)sp); + loop_ub = b_I->size[2]; + for (i1 = 0; i1 < loop_ub; i1++) { + b_loop_ub = b_I->size[1]; + for (i2 = 0; i2 < b_loop_ub; i2++) { + Wt3_tmp = b_I->size[0]; + for (i4 = 0; i4 < Wt3_tmp; i4++) { + I2_data[((i + i4) + I2->size[0] * (b_I2 + i2)) + + I2->size[0] * I2->size[1] * (i3 + i1)] = + I_data[(i4 + b_I->size[0] * i2) + b_I->size[0] * b_I->size[1] * i1]; + } + } + } + emxInit_real_T(sp, &d_I2, 3, &g_emlrtRTEI); + loop_ub = I2->size[1]; + b_loop_ub = I2->size[2]; + i = d_I2->size[0] * d_I2->size[1] * d_I2->size[2]; + d_I2->size[0] = 1; + d_I2->size[1] = I2->size[1]; + d_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, d_I2, i, &g_emlrtRTEI); + b_I2_data = d_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + d_I2->size[1] * i] = + I2_data[(I2->size[0] * i1 + I2->size[0] * I2->size[1] * i) + 1]; + } + } + c_I2[0] = 1; + c_I2[1] = I2->size[1]; + c_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&c_I2[0], 3, &d_I2->size[0], 3, &b_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[1] - 1; + loop_ub = I2->size[2] - 1; + i = d_I2->size[0] * d_I2->size[1] * d_I2->size[2]; + d_I2->size[0] = 1; + d_I2->size[1] = I2->size[1]; + d_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, d_I2, i, &g_emlrtRTEI); + b_I2_data = d_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + d_I2->size[1] * i] = + I2_data[(I2->size[0] * i1 + I2->size[0] * I2->size[1] * i) + 1]; + } + } + loop_ub = d_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = d_I2->size[1]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[I2->size[0] * i1 + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + d_I2->size[1] * i]; + } + } + if (I2->size[0] < 1) { + emlrtDynamicBoundsCheckR2012b(I2->size[0], 1, I2->size[0], &e_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[0] - 1 < 1) || (I2->size[0] - 1 > I2->size[0])) { + emlrtDynamicBoundsCheckR2012b(I2->size[0] - 1, 1, I2->size[0], &d_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = I2->size[1]; + b_loop_ub = I2->size[2]; + i = d_I2->size[0] * d_I2->size[1] * d_I2->size[2]; + d_I2->size[0] = 1; + d_I2->size[1] = I2->size[1]; + d_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, d_I2, i, &h_emlrtRTEI); + b_I2_data = d_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + d_I2->size[1] * i] = + I2_data[((I2->size[0] + I2->size[0] * i1) + + I2->size[0] * I2->size[1] * i) - + 2]; + } + } + c_I2[0] = 1; + c_I2[1] = I2->size[1]; + c_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&c_I2[0], 3, &d_I2->size[0], 3, &c_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[1] - 1; + loop_ub = I2->size[2] - 1; + b_I2 = I2->size[0] - 1; + i = d_I2->size[0] * d_I2->size[1] * d_I2->size[2]; + d_I2->size[0] = 1; + d_I2->size[1] = I2->size[1]; + d_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, d_I2, i, &h_emlrtRTEI); + b_I2_data = d_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + d_I2->size[1] * i] = + I2_data[((I2->size[0] + I2->size[0] * i1) + + I2->size[0] * I2->size[1] * i) - + 2]; + } + } + loop_ub = d_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = d_I2->size[1]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(b_I2 + I2->size[0] * i1) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + d_I2->size[1] * i]; + } + } + emxFree_real_T(sp, &d_I2); + emxInit_real_T(sp, &e_I2, 3, &i_emlrtRTEI); + loop_ub = I2->size[0]; + b_loop_ub = I2->size[2]; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &i_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0]) + I2->size[0] * I2->size[1] * i]; + } + } + c_I2[0] = I2->size[0]; + c_I2[1] = 1; + c_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&c_I2[0], 3, &e_I2->size[0], 3, &d_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[2] - 1; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &i_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0]) + I2->size[0] * I2->size[1] * i]; + } + } + loop_ub = e_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = e_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[i1 + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + e_I2->size[0] * i]; + } + } + if (I2->size[1] < 1) { + emlrtDynamicBoundsCheckR2012b(I2->size[1], 1, I2->size[1], &g_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[1] - 1 < 1) || (I2->size[1] - 1 > I2->size[1])) { + emlrtDynamicBoundsCheckR2012b(I2->size[1] - 1, 1, I2->size[1], &f_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = I2->size[0]; + b_loop_ub = I2->size[2]; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &j_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * (I2->size[1] - 2)) + + I2->size[0] * I2->size[1] * i]; + } + } + c_I2[0] = I2->size[0]; + c_I2[1] = 1; + c_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&c_I2[0], 3, &e_I2->size[0], 3, &e_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[2] - 1; + b_I2 = I2->size[1] - 1; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &j_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * (I2->size[1] - 2)) + + I2->size[0] * I2->size[1] * i]; + } + } + loop_ub = e_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = e_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * b_I2) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + e_I2->size[0] * i]; + } + } + emxFree_real_T(sp, &e_I2); + emxInit_real_T(sp, &f_I2, 2, &k_emlrtRTEI); + g_I2[0] = I2->size[0]; + g_I2[1] = I2->size[1]; + iv[0] = I2->size[0]; + iv[1] = I2->size[1]; + emlrtSubAssignSizeCheckR2012b(&g_I2[0], 2, &iv[0], 2, &f_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[1] - 1; + i = f_I2->size[0] * f_I2->size[1]; + f_I2->size[0] = I2->size[0]; + f_I2->size[1] = I2->size[1]; + emxEnsureCapacity_real_T(sp, f_I2, i, &k_emlrtRTEI); + b_I2_data = f_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + f_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1]]; + } + } + loop_ub = f_I2->size[1]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = f_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[i1 + I2->size[0] * i] = b_I2_data[i1 + f_I2->size[0] * i]; + } + } + if (I2->size[2] < 1) { + emlrtDynamicBoundsCheckR2012b(I2->size[2], 1, I2->size[2], &i_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[2] - 1 < 1) || (I2->size[2] - 1 > I2->size[2])) { + emlrtDynamicBoundsCheckR2012b(I2->size[2] - 1, 1, I2->size[2], &h_emlrtBCI, + (emlrtCTX)sp); + } + g_I2[0] = I2->size[0]; + g_I2[1] = I2->size[1]; + iv[0] = I2->size[0]; + iv[1] = I2->size[1]; + emlrtSubAssignSizeCheckR2012b(&g_I2[0], 2, &iv[0], 2, &g_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[1] - 1; + b_I2 = I2->size[2] - 1; + i = f_I2->size[0] * f_I2->size[1]; + f_I2->size[0] = I2->size[0]; + f_I2->size[1] = I2->size[1]; + emxEnsureCapacity_real_T(sp, f_I2, i, &l_emlrtRTEI); + b_I2_data = f_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + f_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * i) + + I2->size[0] * I2->size[1] * (I2->size[2] - 2)]; + } + } + loop_ub = f_I2->size[1]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = f_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1] * b_I2] = + b_I2_data[i1 + f_I2->size[0] * i]; + } + } + emxFree_real_T(sp, &f_I2); + /* clear I2; */ + i = (int32_T)((newdim[0] - 1.0) + 1.0); + emlrtForLoopVectorCheckR2021a(0.0, 1.0, newdim[0] - 1.0, mxDOUBLE_CLASS, + (int32_T)((newdim[0] - 1.0) + 1.0), &emlrtRTEI, + (emlrtCTX)sp); + if (i - 1 >= 0) { + i5 = (int32_T)((newdim[1] - 1.0) + 1.0); + if (i5 - 1 >= 0) { + i6 = (int32_T)((newdim[2] - 1.0) + 1.0); + } + } + for (b_i = 0; b_i < i; b_i++) { + emlrtForLoopVectorCheckR2021a(0.0, 1.0, newdim[1] - 1.0, mxDOUBLE_CLASS, + (int32_T)((newdim[1] - 1.0) + 1.0), + &b_emlrtRTEI, (emlrtCTX)sp); + for (j = 0; j < i5; j++) { + emlrtForLoopVectorCheckR2021a(0.0, 1.0, newdim[2] - 1.0, mxDOUBLE_CLASS, + (int32_T)((newdim[2] - 1.0) + 1.0), + &c_emlrtRTEI, (emlrtCTX)sp); + for (k = 0; k < i6; k++) { + real_T A_data[125]; + real_T tmp_data[125]; + real_T pixeli[5]; + real_T pixelj[5]; + real_T pixelk[5]; + boolean_T x[5]; + for (Wt3_tmp = 0; Wt3_tmp < 5; Wt3_tmp++) { + b = ((real_T)b_i - ((real_T)Wt3_tmp + -2.0)) / 2.0 + 2.0; + pixeli[Wt3_tmp] = b; + x[Wt3_tmp] = (muDoubleScalarFloor(b) == b); + } + eml_find(x, idxk_data, g_I2); + loop_ub = g_I2[1]; + idxi_size[1] = g_I2[1]; + if (loop_ub - 1 >= 0) { + memcpy(&idxi_data[0], &idxk_data[0], loop_ub * sizeof(int32_T)); + } + for (Wt3_tmp = 0; Wt3_tmp < 5; Wt3_tmp++) { + b = ((real_T)j - ((real_T)Wt3_tmp + -2.0)) / 2.0 + 2.0; + pixelj[Wt3_tmp] = b; + x[Wt3_tmp] = (muDoubleScalarFloor(b) == b); + } + eml_find(x, idxk_data, g_I2); + b_loop_ub = g_I2[1]; + idxj_size[1] = g_I2[1]; + if (b_loop_ub - 1 >= 0) { + memcpy(&idxj_data[0], &idxk_data[0], b_loop_ub * sizeof(int32_T)); + } + for (Wt3_tmp = 0; Wt3_tmp < 5; Wt3_tmp++) { + b = ((real_T)k - ((real_T)Wt3_tmp + -2.0)) / 2.0 + 2.0; + pixelk[Wt3_tmp] = b; + x[Wt3_tmp] = (muDoubleScalarFloor(b) == b); + } + eml_find(x, idxk_data, g_I2); + Wt3_tmp = g_I2[1]; + for (i1 = 0; i1 < Wt3_tmp; i1++) { + for (b_I2 = 0; b_I2 < b_loop_ub; b_I2++) { + for (i2 = 0; i2 < loop_ub; i2++) { + real_T d; + real_T d1; + b = pixeli[idxi_data[i2] - 1]; + if (b != muDoubleScalarFloor(b)) { + emlrtIntegerCheckR2012b(b, &emlrtDCI, (emlrtCTX)sp); + } + if ((int32_T)b > I2->size[0]) { + emlrtDynamicBoundsCheckR2012b((int32_T)b, 1, I2->size[0], + &j_emlrtBCI, (emlrtCTX)sp); + } + d = pixelj[idxj_data[b_I2] - 1]; + if (d != muDoubleScalarFloor(d)) { + emlrtIntegerCheckR2012b(d, &b_emlrtDCI, (emlrtCTX)sp); + } + if ((int32_T)d > I2->size[1]) { + emlrtDynamicBoundsCheckR2012b((int32_T)d, 1, I2->size[1], + &k_emlrtBCI, (emlrtCTX)sp); + } + d1 = pixelk[idxk_data[i1] - 1]; + if (d1 != muDoubleScalarFloor(d1)) { + emlrtIntegerCheckR2012b(d1, &c_emlrtDCI, (emlrtCTX)sp); + } + if ((int32_T)d1 > I2->size[2]) { + emlrtDynamicBoundsCheckR2012b((int32_T)d1, 1, I2->size[2], + &l_emlrtBCI, (emlrtCTX)sp); + } + tmp_data[(i2 + loop_ub * b_I2) + loop_ub * b_loop_ub * i1] = + I2_data[(((int32_T)b + I2->size[0] * ((int32_T)d - 1)) + + I2->size[0] * I2->size[1] * ((int32_T)d1 - 1)) - + 1]; + } + } + } + i1 = idxi_size[1]; + b_I2 = idxj_size[1]; + Wt3_tmp = g_I2[1]; + A_size[0] = loop_ub; + A_size[1] = b_loop_ub; + A_size[2] = g_I2[1]; + for (i2 = 0; i2 < Wt3_tmp; i2++) { + for (i3 = 0; i3 < b_loop_ub; i3++) { + for (i4 = 0; i4 < loop_ub; i4++) { + A_data[(i4 + i1 * i3) + i1 * b_I2 * i2] = + tmp_data[(i4 + loop_ub * i3) + loop_ub * b_loop_ub * i2] * + Wt3[((idxi_data[i4] + 5 * (idxj_data[i3] - 1)) + + 25 * (idxk_data[i2] - 1)) - + 1]; + } + } + } + i1 = A_size[0] * A_size[1] * A_size[2]; + if (i1 == 0) { + b = 0.0; + } else { + b = sumColumnB(A_data, i1); + } + if (((int32_T)(b_i + 1U) < 1) || + ((int32_T)(b_i + 1U) > IResult->size[0])) { + emlrtDynamicBoundsCheckR2012b((int32_T)(b_i + 1U), 1, + IResult->size[0], &m_emlrtBCI, + (emlrtCTX)sp); + } + if (((int32_T)(j + 1U) < 1) || ((int32_T)(j + 1U) > IResult->size[1])) { + emlrtDynamicBoundsCheckR2012b((int32_T)(j + 1U), 1, IResult->size[1], + &n_emlrtBCI, (emlrtCTX)sp); + } + if (((int32_T)(k + 1U) < 1) || ((int32_T)(k + 1U) > IResult->size[2])) { + emlrtDynamicBoundsCheckR2012b((int32_T)(k + 1U), 1, IResult->size[2], + &o_emlrtBCI, (emlrtCTX)sp); + } + IResult_data[(b_i + IResult->size[0] * j) + + IResult->size[0] * IResult->size[1] * k] = 8.0 * b; + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + emxFree_real_T(sp, &I2); + emlrtHeapReferenceStackLeaveFcnR2012b((emlrtCTX)sp); +} + +/* End of code generation (GPExpand.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand.h b/TBM/GP/codegen/mex/GPExpand/GPExpand.h new file mode 100644 index 0000000..b0e280b --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand.h @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand.h + * + * Code generation for function 'GPExpand' + * + */ + +#pragma once + +/* Include files */ +#include "GPExpand_types.h" +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPExpand(const emlrtStack *sp, const emxArray_real_T *b_I, + const real_T newdim[3], emxArray_real_T *IResult); + +/* End of code generation (GPExpand.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand.map b/TBM/GP/codegen/mex/GPExpand/GPExpand.map new file mode 100644 index 0000000..22b27f1 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand.map @@ -0,0 +1,10 @@ +_mexFunction +_mexfilerequiredapiversion +_emlrtMexFcnProperties +_GPExpand +_GPExpand_initialize +_GPExpand_terminate +_GPExpand_atexit +_emxFree_real_T +_emxInit_real_T +_emxEnsureCapacity_real_T diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand.mexmaci64 b/TBM/GP/codegen/mex/GPExpand/GPExpand.mexmaci64 new file mode 100644 index 0000000..ef52aed Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand.mexmaci64 differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand.obj b/TBM/GP/codegen/mex/GPExpand/GPExpand.obj new file mode 100644 index 0000000..53562b7 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_data.c b/TBM/GP/codegen/mex/GPExpand/GPExpand_data.c new file mode 100644 index 0000000..35c2351 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_data.c @@ -0,0 +1,33 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_data.c + * + * Code generation for function 'GPExpand_data' + * + */ + +/* Include files */ +#include "GPExpand_data.h" +#include "rt_nonfinite.h" + +/* Variable Definitions */ +emlrtCTX emlrtRootTLSGlobal = NULL; + +const volatile char_T *emlrtBreakCheckR2012bFlagVar = NULL; + +emlrtContext emlrtContextGlobal = { + true, /* bFirstTime */ + false, /* bInitialized */ + 131626U, /* fVersionInfo */ + NULL, /* fErrorFunction */ + "GPExpand", /* fFunctionName */ + NULL, /* fRTCallStack */ + false, /* bDebugMode */ + {2045744189U, 2170104910U, 2743257031U, 4284093946U}, /* fSigWrd */ + NULL /* fSigMem */ +}; + +/* End of code generation (GPExpand_data.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_data.h b/TBM/GP/codegen/mex/GPExpand/GPExpand_data.h new file mode 100644 index 0000000..96510a5 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_data.h @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_data.h + * + * Code generation for function 'GPExpand_data' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Variable Declarations */ +extern emlrtCTX emlrtRootTLSGlobal; +extern const volatile char_T *emlrtBreakCheckR2012bFlagVar; +extern emlrtContext emlrtContextGlobal; + +/* End of code generation (GPExpand_data.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_data.obj b/TBM/GP/codegen/mex/GPExpand/GPExpand_data.obj new file mode 100644 index 0000000..7e03f11 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_data.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.c b/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.c new file mode 100644 index 0000000..dbba6e0 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.c @@ -0,0 +1,101 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_emxutil.c + * + * Code generation for function 'GPExpand_emxutil' + * + */ + +/* Include files */ +#include "GPExpand_emxutil.h" +#include "GPExpand_types.h" +#include "rt_nonfinite.h" +#include + +/* Function Definitions */ +void emxEnsureCapacity_real_T(const emlrtStack *sp, emxArray_real_T *emxArray, + int32_T oldNumel, const emlrtRTEInfo *srcLocation) +{ + int32_T i; + int32_T newNumel; + void *newData; + if (oldNumel < 0) { + oldNumel = 0; + } + newNumel = 1; + for (i = 0; i < emxArray->numDimensions; i++) { + newNumel = (int32_T)emlrtSizeMulR2012b((size_t)(uint32_T)newNumel, + (size_t)(uint32_T)emxArray->size[i], + srcLocation, (emlrtCTX)sp); + } + if (newNumel > emxArray->allocatedSize) { + i = emxArray->allocatedSize; + if (i < 16) { + i = 16; + } + while (i < newNumel) { + if (i > 1073741823) { + i = MAX_int32_T; + } else { + i *= 2; + } + } + newData = emlrtCallocMex((uint32_T)i, sizeof(real_T)); + if (newData == NULL) { + emlrtHeapAllocationErrorR2012b(srcLocation, (emlrtCTX)sp); + } + if (emxArray->data != NULL) { + memcpy(newData, emxArray->data, sizeof(real_T) * oldNumel); + if (emxArray->canFreeData) { + emlrtFreeMex(emxArray->data); + } + } + emxArray->data = (real_T *)newData; + emxArray->allocatedSize = i; + emxArray->canFreeData = true; + } +} + +void emxFree_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray) +{ + if (*pEmxArray != (emxArray_real_T *)NULL) { + if (((*pEmxArray)->data != (real_T *)NULL) && (*pEmxArray)->canFreeData) { + emlrtFreeMex((*pEmxArray)->data); + } + emlrtFreeMex((*pEmxArray)->size); + emlrtRemoveHeapReference((emlrtCTX)sp, (void *)pEmxArray); + emlrtFreeEmxArray(*pEmxArray); + *pEmxArray = (emxArray_real_T *)NULL; + } +} + +void emxInit_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray, + int32_T numDimensions, const emlrtRTEInfo *srcLocation) +{ + emxArray_real_T *emxArray; + int32_T i; + *pEmxArray = (emxArray_real_T *)emlrtMallocEmxArray(sizeof(emxArray_real_T)); + if ((void *)*pEmxArray == NULL) { + emlrtHeapAllocationErrorR2012b(srcLocation, (emlrtCTX)sp); + } + emlrtPushHeapReferenceStackEmxArray((emlrtCTX)sp, true, (void *)pEmxArray, + (void *)&emxFree_real_T, NULL, NULL, + NULL); + emxArray = *pEmxArray; + emxArray->data = (real_T *)NULL; + emxArray->numDimensions = numDimensions; + emxArray->size = (int32_T *)emlrtMallocMex(sizeof(int32_T) * numDimensions); + if ((void *)emxArray->size == NULL) { + emlrtHeapAllocationErrorR2012b(srcLocation, (emlrtCTX)sp); + } + emxArray->allocatedSize = 0; + emxArray->canFreeData = true; + for (i = 0; i < numDimensions; i++) { + emxArray->size[i] = 0; + } +} + +/* End of code generation (GPExpand_emxutil.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.h b/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.h new file mode 100644 index 0000000..53acc1e --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.h @@ -0,0 +1,34 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_emxutil.h + * + * Code generation for function 'GPExpand_emxutil' + * + */ + +#pragma once + +/* Include files */ +#include "GPExpand_types.h" +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void emxEnsureCapacity_real_T(const emlrtStack *sp, emxArray_real_T *emxArray, + int32_T oldNumel, + const emlrtRTEInfo *srcLocation); + +void emxFree_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray); + +void emxInit_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray, + int32_T numDimensions, const emlrtRTEInfo *srcLocation); + +/* End of code generation (GPExpand_emxutil.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.obj b/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.obj new file mode 100644 index 0000000..eda72b2 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_emxutil.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.c b/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.c new file mode 100644 index 0000000..cabc91a --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.c @@ -0,0 +1,35 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_initialize.c + * + * Code generation for function 'GPExpand_initialize' + * + */ + +/* Include files */ +#include "GPExpand_initialize.h" +#include "GPExpand_data.h" +#include "_coder_GPExpand_mex.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void GPExpand_initialize(void) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + mex_InitInfAndNan(); + mexFunctionCreateRootTLS(); + emlrtBreakCheckR2012bFlagVar = emlrtGetBreakCheckFlagAddressR2012b(); + st.tls = emlrtRootTLSGlobal; + emlrtClearAllocCountR2012b(&st, false, 0U, NULL); + emlrtEnterRtStackR2012b(&st); + emlrtFirstTimeR2012b(emlrtRootTLSGlobal); +} + +/* End of code generation (GPExpand_initialize.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.h b/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.h new file mode 100644 index 0000000..db16b5c --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_initialize.h + * + * Code generation for function 'GPExpand_initialize' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPExpand_initialize(void); + +/* End of code generation (GPExpand_initialize.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.obj b/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.obj new file mode 100644 index 0000000..d148293 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_initialize.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_internal_types.h b/TBM/GP/codegen/mex/GPExpand/GPExpand_internal_types.h new file mode 100644 index 0000000..d8c884a --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_internal_types.h @@ -0,0 +1,30 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_internal_types.h + * + * Code generation for function 'GPExpand' + * + */ + +#pragma once + +/* Include files */ +#include "GPExpand_types.h" +#include "rtwtypes.h" +#include "emlrt.h" + +/* Type Definitions */ +#ifndef typedef_rtDesignRangeCheckInfo +#define typedef_rtDesignRangeCheckInfo +typedef struct { + int32_T lineNo; + int32_T colNo; + const char_T *fName; + const char_T *pName; +} rtDesignRangeCheckInfo; +#endif /* typedef_rtDesignRangeCheckInfo */ + +/* End of code generation (GPExpand_internal_types.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.bat b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.bat new file mode 100644 index 0000000..2aea454 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.bat @@ -0,0 +1,26 @@ +@echo off +set MATLAB=C:\PROGRA~1\MATLAB\R2015a +set MATLAB_ARCH=win64 +set MATLAB_BIN="C:\Program Files\MATLAB\R2015a\bin" +set ENTRYPOINT=mexFunction +set OUTDIR=.\ +set LIB_NAME=GPExpand_mex +set MEX_NAME=GPExpand_mex +set MEX_EXT=.mexw64 +call setEnv.bat +echo # Make settings for GPExpand > GPExpand_mex.mki +echo COMPILER=%COMPILER%>> GPExpand_mex.mki +echo COMPFLAGS=%COMPFLAGS%>> GPExpand_mex.mki +echo OPTIMFLAGS=%OPTIMFLAGS%>> GPExpand_mex.mki +echo DEBUGFLAGS=%DEBUGFLAGS%>> GPExpand_mex.mki +echo LINKER=%LINKER%>> GPExpand_mex.mki +echo LINKFLAGS=%LINKFLAGS%>> GPExpand_mex.mki +echo LINKOPTIMFLAGS=%LINKOPTIMFLAGS%>> GPExpand_mex.mki +echo LINKDEBUGFLAGS=%LINKDEBUGFLAGS%>> GPExpand_mex.mki +echo MATLAB_ARCH=%MATLAB_ARCH%>> GPExpand_mex.mki +echo BORLAND=%BORLAND%>> GPExpand_mex.mki +echo OMPFLAGS= >> GPExpand_mex.mki +echo OMPLINKFLAGS= >> GPExpand_mex.mki +echo EMC_COMPILER=msvcsdk>> GPExpand_mex.mki +echo EMC_CONFIG=optim>> GPExpand_mex.mki +"C:\Program Files\MATLAB\R2015a\bin\win64\gmake" -B -f GPExpand_mex.mk diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.exp b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.exp new file mode 100644 index 0000000..164b78e Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.exp differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.lib b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.lib new file mode 100644 index 0000000..329cc43 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.lib differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mexw64 b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mexw64 new file mode 100644 index 0000000..946a75e Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mexw64 differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mk b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mk new file mode 100644 index 0000000..42432d4 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mk @@ -0,0 +1,122 @@ +START_DIR = D:\TBM_SO~1\TBM\GP + +MATLAB_ROOT = C:\PROGRA~1\MATLAB\R2015a +MAKEFILE = GPExpand_mex.mk + +include GPExpand_mex.mki + + +SRC_FILES = \ + GPExpand_data.c \ + GPExpand_initialize.c \ + GPExpand_terminate.c \ + GPExpand.c \ + floor.c \ + sum.c \ + _coder_GPExpand_api.c \ + _coder_GPExpand_mex.c \ + GPExpand_emxutil.c \ + _coder_GPExpand_info.c + +MEX_FILE_NAME_WO_EXT = GPExpand_mex +MEX_FILE_NAME = $(MEX_FILE_NAME_WO_EXT).mexw64 +TARGET = $(MEX_FILE_NAME) + +SYS_LIBS = + + +# +#==================================================================== +# gmake makefile fragment for building MEX functions using MSVC +# Copyright 2007-2013 The MathWorks, Inc. +#==================================================================== +# +SHELL = cmd +OBJEXT = obj +CC = $(COMPILER) +LD = $(LINKER) +.SUFFIXES: .$(OBJEXT) + +OBJLISTC = $(SRC_FILES:.c=.$(OBJEXT)) +OBJLIST = $(OBJLISTC:.cpp=.$(OBJEXT)) + +ifneq (,$(findstring $(EMC_COMPILER),msvc80 msvc90 msvc100 msvc100free msvc110 msvc120 msvcsdk)) + TARGETMT = $(TARGET).manifest + MEX = $(TARGETMT) + STRICTFP = /fp:strict +else + MEX = $(TARGET) + STRICTFP = /Op +endif + +target: $(MEX) + +MATLAB_INCLUDES = /I "$(MATLAB_ROOT)\simulink\include" +MATLAB_INCLUDES+= /I "$(MATLAB_ROOT)\toolbox\shared\simtargets" +SYS_INCLUDE = $(MATLAB_INCLUDES) + +# Additional includes + +SYS_INCLUDE += /I "$(START_DIR)" +SYS_INCLUDE += /I "$(START_DIR)\codegen\mex\GPExpand" +SYS_INCLUDE += /I "$(START_DIR)\codegen\mex\GPExpand\interface" +SYS_INCLUDE += /I "$(MATLAB_ROOT)\extern\include" +SYS_INCLUDE += /I "." + +DIRECTIVES = $(MEX_FILE_NAME_WO_EXT)_mex.arf +COMP_FLAGS = $(COMPFLAGS) $(OMPFLAGS) -DMX_COMPAT_32 +LINK_FLAGS = $(filter-out /export:mexFunction, $(LINKFLAGS)) +LINK_FLAGS += /NODEFAULTLIB:LIBCMT +ifeq ($(EMC_CONFIG),optim) + COMP_FLAGS += $(OPTIMFLAGS) $(STRICTFP) + LINK_FLAGS += $(LINKOPTIMFLAGS) +else + COMP_FLAGS += $(DEBUGFLAGS) + LINK_FLAGS += $(LINKDEBUGFLAGS) +endif +LINK_FLAGS += $(OMPLINKFLAGS) +LINK_FLAGS += /OUT:$(TARGET) +LINK_FLAGS += + +CFLAGS = $(COMP_FLAGS) $(USER_INCLUDE) $(SYS_INCLUDE) +CPPFLAGS = $(CFLAGS) + +%.$(OBJEXT) : %.c + $(CC) $(CFLAGS) "$<" + +%.$(OBJEXT) : %.cpp + $(CC) $(CPPFLAGS) "$<" + +# Additional sources + +%.$(OBJEXT) : $(START_DIR)/%.c + $(CC) $(CFLAGS) "$<" + +%.$(OBJEXT) : $(START_DIR)\codegen\mex\GPExpand/%.c + $(CC) $(CFLAGS) "$<" + +%.$(OBJEXT) : interface/%.c + $(CC) $(CFLAGS) "$<" + + + +%.$(OBJEXT) : $(START_DIR)/%.cpp + $(CC) $(CPPFLAGS) "$<" + +%.$(OBJEXT) : $(START_DIR)\codegen\mex\GPExpand/%.cpp + $(CC) $(CPPFLAGS) "$<" + +%.$(OBJEXT) : interface/%.cpp + $(CC) $(CPPFLAGS) "$<" + + + +$(TARGET): $(OBJLIST) $(MAKEFILE) $(DIRECTIVES) + $(LD) $(LINK_FLAGS) $(OBJLIST) $(USER_LIBS) $(SYS_LIBS) @$(DIRECTIVES) + @cmd /C "echo Build completed using compiler $(EMC_COMPILER)" + +$(TARGETMT): $(TARGET) + mt -outputresource:"$(TARGET);2" -manifest "$(TARGET).manifest" + +#==================================================================== + diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mki b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mki new file mode 100644 index 0000000..38437f2 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.mki @@ -0,0 +1,15 @@ +# Make settings for GPExpand +COMPILER=cl +COMPFLAGS=/c /GR /W3 /EHs /nologo /MD -I"C:\Program Files\MATLAB\R2015a\extern\include" -I"C:\Program Files\MATLAB\R2015a\simulink\include" /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_SECURE_SCL=0 /DMATLAB_MEX_FILE /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_SECURE_SCL=0 /DMATLAB_MEX_FILE /DMATLAB_MEX_FILE +OPTIMFLAGS=/O2 /Oy- /DNDEBUG +DEBUGFLAGS=/Z7 +LINKER=link +LINKFLAGS=/nologo /manifest /export:mexFunction /DLL /LIBPATH:"C:\Program Files\MATLAB\R2015a\extern\lib\win64\microsoft" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /EXPORT:mexFunction +LINKOPTIMFLAGS= +LINKDEBUGFLAGS=/debug /PDB:".\GPExpand_mex.mexw64.pdb" +MATLAB_ARCH=win64 +BORLAND= +OMPFLAGS= +OMPLINKFLAGS= +EMC_COMPILER=msvcsdk +EMC_CONFIG=optim diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.sh b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.sh new file mode 100644 index 0000000..c62d48d --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex.sh @@ -0,0 +1,2 @@ +"/Applications/MATLAB_R2022a.app/toolbox/shared/coder/ninja/maci64/ninja" -t compdb cc cxx cudac > compile_commands.json +"/Applications/MATLAB_R2022a.app/toolbox/shared/coder/ninja/maci64/ninja" -v "$@" diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_mex_mex.arf b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex_mex.arf new file mode 100644 index 0000000..d5ca913 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_mex_mex.arf @@ -0,0 +1,14 @@ +libemlrt.lib +libcovrt.lib +libut.lib +libmwblas.lib +libmwmathutil.lib +/export:mexFunction +/export:emlrtMexFcnProperties +/export:GPExpand +/export:emxEnsureCapacity +/export:emxFree_real_T +/export:emxInit_real_T +/export:GPExpand_initialize +/export:GPExpand_terminate +/export:GPExpand_atexit diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.c b/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.c new file mode 100644 index 0000000..0f3e5b8 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.c @@ -0,0 +1,46 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_terminate.c + * + * Code generation for function 'GPExpand_terminate' + * + */ + +/* Include files */ +#include "GPExpand_terminate.h" +#include "GPExpand_data.h" +#include "_coder_GPExpand_mex.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void GPExpand_atexit(void) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + mexFunctionCreateRootTLS(); + st.tls = emlrtRootTLSGlobal; + emlrtEnterRtStackR2012b(&st); + emlrtLeaveRtStackR2012b(&st); + emlrtDestroyRootTLS(&emlrtRootTLSGlobal); + emlrtExitTimeCleanup(&emlrtContextGlobal); +} + +void GPExpand_terminate(void) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + st.tls = emlrtRootTLSGlobal; + emlrtLeaveRtStackR2012b(&st); + emlrtDestroyRootTLS(&emlrtRootTLSGlobal); +} + +/* End of code generation (GPExpand_terminate.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.h b/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.h new file mode 100644 index 0000000..0ea7f83 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.h @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_terminate.h + * + * Code generation for function 'GPExpand_terminate' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPExpand_atexit(void); + +void GPExpand_terminate(void); + +/* End of code generation (GPExpand_terminate.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.obj b/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.obj new file mode 100644 index 0000000..db66a1b Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/GPExpand_terminate.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/GPExpand_types.h b/TBM/GP/codegen/mex/GPExpand/GPExpand_types.h new file mode 100644 index 0000000..e481d3f --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/GPExpand_types.h @@ -0,0 +1,34 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPExpand_types.h + * + * Code generation for function 'GPExpand' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" + +/* Type Definitions */ +#ifndef struct_emxArray_real_T +#define struct_emxArray_real_T +struct emxArray_real_T { + real_T *data; + int32_T *size; + int32_T allocatedSize; + int32_T numDimensions; + boolean_T canFreeData; +}; +#endif /* struct_emxArray_real_T */ +#ifndef typedef_emxArray_real_T +#define typedef_emxArray_real_T +typedef struct emxArray_real_T emxArray_real_T; +#endif /* typedef_emxArray_real_T */ + +/* End of code generation (GPExpand_types.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/_clang-format b/TBM/GP/codegen/mex/GPExpand/_clang-format new file mode 100644 index 0000000..55a16f7 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/_clang-format @@ -0,0 +1,27 @@ +BasedOnStyle: LLVM +Language: Cpp +IndentWidth: 2 +ColumnLimit: 80 +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +CommentPragmas: '^(Return Type|Arguments)\s*' +DeriveLineEnding : true +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + SplitEmptyFunction: true + SplitEmptyRecord: true diff --git a/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_api.obj b/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_api.obj new file mode 100644 index 0000000..9f4a6c2 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_api.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_info.obj b/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_info.obj new file mode 100644 index 0000000..0f4e8e4 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_info.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_mex.obj b/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_mex.obj new file mode 100644 index 0000000..f1ee9c8 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/_coder_GPExpand_mex.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/build.ninja b/TBM/GP/codegen/mex/GPExpand/build.ninja new file mode 100644 index 0000000..cc5840d --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/build.ninja @@ -0,0 +1,51 @@ +# CompilerName=clang +# Mode=optim +ninja_required_version = 1.3 + +# Basic folders +root = . +builddir = $root/build/maci64 +matlabdir = /Applications/MATLAB_R2022a.app +startdir = /Users/natasha/Downloads/TBM_software/TBM/GP + +# Toolchain information +cc = /usr/bin/xcrun -sdk macosx12.3 clang +cxx = /usr/bin/xcrun -sdk macosx12.3 clang++ +linker = /usr/bin/xcrun -sdk macosx12.3 clang +linkerxx = /usr/bin/xcrun -sdk macosx12.3 clang++ + +cflags = -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I "$root" -I "$startdir" -I "$root/interface" -I "$matlabdir/extern/include" -I "." -DMODEL=GPExpand -c + +cxxflags = -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -fobjc-arc -std=c++11 -stdlib=libc++ -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c++11 -I "$root" -I "$startdir" -I "$root/interface" -I "$matlabdir/extern/include" -I "." -DMODEL=GPExpand -c + +ldflags = -Wl,-twolevel_namespace -undefined error -arch x86_64 -mmacosx-version-min=10.15 -Wl,-syslibroot,/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -bundle -L"$matlabdir/bin/maci64" -lmx -lmex -lmat -lc++ -Wl,-rpath,@loader_path -o GPExpand.mexmaci64 -lemlrt -lcovrt -lut -lmwmathutil -Wl,-exported_symbols_list,GPExpand.map + +# Build Rules +rule cc + command = $cc $cflags $in -o $out + +rule cxx + command = $cxx $cxxflags $in -o $out + +rule link + command = $linker $in $ldflags + +rule linkxx + command = $linkerxx $in $ldflags + +# Build +build $builddir/GPExpand_data.o : cc $root/GPExpand_data.c +build $builddir/rt_nonfinite.o : cc $root/rt_nonfinite.c +build $builddir/GPExpand_initialize.o : cc $root/GPExpand_initialize.c +build $builddir/GPExpand_terminate.o : cc $root/GPExpand_terminate.c +build $builddir/GPExpand.o : cc $root/GPExpand.c +build $builddir/find.o : cc $root/find.c +build $builddir/sumMatrixIncludeNaN.o : cc $root/sumMatrixIncludeNaN.c +build $builddir/_coder_GPExpand_api.o : cc $root/interface/_coder_GPExpand_api.c +build $builddir/_coder_GPExpand_mex.o : cc $root/interface/_coder_GPExpand_mex.c +build $builddir/GPExpand_emxutil.o : cc $root/GPExpand_emxutil.c +build $builddir/_coder_GPExpand_info.o : cc $root/interface/_coder_GPExpand_info.c +build $builddir/c_mexapi_version.o : cc $matlabdir/extern/version/c_mexapi_version.c + +# Link +build $root/GPExpand.mexmaci64 : link $builddir/GPExpand_data.o $builddir/rt_nonfinite.o $builddir/GPExpand_initialize.o $builddir/GPExpand_terminate.o $builddir/GPExpand.o $builddir/find.o $builddir/sumMatrixIncludeNaN.o $builddir/_coder_GPExpand_api.o $builddir/_coder_GPExpand_mex.o $builddir/GPExpand_emxutil.o $builddir/_coder_GPExpand_info.o $builddir/c_mexapi_version.o diff --git a/TBM/GP/codegen/mex/GPExpand/buildInfo.mat b/TBM/GP/codegen/mex/GPExpand/buildInfo.mat new file mode 100644 index 0000000..0ed6983 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/buildInfo.mat differ diff --git a/TBM/GP/codegen/mex/GPExpand/compile_commands.json b/TBM/GP/codegen/mex/GPExpand/compile_commands.json new file mode 100644 index 0000000..ea0250b --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/compile_commands.json @@ -0,0 +1,74 @@ +[ + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c GPExpand_data.c -o build/maci64/GPExpand_data.o", + "file": "GPExpand_data.c", + "output": "build/maci64/GPExpand_data.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c rt_nonfinite.c -o build/maci64/rt_nonfinite.o", + "file": "rt_nonfinite.c", + "output": "build/maci64/rt_nonfinite.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c GPExpand_initialize.c -o build/maci64/GPExpand_initialize.o", + "file": "GPExpand_initialize.c", + "output": "build/maci64/GPExpand_initialize.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c GPExpand_terminate.c -o build/maci64/GPExpand_terminate.o", + "file": "GPExpand_terminate.c", + "output": "build/maci64/GPExpand_terminate.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c GPExpand.c -o build/maci64/GPExpand.o", + "file": "GPExpand.c", + "output": "build/maci64/GPExpand.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c find.c -o build/maci64/find.o", + "file": "find.c", + "output": "build/maci64/find.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c sumMatrixIncludeNaN.c -o build/maci64/sumMatrixIncludeNaN.o", + "file": "sumMatrixIncludeNaN.c", + "output": "build/maci64/sumMatrixIncludeNaN.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c interface/_coder_GPExpand_api.c -o build/maci64/_coder_GPExpand_api.o", + "file": "interface/_coder_GPExpand_api.c", + "output": "build/maci64/_coder_GPExpand_api.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c interface/_coder_GPExpand_mex.c -o build/maci64/_coder_GPExpand_mex.o", + "file": "interface/_coder_GPExpand_mex.c", + "output": "build/maci64/_coder_GPExpand_mex.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c GPExpand_emxutil.c -o build/maci64/GPExpand_emxutil.o", + "file": "GPExpand_emxutil.c", + "output": "build/maci64/GPExpand_emxutil.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c interface/_coder_GPExpand_info.c -o build/maci64/_coder_GPExpand_info.o", + "file": "interface/_coder_GPExpand_info.c", + "output": "build/maci64/_coder_GPExpand_info.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPExpand", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPExpand -c /Applications/MATLAB_R2022a.app/extern/version/c_mexapi_version.c -o build/maci64/c_mexapi_version.o", + "file": "/Applications/MATLAB_R2022a.app/extern/version/c_mexapi_version.c", + "output": "build/maci64/c_mexapi_version.o" + } +] diff --git a/TBM/GP/codegen/mex/GPExpand/find.c b/TBM/GP/codegen/mex/GPExpand/find.c new file mode 100644 index 0000000..a127ba1 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/find.c @@ -0,0 +1,46 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * find.c + * + * Code generation for function 'find' + * + */ + +/* Include files */ +#include "find.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void eml_find(const boolean_T x[5], int32_T i_data[], int32_T i_size[2]) +{ + int32_T idx; + int32_T ii; + boolean_T exitg1; + idx = 0; + i_size[0] = 1; + ii = 0; + exitg1 = false; + while ((!exitg1) && (ii < 5)) { + if (x[ii]) { + idx++; + i_data[idx - 1] = ii + 1; + if (idx >= 5) { + exitg1 = true; + } else { + ii++; + } + } else { + ii++; + } + } + if (idx < 1) { + i_size[1] = 0; + } else { + i_size[1] = idx; + } +} + +/* End of code generation (find.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/find.h b/TBM/GP/codegen/mex/GPExpand/find.h new file mode 100644 index 0000000..20c9bc3 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/find.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * find.h + * + * Code generation for function 'find' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void eml_find(const boolean_T x[5], int32_T i_data[], int32_T i_size[2]); + +/* End of code generation (find.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/floor.obj b/TBM/GP/codegen/mex/GPExpand/floor.obj new file mode 100644 index 0000000..b14165f Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/floor.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_api.c b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_api.c new file mode 100644 index 0000000..5891409 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_api.c @@ -0,0 +1,169 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPExpand_api.c + * + * Code generation for function '_coder_GPExpand_api' + * + */ + +/* Include files */ +#include "_coder_GPExpand_api.h" +#include "GPExpand.h" +#include "GPExpand_data.h" +#include "GPExpand_emxutil.h" +#include "GPExpand_types.h" +#include "rt_nonfinite.h" + +/* Variable Definitions */ +static emlrtRTEInfo m_emlrtRTEI = { + 1, /* lineNo */ + 1, /* colNo */ + "_coder_GPExpand_api", /* fName */ + "" /* pName */ +}; + +/* Function Declarations */ +static void b_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, + const emlrtMsgIdentifier *parentId, + emxArray_real_T *y); + +static real_T (*c_emlrt_marshallIn(const emlrtStack *sp, const mxArray *newdim, + const char_T *identifier))[3]; + +static real_T (*d_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, + const emlrtMsgIdentifier *parentId))[3]; + +static void e_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, + const emlrtMsgIdentifier *msgId, + emxArray_real_T *ret); + +static void emlrt_marshallIn(const emlrtStack *sp, const mxArray *b_I, + const char_T *identifier, emxArray_real_T *y); + +static const mxArray *emlrt_marshallOut(const emxArray_real_T *u); + +static real_T (*f_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, + const emlrtMsgIdentifier *msgId))[3]; + +/* Function Definitions */ +static void b_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, + const emlrtMsgIdentifier *parentId, + emxArray_real_T *y) +{ + e_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y); + emlrtDestroyArray(&u); +} + +static real_T (*c_emlrt_marshallIn(const emlrtStack *sp, const mxArray *newdim, + const char_T *identifier))[3] +{ + emlrtMsgIdentifier thisId; + real_T(*y)[3]; + thisId.fIdentifier = (const char_T *)identifier; + thisId.fParent = NULL; + thisId.bParentIsCell = false; + y = d_emlrt_marshallIn(sp, emlrtAlias(newdim), &thisId); + emlrtDestroyArray(&newdim); + return y; +} + +static real_T (*d_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, + const emlrtMsgIdentifier *parentId))[3] +{ + real_T(*y)[3]; + y = f_emlrt_marshallIn(sp, emlrtAlias(u), parentId); + emlrtDestroyArray(&u); + return y; +} + +static void e_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, + const emlrtMsgIdentifier *msgId, + emxArray_real_T *ret) +{ + static const int32_T dims[3] = {-1, -1, -1}; + int32_T iv[3]; + int32_T i; + const boolean_T bv[3] = {true, true, true}; + emlrtCheckVsBuiltInR2012b((emlrtCTX)sp, msgId, src, (const char_T *)"double", + false, 3U, (void *)&dims[0], &bv[0], &iv[0]); + ret->allocatedSize = iv[0] * iv[1] * iv[2]; + i = ret->size[0] * ret->size[1] * ret->size[2]; + ret->size[0] = iv[0]; + ret->size[1] = iv[1]; + ret->size[2] = iv[2]; + emxEnsureCapacity_real_T(sp, ret, i, (emlrtRTEInfo *)NULL); + ret->data = (real_T *)emlrtMxGetData(src); + ret->canFreeData = false; + emlrtDestroyArray(&src); +} + +static void emlrt_marshallIn(const emlrtStack *sp, const mxArray *b_I, + const char_T *identifier, emxArray_real_T *y) +{ + emlrtMsgIdentifier thisId; + thisId.fIdentifier = (const char_T *)identifier; + thisId.fParent = NULL; + thisId.bParentIsCell = false; + b_emlrt_marshallIn(sp, emlrtAlias(b_I), &thisId, y); + emlrtDestroyArray(&b_I); +} + +static const mxArray *emlrt_marshallOut(const emxArray_real_T *u) +{ + static const int32_T iv[3] = {0, 0, 0}; + const mxArray *m; + const mxArray *y; + const real_T *u_data; + u_data = u->data; + y = NULL; + m = emlrtCreateNumericArray(3, (const void *)&iv[0], mxDOUBLE_CLASS, mxREAL); + emlrtMxSetData((mxArray *)m, (void *)&u_data[0]); + emlrtSetDimensions((mxArray *)m, &u->size[0], 3); + emlrtAssign(&y, m); + return y; +} + +static real_T (*f_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, + const emlrtMsgIdentifier *msgId))[3] +{ + static const int32_T dims[2] = {1, 3}; + real_T(*ret)[3]; + emlrtCheckBuiltInR2012b((emlrtCTX)sp, msgId, src, (const char_T *)"double", + false, 2U, (void *)&dims[0]); + ret = (real_T(*)[3])emlrtMxGetData(src); + emlrtDestroyArray(&src); + return ret; +} + +void GPExpand_api(const mxArray *const prhs[2], const mxArray **plhs) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + emxArray_real_T *IResult; + emxArray_real_T *b_I; + real_T(*newdim)[3]; + st.tls = emlrtRootTLSGlobal; + emlrtHeapReferenceStackEnterFcnR2012b(&st); + emxInit_real_T(&st, &b_I, 3, &m_emlrtRTEI); + emxInit_real_T(&st, &IResult, 3, &m_emlrtRTEI); + /* Marshall function inputs */ + b_I->canFreeData = false; + emlrt_marshallIn(&st, emlrtAlias(prhs[0]), "I", b_I); + newdim = c_emlrt_marshallIn(&st, emlrtAlias(prhs[1]), "newdim"); + /* Invoke the target function */ + GPExpand(&st, b_I, *newdim, IResult); + /* Marshall function outputs */ + IResult->canFreeData = false; + *plhs = emlrt_marshallOut(IResult); + emxFree_real_T(&st, &IResult); + emxFree_real_T(&st, &b_I); + emlrtHeapReferenceStackLeaveFcnR2012b(&st); +} + +/* End of code generation (_coder_GPExpand_api.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_api.h b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_api.h new file mode 100644 index 0000000..9e3f68f --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_api.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPExpand_api.h + * + * Code generation for function '_coder_GPExpand_api' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPExpand_api(const mxArray *const prhs[2], const mxArray **plhs); + +/* End of code generation (_coder_GPExpand_api.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_info.c b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_info.c new file mode 100644 index 0000000..4a09cf7 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_info.c @@ -0,0 +1,73 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPExpand_info.c + * + * Code generation for function 'GPExpand' + * + */ + +/* Include files */ +#include "_coder_GPExpand_info.h" +#include "emlrt.h" +#include "tmwtypes.h" + +/* Function Declarations */ +static const mxArray *emlrtMexFcnResolvedFunctionsInfo(void); + +/* Function Definitions */ +static const mxArray *emlrtMexFcnResolvedFunctionsInfo(void) +{ + static const int32_T iv[2] = {0, 1}; + const mxArray *m; + const mxArray *nameCaptureInfo; + nameCaptureInfo = NULL; + m = emlrtCreateNumericArray(2, (const void *)&iv[0], mxDOUBLE_CLASS, mxREAL); + emlrtAssign(&nameCaptureInfo, m); + return nameCaptureInfo; +} + +mxArray *emlrtMexFcnProperties(void) +{ + mxArray *xEntryPoints; + mxArray *xInputs; + mxArray *xResult; + const char_T *epFieldName[6] = { + "Name", "NumberOfInputs", "NumberOfOutputs", + "ConstantInputs", "FullPath", "TimeStamp"}; + const char_T *propFieldName[6] = {"Version", "ResolvedFunctions", + "Checksum", "EntryPoints", + "CoverageInfo", "IsPolymorphic"}; + xEntryPoints = + emlrtCreateStructMatrix(1, 1, 6, (const char_T **)&epFieldName[0]); + xInputs = emlrtCreateLogicalMatrix(1, 2); + emlrtSetField(xEntryPoints, 0, (const char_T *)"Name", + emlrtMxCreateString((const char_T *)"GPExpand")); + emlrtSetField(xEntryPoints, 0, (const char_T *)"NumberOfInputs", + emlrtMxCreateDoubleScalar(2.0)); + emlrtSetField(xEntryPoints, 0, (const char_T *)"NumberOfOutputs", + emlrtMxCreateDoubleScalar(1.0)); + emlrtSetField(xEntryPoints, 0, (const char_T *)"ConstantInputs", xInputs); + emlrtSetField( + xEntryPoints, 0, (const char_T *)"FullPath", + emlrtMxCreateString( + (const char_T + *)"/Users/natasha/Downloads/TBM_software/TBM/GP/GPExpand.m")); + emlrtSetField(xEntryPoints, 0, (const char_T *)"TimeStamp", + emlrtMxCreateDoubleScalar(736524.36016203708)); + xResult = + emlrtCreateStructMatrix(1, 1, 6, (const char_T **)&propFieldName[0]); + emlrtSetField( + xResult, 0, (const char_T *)"Version", + emlrtMxCreateString((const char_T *)"9.12.0.2009381 (R2022a) Update 4")); + emlrtSetField(xResult, 0, (const char_T *)"ResolvedFunctions", + (mxArray *)emlrtMexFcnResolvedFunctionsInfo()); + emlrtSetField(xResult, 0, (const char_T *)"Checksum", + emlrtMxCreateString((const char_T *)"UZNV6GSDjNHqUjgyPa3PcG")); + emlrtSetField(xResult, 0, (const char_T *)"EntryPoints", xEntryPoints); + return xResult; +} + +/* End of code generation (_coder_GPExpand_info.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_info.h b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_info.h new file mode 100644 index 0000000..c5f3d7b --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_info.h @@ -0,0 +1,20 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPExpand_info.h + * + * Code generation for function 'GPExpand' + * + */ + +#pragma once + +/* Include files */ +#include "mex.h" + +/* Function Declarations */ +MEXFUNCTION_LINKAGE mxArray *emlrtMexFcnProperties(void); + +/* End of code generation (_coder_GPExpand_info.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_mex.c b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_mex.c new file mode 100644 index 0000000..ec273c7 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_mex.c @@ -0,0 +1,65 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPExpand_mex.c + * + * Code generation for function '_coder_GPExpand_mex' + * + */ + +/* Include files */ +#include "_coder_GPExpand_mex.h" +#include "GPExpand_data.h" +#include "GPExpand_initialize.h" +#include "GPExpand_terminate.h" +#include "_coder_GPExpand_api.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void GPExpand_mexFunction(int32_T nlhs, mxArray *plhs[1], int32_T nrhs, + const mxArray *prhs[2]) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + const mxArray *outputs; + st.tls = emlrtRootTLSGlobal; + /* Check for proper number of arguments. */ + if (nrhs != 2) { + emlrtErrMsgIdAndTxt(&st, "EMLRT:runTime:WrongNumberOfInputs", 5, 12, 2, 4, + 8, "GPExpand"); + } + if (nlhs > 1) { + emlrtErrMsgIdAndTxt(&st, "EMLRT:runTime:TooManyOutputArguments", 3, 4, 8, + "GPExpand"); + } + /* Call the function. */ + GPExpand_api(prhs, &outputs); + /* Copy over outputs to the caller. */ + emlrtReturnArrays(1, &plhs[0], &outputs); +} + +void mexFunction(int32_T nlhs, mxArray *plhs[], int32_T nrhs, + const mxArray *prhs[]) +{ + mexAtExit(&GPExpand_atexit); + /* Module initialization. */ + GPExpand_initialize(); + /* Dispatch the entry-point. */ + GPExpand_mexFunction(nlhs, plhs, nrhs, prhs); + /* Module termination. */ + GPExpand_terminate(); +} + +emlrtCTX mexFunctionCreateRootTLS(void) +{ + emlrtCreateRootTLSR2022a(&emlrtRootTLSGlobal, &emlrtContextGlobal, NULL, 1, + NULL, (const char_T *)"UTF-8", true); + return emlrtRootTLSGlobal; +} + +/* End of code generation (_coder_GPExpand_mex.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_mex.h b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_mex.h new file mode 100644 index 0000000..aedd864 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/interface/_coder_GPExpand_mex.h @@ -0,0 +1,32 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPExpand_mex.h + * + * Code generation for function '_coder_GPExpand_mex' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPExpand_mexFunction(int32_T nlhs, mxArray *plhs[1], int32_T nrhs, + const mxArray *prhs[2]); + +MEXFUNCTION_LINKAGE void mexFunction(int32_T nlhs, mxArray *plhs[], + int32_T nrhs, const mxArray *prhs[]); + +emlrtCTX mexFunctionCreateRootTLS(void); + +/* End of code generation (_coder_GPExpand_mex.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/rt_nonfinite.c b/TBM/GP/codegen/mex/GPExpand/rt_nonfinite.c new file mode 100644 index 0000000..58d73e4 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/rt_nonfinite.c @@ -0,0 +1,32 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * rt_nonfinite.c + * + * Code generation for function 'GPExpand' + * + */ + +/* Include files */ +#include "rt_nonfinite.h" +#include "matrix.h" + +real_T mex_rtInf; +real_T mex_rtMinusInf; +real_T mex_rtNaN; +real32_T mex_rtInfF; +real32_T mex_rtMinusInfF; +real32_T mex_rtNaNF; + +void mex_InitInfAndNan(void) +{ + mex_rtInf = mxGetInf(); + mex_rtMinusInf = -rtInf; + mex_rtInfF = (real32_T)rtInf; + mex_rtMinusInfF = -rtInfF; + mex_rtNaN = mxGetNaN(); + mex_rtNaNF = (real32_T)rtNaN; +} +/* End of code generation (rt_nonfinite.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/rt_nonfinite.h b/TBM/GP/codegen/mex/GPExpand/rt_nonfinite.h new file mode 100644 index 0000000..0bc01a4 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/rt_nonfinite.h @@ -0,0 +1,38 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * rt_nonfinite.h + * + * Code generation for function 'GPExpand' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "tmwtypes.h" + +extern real_T mex_rtInf; +extern real_T mex_rtMinusInf; +extern real_T mex_rtNaN; +extern real32_T mex_rtInfF; +extern real32_T mex_rtMinusInfF; +extern real32_T mex_rtNaNF; + +#define rtInf mex_rtInf +#define rtMinusInf mex_rtMinusInf +#define rtNaN mex_rtNaN +#define rtInfF mex_rtInfF +#define rtMinusInfF mex_rtMinusInfF +#define rtNaNF mex_rtNaNF +#define rtIsNaN(X) mxIsNaN(X) +#define rtIsInf(X) mxIsInf(X) +#define rtIsNaNF(X) mxIsNaN(X) +#define rtIsInfF(X) mxIsInf(X) + +extern void mex_InitInfAndNan(void); + +/* End of code generation (rt_nonfinite.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/rtwtypes.h b/TBM/GP/codegen/mex/GPExpand/rtwtypes.h new file mode 100644 index 0000000..ac31c71 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/rtwtypes.h @@ -0,0 +1,27 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * rtwtypes.h + * + * Code generation for function 'GPExpand' + * + */ + +#pragma once + +/* Include files */ +#include "tmwtypes.h" + +/* + * TRUE/FALSE definitions + */ +#ifndef TRUE +#define TRUE (1U) +#endif +#ifndef FALSE +#define FALSE (0U) +#endif + +/* End of code generation (rtwtypes.h) */ diff --git a/TBM/GP/codegen/mex/GPExpand/setEnv.bat b/TBM/GP/codegen/mex/GPExpand/setEnv.bat new file mode 100644 index 0000000..1a355b9 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/setEnv.bat @@ -0,0 +1,12 @@ +set COMPILER=cl + set COMPFLAGS=/c /GR /W3 /EHs /nologo /MD -I"C:\Program Files\MATLAB\R2015a\extern\include" -I"C:\Program Files\MATLAB\R2015a\simulink\include" /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_SECURE_SCL=0 /DMATLAB_MEX_FILE /D_CRT_SECURE_NO_DEPRECATE /D_SCL_SECURE_NO_DEPRECATE /D_SECURE_SCL=0 /DMATLAB_MEX_FILE /DMATLAB_MEX_FILE + set OPTIMFLAGS=/O2 /Oy- /DNDEBUG + set DEBUGFLAGS=/Z7 + set LINKER=link + set LINKFLAGS=/nologo /manifest /export:%ENTRYPOINT% /DLL /LIBPATH:"C:\Program Files\MATLAB\R2015a\extern\lib\win64\microsoft" libmx.lib libmex.lib libmat.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /EXPORT:mexFunction + set LINKDEBUGFLAGS=/debug /PDB:"%OUTDIR%%MEX_NAME%.mexw64.pdb" + set NAME_OUTPUT=/out:"%OUTDIR%%MEX_NAME%%MEX_EXT%" +set PATH=c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Bin\amd64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Bin\VCPackages;C:\Program Files\Microsoft SDKs\Windows\v7.1\\Bin\x64;C:\Program Files\Microsoft SDKs\Windows\v7.1\\Bin;;%MATLAB_BIN%;%PATH% +set INCLUDE=c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE;C:\Program Files\Microsoft SDKs\Windows\v7.1\\INCLUDE;C:\Program Files\Microsoft SDKs\Windows\v7.1\\INCLUDE\gl;C:\Program Files\MATLAB\R2015a\extern\include;;%INCLUDE% +set LIB=c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Lib\amd64;C:\Program Files\Microsoft SDKs\Windows\v7.1\\Lib\X64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\ATLMFC\LIB\AMD64;C:\Program Files\MATLAB\R2015a\lib\win64;C:\Program Files\MATLAB\R2015a\extern\lib\win64;%LIB% +set LIBPATH=c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\Lib\amd64;C:\Program Files\Microsoft SDKs\Windows\v7.1\\LIB\X64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\ATLMFC\LIB\AMD64;C:\Program Files\MATLAB\R2015a\extern\lib\win64;%LIBPATH% diff --git a/TBM/GP/codegen/mex/GPExpand/sum.obj b/TBM/GP/codegen/mex/GPExpand/sum.obj new file mode 100644 index 0000000..4a5daf3 Binary files /dev/null and b/TBM/GP/codegen/mex/GPExpand/sum.obj differ diff --git a/TBM/GP/codegen/mex/GPExpand/sumMatrixIncludeNaN.c b/TBM/GP/codegen/mex/GPExpand/sumMatrixIncludeNaN.c new file mode 100644 index 0000000..8f8b353 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/sumMatrixIncludeNaN.c @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * sumMatrixIncludeNaN.c + * + * Code generation for function 'sumMatrixIncludeNaN' + * + */ + +/* Include files */ +#include "sumMatrixIncludeNaN.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +real_T sumColumnB(const real_T x_data[], int32_T vlen) +{ + real_T y; + int32_T k; + y = x_data[0]; + for (k = 0; k <= vlen - 2; k++) { + y += x_data[k + 1]; + } + return y; +} + +/* End of code generation (sumMatrixIncludeNaN.c) */ diff --git a/TBM/GP/codegen/mex/GPExpand/sumMatrixIncludeNaN.h b/TBM/GP/codegen/mex/GPExpand/sumMatrixIncludeNaN.h new file mode 100644 index 0000000..de0bb94 --- /dev/null +++ b/TBM/GP/codegen/mex/GPExpand/sumMatrixIncludeNaN.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * sumMatrixIncludeNaN.h + * + * Code generation for function 'sumMatrixIncludeNaN' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +real_T sumColumnB(const real_T x_data[], int32_T vlen); + +/* End of code generation (sumMatrixIncludeNaN.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce.c b/TBM/GP/codegen/mex/GPReduce/GPReduce.c new file mode 100644 index 0000000..b2d2b57 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce.c @@ -0,0 +1,1202 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce.c + * + * Code generation for function 'GPReduce' + * + */ + +/* Include files */ +#include "GPReduce.h" +#include "GPReduce_data.h" +#include "GPReduce_emxutil.h" +#include "GPReduce_types.h" +#include "rt_nonfinite.h" +#include "sumMatrixIncludeNaN.h" +#include "mwmathutil.h" + +/* Variable Definitions */ +static emlrtBCInfo emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 45, /* lineNo */ + 8, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo b_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 45, /* lineNo */ + 19, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo c_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 45, /* lineNo */ + 30, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo emlrtECI = { + -1, /* nDims */ + 45, /* lineNo */ + 3, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtECInfo b_emlrtECI = { + -1, /* nDims */ + 46, /* lineNo */ + 3, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtECInfo c_emlrtECI = { + -1, /* nDims */ + 46, /* lineNo */ + 23, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo d_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 46, /* lineNo */ + 58, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo e_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 46, /* lineNo */ + 46, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo d_emlrtECI = { + -1, /* nDims */ + 46, /* lineNo */ + 43, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo f_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 46, /* lineNo */ + 86, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo g_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 46, /* lineNo */ + 72, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo e_emlrtECI = { + -1, /* nDims */ + 46, /* lineNo */ + 69, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtECInfo f_emlrtECI = { + -1, /* nDims */ + 47, /* lineNo */ + 3, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtECInfo g_emlrtECI = { + -1, /* nDims */ + 47, /* lineNo */ + 23, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo h_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 47, /* lineNo */ + 60, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo i_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 47, /* lineNo */ + 48, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo h_emlrtECI = { + -1, /* nDims */ + 47, /* lineNo */ + 43, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo j_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 47, /* lineNo */ + 88, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo k_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 47, /* lineNo */ + 74, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo i_emlrtECI = { + -1, /* nDims */ + 47, /* lineNo */ + 69, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtECInfo j_emlrtECI = { + -1, /* nDims */ + 48, /* lineNo */ + 3, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtECInfo k_emlrtECI = { + -1, /* nDims */ + 48, /* lineNo */ + 23, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo l_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 48, /* lineNo */ + 62, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo m_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 48, /* lineNo */ + 50, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo l_emlrtECI = { + -1, /* nDims */ + 48, /* lineNo */ + 43, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo n_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 48, /* lineNo */ + 90, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo o_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 48, /* lineNo */ + 76, /* colNo */ + "I2", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtECInfo m_emlrtECI = { + -1, /* nDims */ + 48, /* lineNo */ + 69, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtBCInfo p_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 54, /* lineNo */ + 12, /* colNo */ + "I", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo q_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 54, /* lineNo */ + 20, /* colNo */ + "I", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo r_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 54, /* lineNo */ + 28, /* colNo */ + "I", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo s_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 55, /* lineNo */ + 14, /* colNo */ + "IResult", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo t_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 55, /* lineNo */ + 18, /* colNo */ + "IResult", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtBCInfo u_emlrtBCI = { + -1, /* iFirst */ + -1, /* iLast */ + 55, /* lineNo */ + 22, /* colNo */ + "IResult", /* aName */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 0 /* checkKind */ +}; + +static emlrtDCInfo emlrtDCI = { + 44, /* lineNo */ + 14, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m", /* pName */ + 1 /* checkKind */ +}; + +static emlrtRTEInfo emlrtRTEI = { + 10, /* lineNo */ + 1, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo b_emlrtRTEI = { + 44, /* lineNo */ + 3, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo c_emlrtRTEI = { + 46, /* lineNo */ + 13, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo d_emlrtRTEI = { + 46, /* lineNo */ + 33, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo e_emlrtRTEI = { + 46, /* lineNo */ + 55, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo f_emlrtRTEI = { + 46, /* lineNo */ + 83, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo g_emlrtRTEI = { + 47, /* lineNo */ + 13, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo h_emlrtRTEI = { + 47, /* lineNo */ + 33, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo i_emlrtRTEI = { + 47, /* lineNo */ + 55, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo j_emlrtRTEI = { + 47, /* lineNo */ + 83, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo k_emlrtRTEI = { + 48, /* lineNo */ + 13, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo l_emlrtRTEI = { + 48, /* lineNo */ + 33, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo m_emlrtRTEI = { + 48, /* lineNo */ + 55, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +static emlrtRTEInfo n_emlrtRTEI = { + 48, /* lineNo */ + 83, /* colNo */ + "GPReduce", /* fName */ + "/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m" /* pName */ +}; + +/* Function Definitions */ +void GPReduce(const emlrtStack *sp, const emxArray_real_T *b_I, + emxArray_real_T *IResult) +{ + static const real_T dv[5] = {0.05, 0.25, 0.4, 0.25, 0.05}; + emxArray_real_T *I2; + emxArray_real_T *c_I2; + emxArray_real_T *e_I2; + emxArray_real_T *f_I2; + real_T Wt3[125]; + const real_T *I_data; + real_T *I2_data; + real_T *IResult_data; + real_T *b_I2_data; + int32_T b_I2[3]; + int32_T g_I2[2]; + int32_T iv[2]; + int32_T Wt3_tmp; + int32_T b_i; + int32_T b_loop_ub; + int32_T d_I2; + int32_T i; + int32_T i1; + int32_T i2; + int32_T i3; + int32_T i4; + int32_T i5; + int32_T i6; + int32_T k; + int32_T loop_ub; + int32_T newdim_idx_0; + int32_T newdim_idx_1; + int32_T newdim_idx_2; + I_data = b_I->data; + emlrtHeapReferenceStackEnterFcnR2012b((emlrtCTX)sp); + /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + /* Reduce an image applying Gaussian Pyramid. */ + /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */ + newdim_idx_0 = (int32_T)muDoubleScalarCeil((real_T)b_I->size[0] * 0.5); + newdim_idx_1 = (int32_T)muDoubleScalarCeil((real_T)b_I->size[1] * 0.5); + newdim_idx_2 = (int32_T)muDoubleScalarCeil((real_T)b_I->size[2] * 0.5); + i = IResult->size[0] * IResult->size[1] * IResult->size[2]; + IResult->size[0] = newdim_idx_0; + IResult->size[1] = newdim_idx_1; + IResult->size[2] = newdim_idx_2; + emxEnsureCapacity_real_T(sp, IResult, i, &emlrtRTEI); + IResult_data = IResult->data; + loop_ub = newdim_idx_0 * newdim_idx_1 * newdim_idx_2; + for (i = 0; i < loop_ub; i++) { + IResult_data[i] = 0.0; + } + /* Initialize the array in the beginning .. */ + for (i = 0; i < 125; i++) { + Wt3[i] = 1.0; + } + for (b_i = 0; b_i < 5; b_i++) { + real_T b; + b = dv[b_i]; + for (i = 0; i < 5; i++) { + for (i1 = 0; i1 < 5; i1++) { + Wt3_tmp = (b_i + 5 * i1) + 25 * i; + Wt3[Wt3_tmp] *= b; + } + for (i1 = 0; i1 < 5; i1++) { + Wt3_tmp = (i1 + 5 * b_i) + 25 * i; + Wt3[Wt3_tmp] *= b; + } + } + for (i = 0; i < 5; i++) { + for (i1 = 0; i1 < 5; i1++) { + Wt3_tmp = (i1 + 5 * i) + 25 * b_i; + Wt3[Wt3_tmp] *= b; + } + } + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + /* %% Pad the boundaries. */ + if ((real_T)b_I->size[0] + 4.0 != b_I->size[0] + 4) { + emlrtIntegerCheckR2012b((real_T)b_I->size[0] + 4.0, &emlrtDCI, + (emlrtCTX)sp); + } + if ((real_T)b_I->size[1] + 4.0 != b_I->size[1] + 4) { + emlrtIntegerCheckR2012b((real_T)b_I->size[1] + 4.0, &emlrtDCI, + (emlrtCTX)sp); + } + if ((real_T)b_I->size[2] + 4.0 != b_I->size[2] + 4) { + emlrtIntegerCheckR2012b((real_T)b_I->size[2] + 4.0, &emlrtDCI, + (emlrtCTX)sp); + } + emxInit_real_T(sp, &I2, 3, &b_emlrtRTEI); + i = I2->size[0] * I2->size[1] * I2->size[2]; + I2->size[0] = (int32_T)(uint32_T)((real_T)b_I->size[0] + 4.0); + I2->size[1] = (int32_T)(uint32_T)((real_T)b_I->size[1] + 4.0); + I2->size[2] = (int32_T)(uint32_T)((real_T)b_I->size[2] + 4.0); + emxEnsureCapacity_real_T(sp, I2, i, &b_emlrtRTEI); + I2_data = I2->data; + loop_ub = (int32_T)(uint32_T)((real_T)b_I->size[0] + 4.0) * + (int32_T)(uint32_T)((real_T)b_I->size[1] + 4.0) * + (int32_T)(uint32_T)((real_T)b_I->size[2] + 4.0); + for (i = 0; i < loop_ub; i++) { + I2_data[i] = 0.0; + } + if (b_I->size[0] + 2U < 3U) { + i = 0; + i1 = 0; + } else { + i = 2; + if (((int32_T)(b_I->size[0] + 2U) < 1) || + ((int32_T)(b_I->size[0] + 2U) > + (int32_T)(uint32_T)((real_T)b_I->size[0] + 4.0))) { + emlrtDynamicBoundsCheckR2012b( + (int32_T)(b_I->size[0] + 2U), 1, + (int32_T)(uint32_T)((real_T)b_I->size[0] + 4.0), &emlrtBCI, + (emlrtCTX)sp); + } + i1 = (int32_T)(b_I->size[0] + 2U); + } + if (b_I->size[1] + 2U < 3U) { + i2 = 0; + i3 = 0; + } else { + i2 = 2; + if (((int32_T)(b_I->size[1] + 2U) < 1) || + ((int32_T)(b_I->size[1] + 2U) > + (int32_T)(uint32_T)((real_T)b_I->size[1] + 4.0))) { + emlrtDynamicBoundsCheckR2012b( + (int32_T)(b_I->size[1] + 2U), 1, + (int32_T)(uint32_T)((real_T)b_I->size[1] + 4.0), &b_emlrtBCI, + (emlrtCTX)sp); + } + i3 = (int32_T)(b_I->size[1] + 2U); + } + if (b_I->size[2] + 2U < 3U) { + i4 = 0; + i5 = 0; + } else { + i4 = 2; + if (((int32_T)(b_I->size[2] + 2U) < 1) || + ((int32_T)(b_I->size[2] + 2U) > + (int32_T)(uint32_T)((real_T)b_I->size[2] + 4.0))) { + emlrtDynamicBoundsCheckR2012b( + (int32_T)(b_I->size[2] + 2U), 1, + (int32_T)(uint32_T)((real_T)b_I->size[2] + 4.0), &c_emlrtBCI, + (emlrtCTX)sp); + } + i5 = (int32_T)(b_I->size[2] + 2U); + } + b_I2[0] = i1 - i; + b_I2[1] = i3 - i2; + b_I2[2] = i5 - i4; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &b_I->size[0], 3, &emlrtECI, + (emlrtCTX)sp); + loop_ub = b_I->size[2]; + for (i1 = 0; i1 < loop_ub; i1++) { + b_loop_ub = b_I->size[1]; + for (i3 = 0; i3 < b_loop_ub; i3++) { + Wt3_tmp = b_I->size[0]; + for (i5 = 0; i5 < Wt3_tmp; i5++) { + I2_data[((i + i5) + I2->size[0] * (i2 + i3)) + + I2->size[0] * I2->size[1] * (i4 + i1)] = + I_data[(i5 + b_I->size[0] * i3) + b_I->size[0] * b_I->size[1] * i1]; + } + } + } + emxInit_real_T(sp, &c_I2, 3, &c_emlrtRTEI); + loop_ub = I2->size[1]; + b_loop_ub = I2->size[2]; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &c_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[(I2->size[0] * i1 + I2->size[0] * I2->size[1] * i) + 2]; + } + } + b_I2[0] = 1; + b_I2[1] = I2->size[1]; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &c_I2->size[0], 3, &b_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[1] - 1; + loop_ub = I2->size[2] - 1; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &c_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[(I2->size[0] * i1 + I2->size[0] * I2->size[1] * i) + 2]; + } + } + loop_ub = c_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = c_I2->size[1]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[I2->size[0] * i1 + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + c_I2->size[1] * i]; + } + } + loop_ub = I2->size[1]; + b_loop_ub = I2->size[2]; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &d_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[(I2->size[0] * i1 + I2->size[0] * I2->size[1] * i) + 2]; + } + } + b_I2[0] = 1; + b_I2[1] = I2->size[1]; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &c_I2->size[0], 3, &c_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[1] - 1; + loop_ub = I2->size[2] - 1; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &d_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[(I2->size[0] * i1 + I2->size[0] * I2->size[1] * i) + 2]; + } + } + loop_ub = c_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = c_I2->size[1]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[I2->size[0] * i1 + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + c_I2->size[1] * i]; + } + } + if (I2->size[0] < 1) { + emlrtDynamicBoundsCheckR2012b(I2->size[0], 1, I2->size[0], &e_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[0] - 2 < 1) || (I2->size[0] - 2 > I2->size[0])) { + emlrtDynamicBoundsCheckR2012b(I2->size[0] - 2, 1, I2->size[0], &d_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = I2->size[1]; + b_loop_ub = I2->size[2]; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &e_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[((I2->size[0] + I2->size[0] * i1) + + I2->size[0] * I2->size[1] * i) - + 3]; + } + } + b_I2[0] = 1; + b_I2[1] = I2->size[1]; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &c_I2->size[0], 3, &d_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[1] - 1; + loop_ub = I2->size[2] - 1; + d_I2 = I2->size[0] - 1; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &e_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[((I2->size[0] + I2->size[0] * i1) + + I2->size[0] * I2->size[1] * i) - + 3]; + } + } + loop_ub = c_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = c_I2->size[1]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(d_I2 + I2->size[0] * i1) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + c_I2->size[1] * i]; + } + } + if ((I2->size[0] - 1 < 1) || (I2->size[0] - 1 > I2->size[0])) { + emlrtDynamicBoundsCheckR2012b(I2->size[0] - 1, 1, I2->size[0], &g_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[0] - 2 < 1) || (I2->size[0] - 2 > I2->size[0])) { + emlrtDynamicBoundsCheckR2012b(I2->size[0] - 2, 1, I2->size[0], &f_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = I2->size[1]; + b_loop_ub = I2->size[2]; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &f_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[((I2->size[0] + I2->size[0] * i1) + + I2->size[0] * I2->size[1] * i) - + 3]; + } + } + b_I2[0] = 1; + b_I2[1] = I2->size[1]; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &c_I2->size[0], 3, &e_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[1] - 1; + loop_ub = I2->size[2] - 1; + d_I2 = I2->size[0] - 2; + i = c_I2->size[0] * c_I2->size[1] * c_I2->size[2]; + c_I2->size[0] = 1; + c_I2->size[1] = I2->size[1]; + c_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, c_I2, i, &f_emlrtRTEI); + b_I2_data = c_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + c_I2->size[1] * i] = + I2_data[((I2->size[0] + I2->size[0] * i1) + + I2->size[0] * I2->size[1] * i) - + 3]; + } + } + loop_ub = c_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = c_I2->size[1]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(d_I2 + I2->size[0] * i1) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + c_I2->size[1] * i]; + } + } + emxFree_real_T(sp, &c_I2); + emxInit_real_T(sp, &e_I2, 3, &g_emlrtRTEI); + loop_ub = I2->size[0]; + b_loop_ub = I2->size[2]; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &g_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * 2) + I2->size[0] * I2->size[1] * i]; + } + } + b_I2[0] = I2->size[0]; + b_I2[1] = 1; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &e_I2->size[0], 3, &f_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[2] - 1; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &g_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * 2) + I2->size[0] * I2->size[1] * i]; + } + } + loop_ub = e_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = e_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[i1 + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + e_I2->size[0] * i]; + } + } + loop_ub = I2->size[0]; + b_loop_ub = I2->size[2]; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &h_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * 2) + I2->size[0] * I2->size[1] * i]; + } + } + b_I2[0] = I2->size[0]; + b_I2[1] = 1; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &e_I2->size[0], 3, &g_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[2] - 1; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &h_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * 2) + I2->size[0] * I2->size[1] * i]; + } + } + loop_ub = e_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = e_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0]) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + e_I2->size[0] * i]; + } + } + if (I2->size[1] < 1) { + emlrtDynamicBoundsCheckR2012b(I2->size[1], 1, I2->size[1], &i_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[1] - 2 < 1) || (I2->size[1] - 2 > I2->size[1])) { + emlrtDynamicBoundsCheckR2012b(I2->size[1] - 2, 1, I2->size[1], &h_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = I2->size[0]; + b_loop_ub = I2->size[2]; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &i_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * (I2->size[1] - 3)) + + I2->size[0] * I2->size[1] * i]; + } + } + b_I2[0] = I2->size[0]; + b_I2[1] = 1; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &e_I2->size[0], 3, &h_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[2] - 1; + d_I2 = I2->size[1] - 1; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &i_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * (I2->size[1] - 3)) + + I2->size[0] * I2->size[1] * i]; + } + } + loop_ub = e_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = e_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * d_I2) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + e_I2->size[0] * i]; + } + } + if ((I2->size[1] - 1 < 1) || (I2->size[1] - 1 > I2->size[1])) { + emlrtDynamicBoundsCheckR2012b(I2->size[1] - 1, 1, I2->size[1], &k_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[1] - 2 < 1) || (I2->size[1] - 2 > I2->size[1])) { + emlrtDynamicBoundsCheckR2012b(I2->size[1] - 2, 1, I2->size[1], &j_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = I2->size[0]; + b_loop_ub = I2->size[2]; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &j_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i < b_loop_ub; i++) { + for (i1 = 0; i1 < loop_ub; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * (I2->size[1] - 3)) + + I2->size[0] * I2->size[1] * i]; + } + } + b_I2[0] = I2->size[0]; + b_I2[1] = 1; + b_I2[2] = I2->size[2]; + emlrtSubAssignSizeCheckR2012b(&b_I2[0], 3, &e_I2->size[0], 3, &i_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[2] - 1; + d_I2 = I2->size[1] - 2; + i = e_I2->size[0] * e_I2->size[1] * e_I2->size[2]; + e_I2->size[0] = I2->size[0]; + e_I2->size[1] = 1; + e_I2->size[2] = I2->size[2]; + emxEnsureCapacity_real_T(sp, e_I2, i, &j_emlrtRTEI); + b_I2_data = e_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + e_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * (I2->size[1] - 3)) + + I2->size[0] * I2->size[1] * i]; + } + } + loop_ub = e_I2->size[2]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = e_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * d_I2) + I2->size[0] * I2->size[1] * i] = + b_I2_data[i1 + e_I2->size[0] * i]; + } + } + emxFree_real_T(sp, &e_I2); + emxInit_real_T(sp, &f_I2, 2, &k_emlrtRTEI); + g_I2[0] = I2->size[0]; + g_I2[1] = I2->size[1]; + iv[0] = I2->size[0]; + iv[1] = I2->size[1]; + emlrtSubAssignSizeCheckR2012b(&g_I2[0], 2, &iv[0], 2, &j_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[1] - 1; + i = f_I2->size[0] * f_I2->size[1]; + f_I2->size[0] = I2->size[0]; + f_I2->size[1] = I2->size[1]; + emxEnsureCapacity_real_T(sp, f_I2, i, &k_emlrtRTEI); + b_I2_data = f_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + f_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1] * 2]; + } + } + loop_ub = f_I2->size[1]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = f_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[i1 + I2->size[0] * i] = b_I2_data[i1 + f_I2->size[0] * i]; + } + } + g_I2[0] = I2->size[0]; + g_I2[1] = I2->size[1]; + iv[0] = I2->size[0]; + iv[1] = I2->size[1]; + emlrtSubAssignSizeCheckR2012b(&g_I2[0], 2, &iv[0], 2, &k_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[1] - 1; + i = f_I2->size[0] * f_I2->size[1]; + f_I2->size[0] = I2->size[0]; + f_I2->size[1] = I2->size[1]; + emxEnsureCapacity_real_T(sp, f_I2, i, &l_emlrtRTEI); + b_I2_data = f_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + f_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1] * 2]; + } + } + loop_ub = f_I2->size[1]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = f_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1]] = + b_I2_data[i1 + f_I2->size[0] * i]; + } + } + if (I2->size[2] < 1) { + emlrtDynamicBoundsCheckR2012b(I2->size[2], 1, I2->size[2], &m_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[2] - 2 < 1) || (I2->size[2] - 2 > I2->size[2])) { + emlrtDynamicBoundsCheckR2012b(I2->size[2] - 2, 1, I2->size[2], &l_emlrtBCI, + (emlrtCTX)sp); + } + g_I2[0] = I2->size[0]; + g_I2[1] = I2->size[1]; + iv[0] = I2->size[0]; + iv[1] = I2->size[1]; + emlrtSubAssignSizeCheckR2012b(&g_I2[0], 2, &iv[0], 2, &l_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[1] - 1; + d_I2 = I2->size[2] - 1; + i = f_I2->size[0] * f_I2->size[1]; + f_I2->size[0] = I2->size[0]; + f_I2->size[1] = I2->size[1]; + emxEnsureCapacity_real_T(sp, f_I2, i, &m_emlrtRTEI); + b_I2_data = f_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + f_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * i) + + I2->size[0] * I2->size[1] * (I2->size[2] - 3)]; + } + } + loop_ub = f_I2->size[1]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = f_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1] * d_I2] = + b_I2_data[i1 + f_I2->size[0] * i]; + } + } + if ((I2->size[2] - 1 < 1) || (I2->size[2] - 1 > I2->size[2])) { + emlrtDynamicBoundsCheckR2012b(I2->size[2] - 1, 1, I2->size[2], &o_emlrtBCI, + (emlrtCTX)sp); + } + if ((I2->size[2] - 2 < 1) || (I2->size[2] - 2 > I2->size[2])) { + emlrtDynamicBoundsCheckR2012b(I2->size[2] - 2, 1, I2->size[2], &n_emlrtBCI, + (emlrtCTX)sp); + } + g_I2[0] = I2->size[0]; + g_I2[1] = I2->size[1]; + iv[0] = I2->size[0]; + iv[1] = I2->size[1]; + emlrtSubAssignSizeCheckR2012b(&g_I2[0], 2, &iv[0], 2, &m_emlrtECI, + (emlrtCTX)sp); + Wt3_tmp = I2->size[0] - 1; + loop_ub = I2->size[1] - 1; + d_I2 = I2->size[2] - 2; + i = f_I2->size[0] * f_I2->size[1]; + f_I2->size[0] = I2->size[0]; + f_I2->size[1] = I2->size[1]; + emxEnsureCapacity_real_T(sp, f_I2, i, &n_emlrtRTEI); + b_I2_data = f_I2->data; + for (i = 0; i <= loop_ub; i++) { + for (i1 = 0; i1 <= Wt3_tmp; i1++) { + b_I2_data[i1 + f_I2->size[0] * i] = + I2_data[(i1 + I2->size[0] * i) + + I2->size[0] * I2->size[1] * (I2->size[2] - 3)]; + } + } + loop_ub = f_I2->size[1]; + for (i = 0; i < loop_ub; i++) { + b_loop_ub = f_I2->size[0]; + for (i1 = 0; i1 < b_loop_ub; i1++) { + I2_data[(i1 + I2->size[0] * i) + I2->size[0] * I2->size[1] * d_I2] = + b_I2_data[i1 + f_I2->size[0] * i]; + } + } + emxFree_real_T(sp, &f_I2); + /* clear I2; */ + for (b_i = 0; b_i < newdim_idx_0; b_i++) { + for (b_loop_ub = 0; b_loop_ub < newdim_idx_1; b_loop_ub++) { + for (k = 0; k < newdim_idx_2; k++) { + real_T A[125]; + i = 2 * b_i; + i1 = 2 * b_loop_ub; + i2 = 2 * k; + for (i3 = 0; i3 < 5; i3++) { + i4 = (int32_T)(((real_T)i2 + ((real_T)i3 + -2.0)) + 3.0); + for (i5 = 0; i5 < 5; i5++) { + Wt3_tmp = (int32_T)(((real_T)i1 + ((real_T)i5 + -2.0)) + 3.0); + for (i6 = 0; i6 < 5; i6++) { + d_I2 = (int32_T)(((real_T)i + ((real_T)i6 + -2.0)) + 3.0); + if ((d_I2 < 1) || (d_I2 > I2->size[0])) { + emlrtDynamicBoundsCheckR2012b(d_I2, 1, I2->size[0], &p_emlrtBCI, + (emlrtCTX)sp); + } + if ((Wt3_tmp < 1) || (Wt3_tmp > I2->size[1])) { + emlrtDynamicBoundsCheckR2012b(Wt3_tmp, 1, I2->size[1], + &q_emlrtBCI, (emlrtCTX)sp); + } + if ((i4 < 1) || (i4 > I2->size[2])) { + emlrtDynamicBoundsCheckR2012b(i4, 1, I2->size[2], &r_emlrtBCI, + (emlrtCTX)sp); + } + loop_ub = (i6 + 5 * i5) + 25 * i3; + A[loop_ub] = I2_data[((d_I2 + I2->size[0] * (Wt3_tmp - 1)) + + I2->size[0] * I2->size[1] * (i4 - 1)) - + 1] * + Wt3[loop_ub]; + } + } + } + if (b_i + 1 > IResult->size[0]) { + emlrtDynamicBoundsCheckR2012b(b_i + 1, 1, IResult->size[0], + &s_emlrtBCI, (emlrtCTX)sp); + } + if (b_loop_ub + 1 > IResult->size[1]) { + emlrtDynamicBoundsCheckR2012b(b_loop_ub + 1, 1, IResult->size[1], + &t_emlrtBCI, (emlrtCTX)sp); + } + if (k + 1 > IResult->size[2]) { + emlrtDynamicBoundsCheckR2012b(k + 1, 1, IResult->size[2], &u_emlrtBCI, + (emlrtCTX)sp); + } + IResult_data[(b_i + IResult->size[0] * b_loop_ub) + + IResult->size[0] * IResult->size[1] * k] = sumColumnB(A); + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + if (*emlrtBreakCheckR2012bFlagVar != 0) { + emlrtBreakCheckR2012b((emlrtCTX)sp); + } + } + emxFree_real_T(sp, &I2); + emlrtHeapReferenceStackLeaveFcnR2012b((emlrtCTX)sp); +} + +/* End of code generation (GPReduce.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce.h b/TBM/GP/codegen/mex/GPReduce/GPReduce.h new file mode 100644 index 0000000..a37d88b --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce.h @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce.h + * + * Code generation for function 'GPReduce' + * + */ + +#pragma once + +/* Include files */ +#include "GPReduce_types.h" +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPReduce(const emlrtStack *sp, const emxArray_real_T *b_I, + emxArray_real_T *IResult); + +/* End of code generation (GPReduce.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce.map b/TBM/GP/codegen/mex/GPReduce/GPReduce.map new file mode 100644 index 0000000..13de52b --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce.map @@ -0,0 +1,10 @@ +_mexFunction +_mexfilerequiredapiversion +_emlrtMexFcnProperties +_GPReduce +_GPReduce_initialize +_GPReduce_terminate +_GPReduce_atexit +_emxFree_real_T +_emxInit_real_T +_emxEnsureCapacity_real_T diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce.mexmaci64 b/TBM/GP/codegen/mex/GPReduce/GPReduce.mexmaci64 new file mode 100644 index 0000000..e2b51a2 Binary files /dev/null and b/TBM/GP/codegen/mex/GPReduce/GPReduce.mexmaci64 differ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_data.c b/TBM/GP/codegen/mex/GPReduce/GPReduce_data.c new file mode 100644 index 0000000..702556c --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_data.c @@ -0,0 +1,33 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_data.c + * + * Code generation for function 'GPReduce_data' + * + */ + +/* Include files */ +#include "GPReduce_data.h" +#include "rt_nonfinite.h" + +/* Variable Definitions */ +emlrtCTX emlrtRootTLSGlobal = NULL; + +const volatile char_T *emlrtBreakCheckR2012bFlagVar = NULL; + +emlrtContext emlrtContextGlobal = { + true, /* bFirstTime */ + false, /* bInitialized */ + 131626U, /* fVersionInfo */ + NULL, /* fErrorFunction */ + "GPReduce", /* fFunctionName */ + NULL, /* fRTCallStack */ + false, /* bDebugMode */ + {2045744189U, 2170104910U, 2743257031U, 4284093946U}, /* fSigWrd */ + NULL /* fSigMem */ +}; + +/* End of code generation (GPReduce_data.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_data.h b/TBM/GP/codegen/mex/GPReduce/GPReduce_data.h new file mode 100644 index 0000000..96879fe --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_data.h @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_data.h + * + * Code generation for function 'GPReduce_data' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Variable Declarations */ +extern emlrtCTX emlrtRootTLSGlobal; +extern const volatile char_T *emlrtBreakCheckR2012bFlagVar; +extern emlrtContext emlrtContextGlobal; + +/* End of code generation (GPReduce_data.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_emxutil.c b/TBM/GP/codegen/mex/GPReduce/GPReduce_emxutil.c new file mode 100644 index 0000000..43e67c0 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_emxutil.c @@ -0,0 +1,101 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_emxutil.c + * + * Code generation for function 'GPReduce_emxutil' + * + */ + +/* Include files */ +#include "GPReduce_emxutil.h" +#include "GPReduce_types.h" +#include "rt_nonfinite.h" +#include + +/* Function Definitions */ +void emxEnsureCapacity_real_T(const emlrtStack *sp, emxArray_real_T *emxArray, + int32_T oldNumel, const emlrtRTEInfo *srcLocation) +{ + int32_T i; + int32_T newNumel; + void *newData; + if (oldNumel < 0) { + oldNumel = 0; + } + newNumel = 1; + for (i = 0; i < emxArray->numDimensions; i++) { + newNumel = (int32_T)emlrtSizeMulR2012b((size_t)(uint32_T)newNumel, + (size_t)(uint32_T)emxArray->size[i], + srcLocation, (emlrtCTX)sp); + } + if (newNumel > emxArray->allocatedSize) { + i = emxArray->allocatedSize; + if (i < 16) { + i = 16; + } + while (i < newNumel) { + if (i > 1073741823) { + i = MAX_int32_T; + } else { + i *= 2; + } + } + newData = emlrtCallocMex((uint32_T)i, sizeof(real_T)); + if (newData == NULL) { + emlrtHeapAllocationErrorR2012b(srcLocation, (emlrtCTX)sp); + } + if (emxArray->data != NULL) { + memcpy(newData, emxArray->data, sizeof(real_T) * oldNumel); + if (emxArray->canFreeData) { + emlrtFreeMex(emxArray->data); + } + } + emxArray->data = (real_T *)newData; + emxArray->allocatedSize = i; + emxArray->canFreeData = true; + } +} + +void emxFree_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray) +{ + if (*pEmxArray != (emxArray_real_T *)NULL) { + if (((*pEmxArray)->data != (real_T *)NULL) && (*pEmxArray)->canFreeData) { + emlrtFreeMex((*pEmxArray)->data); + } + emlrtFreeMex((*pEmxArray)->size); + emlrtRemoveHeapReference((emlrtCTX)sp, (void *)pEmxArray); + emlrtFreeEmxArray(*pEmxArray); + *pEmxArray = (emxArray_real_T *)NULL; + } +} + +void emxInit_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray, + int32_T numDimensions, const emlrtRTEInfo *srcLocation) +{ + emxArray_real_T *emxArray; + int32_T i; + *pEmxArray = (emxArray_real_T *)emlrtMallocEmxArray(sizeof(emxArray_real_T)); + if ((void *)*pEmxArray == NULL) { + emlrtHeapAllocationErrorR2012b(srcLocation, (emlrtCTX)sp); + } + emlrtPushHeapReferenceStackEmxArray((emlrtCTX)sp, true, (void *)pEmxArray, + (void *)&emxFree_real_T, NULL, NULL, + NULL); + emxArray = *pEmxArray; + emxArray->data = (real_T *)NULL; + emxArray->numDimensions = numDimensions; + emxArray->size = (int32_T *)emlrtMallocMex(sizeof(int32_T) * numDimensions); + if ((void *)emxArray->size == NULL) { + emlrtHeapAllocationErrorR2012b(srcLocation, (emlrtCTX)sp); + } + emxArray->allocatedSize = 0; + emxArray->canFreeData = true; + for (i = 0; i < numDimensions; i++) { + emxArray->size[i] = 0; + } +} + +/* End of code generation (GPReduce_emxutil.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_emxutil.h b/TBM/GP/codegen/mex/GPReduce/GPReduce_emxutil.h new file mode 100644 index 0000000..b9c361a --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_emxutil.h @@ -0,0 +1,34 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_emxutil.h + * + * Code generation for function 'GPReduce_emxutil' + * + */ + +#pragma once + +/* Include files */ +#include "GPReduce_types.h" +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void emxEnsureCapacity_real_T(const emlrtStack *sp, emxArray_real_T *emxArray, + int32_T oldNumel, + const emlrtRTEInfo *srcLocation); + +void emxFree_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray); + +void emxInit_real_T(const emlrtStack *sp, emxArray_real_T **pEmxArray, + int32_T numDimensions, const emlrtRTEInfo *srcLocation); + +/* End of code generation (GPReduce_emxutil.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_initialize.c b/TBM/GP/codegen/mex/GPReduce/GPReduce_initialize.c new file mode 100644 index 0000000..d811ee1 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_initialize.c @@ -0,0 +1,35 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_initialize.c + * + * Code generation for function 'GPReduce_initialize' + * + */ + +/* Include files */ +#include "GPReduce_initialize.h" +#include "GPReduce_data.h" +#include "_coder_GPReduce_mex.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void GPReduce_initialize(void) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + mex_InitInfAndNan(); + mexFunctionCreateRootTLS(); + emlrtBreakCheckR2012bFlagVar = emlrtGetBreakCheckFlagAddressR2012b(); + st.tls = emlrtRootTLSGlobal; + emlrtClearAllocCountR2012b(&st, false, 0U, NULL); + emlrtEnterRtStackR2012b(&st); + emlrtFirstTimeR2012b(emlrtRootTLSGlobal); +} + +/* End of code generation (GPReduce_initialize.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_initialize.h b/TBM/GP/codegen/mex/GPReduce/GPReduce_initialize.h new file mode 100644 index 0000000..43e122f --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_initialize.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_initialize.h + * + * Code generation for function 'GPReduce_initialize' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPReduce_initialize(void); + +/* End of code generation (GPReduce_initialize.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_internal_types.h b/TBM/GP/codegen/mex/GPReduce/GPReduce_internal_types.h new file mode 100644 index 0000000..a1b9c40 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_internal_types.h @@ -0,0 +1,30 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_internal_types.h + * + * Code generation for function 'GPReduce' + * + */ + +#pragma once + +/* Include files */ +#include "GPReduce_types.h" +#include "rtwtypes.h" +#include "emlrt.h" + +/* Type Definitions */ +#ifndef typedef_rtDesignRangeCheckInfo +#define typedef_rtDesignRangeCheckInfo +typedef struct { + int32_T lineNo; + int32_T colNo; + const char_T *fName; + const char_T *pName; +} rtDesignRangeCheckInfo; +#endif /* typedef_rtDesignRangeCheckInfo */ + +/* End of code generation (GPReduce_internal_types.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_mex.sh b/TBM/GP/codegen/mex/GPReduce/GPReduce_mex.sh new file mode 100644 index 0000000..c62d48d --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_mex.sh @@ -0,0 +1,2 @@ +"/Applications/MATLAB_R2022a.app/toolbox/shared/coder/ninja/maci64/ninja" -t compdb cc cxx cudac > compile_commands.json +"/Applications/MATLAB_R2022a.app/toolbox/shared/coder/ninja/maci64/ninja" -v "$@" diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_terminate.c b/TBM/GP/codegen/mex/GPReduce/GPReduce_terminate.c new file mode 100644 index 0000000..7d27de1 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_terminate.c @@ -0,0 +1,46 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_terminate.c + * + * Code generation for function 'GPReduce_terminate' + * + */ + +/* Include files */ +#include "GPReduce_terminate.h" +#include "GPReduce_data.h" +#include "_coder_GPReduce_mex.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void GPReduce_atexit(void) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + mexFunctionCreateRootTLS(); + st.tls = emlrtRootTLSGlobal; + emlrtEnterRtStackR2012b(&st); + emlrtLeaveRtStackR2012b(&st); + emlrtDestroyRootTLS(&emlrtRootTLSGlobal); + emlrtExitTimeCleanup(&emlrtContextGlobal); +} + +void GPReduce_terminate(void) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + st.tls = emlrtRootTLSGlobal; + emlrtLeaveRtStackR2012b(&st); + emlrtDestroyRootTLS(&emlrtRootTLSGlobal); +} + +/* End of code generation (GPReduce_terminate.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_terminate.h b/TBM/GP/codegen/mex/GPReduce/GPReduce_terminate.h new file mode 100644 index 0000000..821e147 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_terminate.h @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_terminate.h + * + * Code generation for function 'GPReduce_terminate' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPReduce_atexit(void); + +void GPReduce_terminate(void); + +/* End of code generation (GPReduce_terminate.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/GPReduce_types.h b/TBM/GP/codegen/mex/GPReduce/GPReduce_types.h new file mode 100644 index 0000000..ddecbf8 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/GPReduce_types.h @@ -0,0 +1,34 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * GPReduce_types.h + * + * Code generation for function 'GPReduce' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" + +/* Type Definitions */ +#ifndef struct_emxArray_real_T +#define struct_emxArray_real_T +struct emxArray_real_T { + real_T *data; + int32_T *size; + int32_T allocatedSize; + int32_T numDimensions; + boolean_T canFreeData; +}; +#endif /* struct_emxArray_real_T */ +#ifndef typedef_emxArray_real_T +#define typedef_emxArray_real_T +typedef struct emxArray_real_T emxArray_real_T; +#endif /* typedef_emxArray_real_T */ + +/* End of code generation (GPReduce_types.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/_clang-format b/TBM/GP/codegen/mex/GPReduce/_clang-format new file mode 100644 index 0000000..55a16f7 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/_clang-format @@ -0,0 +1,27 @@ +BasedOnStyle: LLVM +Language: Cpp +IndentWidth: 2 +ColumnLimit: 80 +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +CommentPragmas: '^(Return Type|Arguments)\s*' +DeriveLineEnding : true +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + SplitEmptyFunction: true + SplitEmptyRecord: true diff --git a/TBM/GP/codegen/mex/GPReduce/build.ninja b/TBM/GP/codegen/mex/GPReduce/build.ninja new file mode 100644 index 0000000..438b446 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/build.ninja @@ -0,0 +1,50 @@ +# CompilerName=clang +# Mode=optim +ninja_required_version = 1.3 + +# Basic folders +root = . +builddir = $root/build/maci64 +matlabdir = /Applications/MATLAB_R2022a.app +startdir = /Users/natasha/Downloads/TBM_software/TBM/GP + +# Toolchain information +cc = /usr/bin/xcrun -sdk macosx12.3 clang +cxx = /usr/bin/xcrun -sdk macosx12.3 clang++ +linker = /usr/bin/xcrun -sdk macosx12.3 clang +linkerxx = /usr/bin/xcrun -sdk macosx12.3 clang++ + +cflags = -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I "$root" -I "$startdir" -I "$root/interface" -I "$matlabdir/extern/include" -I "." -DMODEL=GPReduce -c + +cxxflags = -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -fobjc-arc -std=c++11 -stdlib=libc++ -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c++11 -I "$root" -I "$startdir" -I "$root/interface" -I "$matlabdir/extern/include" -I "." -DMODEL=GPReduce -c + +ldflags = -Wl,-twolevel_namespace -undefined error -arch x86_64 -mmacosx-version-min=10.15 -Wl,-syslibroot,/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -bundle -L"$matlabdir/bin/maci64" -lmx -lmex -lmat -lc++ -Wl,-rpath,@loader_path -o GPReduce.mexmaci64 -lemlrt -lcovrt -lut -lmwmathutil -Wl,-exported_symbols_list,GPReduce.map + +# Build Rules +rule cc + command = $cc $cflags $in -o $out + +rule cxx + command = $cxx $cxxflags $in -o $out + +rule link + command = $linker $in $ldflags + +rule linkxx + command = $linkerxx $in $ldflags + +# Build +build $builddir/GPReduce_data.o : cc $root/GPReduce_data.c +build $builddir/rt_nonfinite.o : cc $root/rt_nonfinite.c +build $builddir/GPReduce_initialize.o : cc $root/GPReduce_initialize.c +build $builddir/GPReduce_terminate.o : cc $root/GPReduce_terminate.c +build $builddir/GPReduce.o : cc $root/GPReduce.c +build $builddir/_coder_GPReduce_api.o : cc $root/interface/_coder_GPReduce_api.c +build $builddir/_coder_GPReduce_mex.o : cc $root/interface/_coder_GPReduce_mex.c +build $builddir/sumMatrixIncludeNaN.o : cc $root/sumMatrixIncludeNaN.c +build $builddir/GPReduce_emxutil.o : cc $root/GPReduce_emxutil.c +build $builddir/_coder_GPReduce_info.o : cc $root/interface/_coder_GPReduce_info.c +build $builddir/c_mexapi_version.o : cc $matlabdir/extern/version/c_mexapi_version.c + +# Link +build $root/GPReduce.mexmaci64 : link $builddir/GPReduce_data.o $builddir/rt_nonfinite.o $builddir/GPReduce_initialize.o $builddir/GPReduce_terminate.o $builddir/GPReduce.o $builddir/_coder_GPReduce_api.o $builddir/_coder_GPReduce_mex.o $builddir/sumMatrixIncludeNaN.o $builddir/GPReduce_emxutil.o $builddir/_coder_GPReduce_info.o $builddir/c_mexapi_version.o diff --git a/TBM/GP/codegen/mex/GPReduce/buildInfo.mat b/TBM/GP/codegen/mex/GPReduce/buildInfo.mat new file mode 100644 index 0000000..d78b574 Binary files /dev/null and b/TBM/GP/codegen/mex/GPReduce/buildInfo.mat differ diff --git a/TBM/GP/codegen/mex/GPReduce/compile_commands.json b/TBM/GP/codegen/mex/GPReduce/compile_commands.json new file mode 100644 index 0000000..b04649f --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/compile_commands.json @@ -0,0 +1,68 @@ +[ + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c GPReduce_data.c -o build/maci64/GPReduce_data.o", + "file": "GPReduce_data.c", + "output": "build/maci64/GPReduce_data.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c rt_nonfinite.c -o build/maci64/rt_nonfinite.o", + "file": "rt_nonfinite.c", + "output": "build/maci64/rt_nonfinite.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c GPReduce_initialize.c -o build/maci64/GPReduce_initialize.o", + "file": "GPReduce_initialize.c", + "output": "build/maci64/GPReduce_initialize.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c GPReduce_terminate.c -o build/maci64/GPReduce_terminate.o", + "file": "GPReduce_terminate.c", + "output": "build/maci64/GPReduce_terminate.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c GPReduce.c -o build/maci64/GPReduce.o", + "file": "GPReduce.c", + "output": "build/maci64/GPReduce.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c interface/_coder_GPReduce_api.c -o build/maci64/_coder_GPReduce_api.o", + "file": "interface/_coder_GPReduce_api.c", + "output": "build/maci64/_coder_GPReduce_api.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c interface/_coder_GPReduce_mex.c -o build/maci64/_coder_GPReduce_mex.o", + "file": "interface/_coder_GPReduce_mex.c", + "output": "build/maci64/_coder_GPReduce_mex.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c sumMatrixIncludeNaN.c -o build/maci64/sumMatrixIncludeNaN.o", + "file": "sumMatrixIncludeNaN.c", + "output": "build/maci64/sumMatrixIncludeNaN.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c GPReduce_emxutil.c -o build/maci64/GPReduce_emxutil.o", + "file": "GPReduce_emxutil.c", + "output": "build/maci64/GPReduce_emxutil.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c interface/_coder_GPReduce_info.c -o build/maci64/_coder_GPReduce_info.o", + "file": "interface/_coder_GPReduce_info.c", + "output": "build/maci64/_coder_GPReduce_info.o" + }, + { + "directory": "/Users/natasha/Downloads/TBM_software/TBM/GP/codegen/mex/GPReduce", + "command": "/usr/bin/xcrun -sdk macosx12.3 clang -fno-common -arch x86_64 -mmacosx-version-min=10.15 -fexceptions -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -DMATLAB_MEX_FILE -O2 -fwrapv -DNDEBUG -std=c99 -I \".\" -I \"/Users/natasha/Downloads/TBM_software/TBM/GP\" -I \"./interface\" -I \"/Applications/MATLAB_R2022a.app/extern/include\" -I \".\" -DMODEL=GPReduce -c /Applications/MATLAB_R2022a.app/extern/version/c_mexapi_version.c -o build/maci64/c_mexapi_version.o", + "file": "/Applications/MATLAB_R2022a.app/extern/version/c_mexapi_version.c", + "output": "build/maci64/c_mexapi_version.o" + } +] diff --git a/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_api.c b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_api.c new file mode 100644 index 0000000..745267e --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_api.c @@ -0,0 +1,124 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPReduce_api.c + * + * Code generation for function '_coder_GPReduce_api' + * + */ + +/* Include files */ +#include "_coder_GPReduce_api.h" +#include "GPReduce.h" +#include "GPReduce_data.h" +#include "GPReduce_emxutil.h" +#include "GPReduce_types.h" +#include "rt_nonfinite.h" + +/* Variable Definitions */ +static emlrtRTEInfo o_emlrtRTEI = { + 1, /* lineNo */ + 1, /* colNo */ + "_coder_GPReduce_api", /* fName */ + "" /* pName */ +}; + +/* Function Declarations */ +static void b_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, + const emlrtMsgIdentifier *parentId, + emxArray_real_T *y); + +static void c_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, + const emlrtMsgIdentifier *msgId, + emxArray_real_T *ret); + +static void emlrt_marshallIn(const emlrtStack *sp, const mxArray *b_I, + const char_T *identifier, emxArray_real_T *y); + +static const mxArray *emlrt_marshallOut(const emxArray_real_T *u); + +/* Function Definitions */ +static void b_emlrt_marshallIn(const emlrtStack *sp, const mxArray *u, + const emlrtMsgIdentifier *parentId, + emxArray_real_T *y) +{ + c_emlrt_marshallIn(sp, emlrtAlias(u), parentId, y); + emlrtDestroyArray(&u); +} + +static void c_emlrt_marshallIn(const emlrtStack *sp, const mxArray *src, + const emlrtMsgIdentifier *msgId, + emxArray_real_T *ret) +{ + static const int32_T dims[3] = {-1, -1, -1}; + int32_T iv[3]; + int32_T i; + const boolean_T bv[3] = {true, true, true}; + emlrtCheckVsBuiltInR2012b((emlrtCTX)sp, msgId, src, (const char_T *)"double", + false, 3U, (void *)&dims[0], &bv[0], &iv[0]); + ret->allocatedSize = iv[0] * iv[1] * iv[2]; + i = ret->size[0] * ret->size[1] * ret->size[2]; + ret->size[0] = iv[0]; + ret->size[1] = iv[1]; + ret->size[2] = iv[2]; + emxEnsureCapacity_real_T(sp, ret, i, (emlrtRTEInfo *)NULL); + ret->data = (real_T *)emlrtMxGetData(src); + ret->canFreeData = false; + emlrtDestroyArray(&src); +} + +static void emlrt_marshallIn(const emlrtStack *sp, const mxArray *b_I, + const char_T *identifier, emxArray_real_T *y) +{ + emlrtMsgIdentifier thisId; + thisId.fIdentifier = (const char_T *)identifier; + thisId.fParent = NULL; + thisId.bParentIsCell = false; + b_emlrt_marshallIn(sp, emlrtAlias(b_I), &thisId, y); + emlrtDestroyArray(&b_I); +} + +static const mxArray *emlrt_marshallOut(const emxArray_real_T *u) +{ + static const int32_T iv[3] = {0, 0, 0}; + const mxArray *m; + const mxArray *y; + const real_T *u_data; + u_data = u->data; + y = NULL; + m = emlrtCreateNumericArray(3, (const void *)&iv[0], mxDOUBLE_CLASS, mxREAL); + emlrtMxSetData((mxArray *)m, (void *)&u_data[0]); + emlrtSetDimensions((mxArray *)m, &u->size[0], 3); + emlrtAssign(&y, m); + return y; +} + +void GPReduce_api(const mxArray *prhs, const mxArray **plhs) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + emxArray_real_T *IResult; + emxArray_real_T *b_I; + st.tls = emlrtRootTLSGlobal; + emlrtHeapReferenceStackEnterFcnR2012b(&st); + emxInit_real_T(&st, &b_I, 3, &o_emlrtRTEI); + emxInit_real_T(&st, &IResult, 3, &o_emlrtRTEI); + /* Marshall function inputs */ + b_I->canFreeData = false; + emlrt_marshallIn(&st, emlrtAlias(prhs), "I", b_I); + /* Invoke the target function */ + GPReduce(&st, b_I, IResult); + /* Marshall function outputs */ + IResult->canFreeData = false; + *plhs = emlrt_marshallOut(IResult); + emxFree_real_T(&st, &IResult); + emxFree_real_T(&st, &b_I); + emlrtHeapReferenceStackLeaveFcnR2012b(&st); +} + +/* End of code generation (_coder_GPReduce_api.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_api.h b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_api.h new file mode 100644 index 0000000..744fc9b --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_api.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPReduce_api.h + * + * Code generation for function '_coder_GPReduce_api' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPReduce_api(const mxArray *prhs, const mxArray **plhs); + +/* End of code generation (_coder_GPReduce_api.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_info.c b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_info.c new file mode 100644 index 0000000..90e6906 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_info.c @@ -0,0 +1,73 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPReduce_info.c + * + * Code generation for function 'GPReduce' + * + */ + +/* Include files */ +#include "_coder_GPReduce_info.h" +#include "emlrt.h" +#include "tmwtypes.h" + +/* Function Declarations */ +static const mxArray *emlrtMexFcnResolvedFunctionsInfo(void); + +/* Function Definitions */ +static const mxArray *emlrtMexFcnResolvedFunctionsInfo(void) +{ + static const int32_T iv[2] = {0, 1}; + const mxArray *m; + const mxArray *nameCaptureInfo; + nameCaptureInfo = NULL; + m = emlrtCreateNumericArray(2, (const void *)&iv[0], mxDOUBLE_CLASS, mxREAL); + emlrtAssign(&nameCaptureInfo, m); + return nameCaptureInfo; +} + +mxArray *emlrtMexFcnProperties(void) +{ + mxArray *xEntryPoints; + mxArray *xInputs; + mxArray *xResult; + const char_T *epFieldName[6] = { + "Name", "NumberOfInputs", "NumberOfOutputs", + "ConstantInputs", "FullPath", "TimeStamp"}; + const char_T *propFieldName[6] = {"Version", "ResolvedFunctions", + "Checksum", "EntryPoints", + "CoverageInfo", "IsPolymorphic"}; + xEntryPoints = + emlrtCreateStructMatrix(1, 1, 6, (const char_T **)&epFieldName[0]); + xInputs = emlrtCreateLogicalMatrix(1, 1); + emlrtSetField(xEntryPoints, 0, (const char_T *)"Name", + emlrtMxCreateString((const char_T *)"GPReduce")); + emlrtSetField(xEntryPoints, 0, (const char_T *)"NumberOfInputs", + emlrtMxCreateDoubleScalar(1.0)); + emlrtSetField(xEntryPoints, 0, (const char_T *)"NumberOfOutputs", + emlrtMxCreateDoubleScalar(1.0)); + emlrtSetField(xEntryPoints, 0, (const char_T *)"ConstantInputs", xInputs); + emlrtSetField( + xEntryPoints, 0, (const char_T *)"FullPath", + emlrtMxCreateString( + (const char_T + *)"/Users/natasha/Downloads/TBM_software/TBM/GP/GPReduce.m")); + emlrtSetField(xEntryPoints, 0, (const char_T *)"TimeStamp", + emlrtMxCreateDoubleScalar(736524.36027777777)); + xResult = + emlrtCreateStructMatrix(1, 1, 6, (const char_T **)&propFieldName[0]); + emlrtSetField( + xResult, 0, (const char_T *)"Version", + emlrtMxCreateString((const char_T *)"9.12.0.2009381 (R2022a) Update 4")); + emlrtSetField(xResult, 0, (const char_T *)"ResolvedFunctions", + (mxArray *)emlrtMexFcnResolvedFunctionsInfo()); + emlrtSetField(xResult, 0, (const char_T *)"Checksum", + emlrtMxCreateString((const char_T *)"UZNV6GSDjNHqUjgyPa3PcG")); + emlrtSetField(xResult, 0, (const char_T *)"EntryPoints", xEntryPoints); + return xResult; +} + +/* End of code generation (_coder_GPReduce_info.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_info.h b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_info.h new file mode 100644 index 0000000..4130c01 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_info.h @@ -0,0 +1,20 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPReduce_info.h + * + * Code generation for function 'GPReduce' + * + */ + +#pragma once + +/* Include files */ +#include "mex.h" + +/* Function Declarations */ +MEXFUNCTION_LINKAGE mxArray *emlrtMexFcnProperties(void); + +/* End of code generation (_coder_GPReduce_info.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_mex.c b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_mex.c new file mode 100644 index 0000000..15a1b08 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_mex.c @@ -0,0 +1,65 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPReduce_mex.c + * + * Code generation for function '_coder_GPReduce_mex' + * + */ + +/* Include files */ +#include "_coder_GPReduce_mex.h" +#include "GPReduce_data.h" +#include "GPReduce_initialize.h" +#include "GPReduce_terminate.h" +#include "_coder_GPReduce_api.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +void GPReduce_mexFunction(int32_T nlhs, mxArray *plhs[1], int32_T nrhs, + const mxArray *prhs[1]) +{ + emlrtStack st = { + NULL, /* site */ + NULL, /* tls */ + NULL /* prev */ + }; + const mxArray *outputs; + st.tls = emlrtRootTLSGlobal; + /* Check for proper number of arguments. */ + if (nrhs != 1) { + emlrtErrMsgIdAndTxt(&st, "EMLRT:runTime:WrongNumberOfInputs", 5, 12, 1, 4, + 8, "GPReduce"); + } + if (nlhs > 1) { + emlrtErrMsgIdAndTxt(&st, "EMLRT:runTime:TooManyOutputArguments", 3, 4, 8, + "GPReduce"); + } + /* Call the function. */ + GPReduce_api(prhs[0], &outputs); + /* Copy over outputs to the caller. */ + emlrtReturnArrays(1, &plhs[0], &outputs); +} + +void mexFunction(int32_T nlhs, mxArray *plhs[], int32_T nrhs, + const mxArray *prhs[]) +{ + mexAtExit(&GPReduce_atexit); + /* Module initialization. */ + GPReduce_initialize(); + /* Dispatch the entry-point. */ + GPReduce_mexFunction(nlhs, plhs, nrhs, prhs); + /* Module termination. */ + GPReduce_terminate(); +} + +emlrtCTX mexFunctionCreateRootTLS(void) +{ + emlrtCreateRootTLSR2022a(&emlrtRootTLSGlobal, &emlrtContextGlobal, NULL, 1, + NULL, (const char_T *)"UTF-8", true); + return emlrtRootTLSGlobal; +} + +/* End of code generation (_coder_GPReduce_mex.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_mex.h b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_mex.h new file mode 100644 index 0000000..1d6b807 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/interface/_coder_GPReduce_mex.h @@ -0,0 +1,32 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * _coder_GPReduce_mex.h + * + * Code generation for function '_coder_GPReduce_mex' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +void GPReduce_mexFunction(int32_T nlhs, mxArray *plhs[1], int32_T nrhs, + const mxArray *prhs[1]); + +MEXFUNCTION_LINKAGE void mexFunction(int32_T nlhs, mxArray *plhs[], + int32_T nrhs, const mxArray *prhs[]); + +emlrtCTX mexFunctionCreateRootTLS(void); + +/* End of code generation (_coder_GPReduce_mex.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/rt_nonfinite.c b/TBM/GP/codegen/mex/GPReduce/rt_nonfinite.c new file mode 100644 index 0000000..03ebd8b --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/rt_nonfinite.c @@ -0,0 +1,32 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * rt_nonfinite.c + * + * Code generation for function 'GPReduce' + * + */ + +/* Include files */ +#include "rt_nonfinite.h" +#include "matrix.h" + +real_T mex_rtInf; +real_T mex_rtMinusInf; +real_T mex_rtNaN; +real32_T mex_rtInfF; +real32_T mex_rtMinusInfF; +real32_T mex_rtNaNF; + +void mex_InitInfAndNan(void) +{ + mex_rtInf = mxGetInf(); + mex_rtMinusInf = -rtInf; + mex_rtInfF = (real32_T)rtInf; + mex_rtMinusInfF = -rtInfF; + mex_rtNaN = mxGetNaN(); + mex_rtNaNF = (real32_T)rtNaN; +} +/* End of code generation (rt_nonfinite.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/rt_nonfinite.h b/TBM/GP/codegen/mex/GPReduce/rt_nonfinite.h new file mode 100644 index 0000000..16d7d5b --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/rt_nonfinite.h @@ -0,0 +1,38 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * rt_nonfinite.h + * + * Code generation for function 'GPReduce' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "tmwtypes.h" + +extern real_T mex_rtInf; +extern real_T mex_rtMinusInf; +extern real_T mex_rtNaN; +extern real32_T mex_rtInfF; +extern real32_T mex_rtMinusInfF; +extern real32_T mex_rtNaNF; + +#define rtInf mex_rtInf +#define rtMinusInf mex_rtMinusInf +#define rtNaN mex_rtNaN +#define rtInfF mex_rtInfF +#define rtMinusInfF mex_rtMinusInfF +#define rtNaNF mex_rtNaNF +#define rtIsNaN(X) mxIsNaN(X) +#define rtIsInf(X) mxIsInf(X) +#define rtIsNaNF(X) mxIsNaN(X) +#define rtIsInfF(X) mxIsInf(X) + +extern void mex_InitInfAndNan(void); + +/* End of code generation (rt_nonfinite.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/rtwtypes.h b/TBM/GP/codegen/mex/GPReduce/rtwtypes.h new file mode 100644 index 0000000..c707b38 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/rtwtypes.h @@ -0,0 +1,27 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * rtwtypes.h + * + * Code generation for function 'GPReduce' + * + */ + +#pragma once + +/* Include files */ +#include "tmwtypes.h" + +/* + * TRUE/FALSE definitions + */ +#ifndef TRUE +#define TRUE (1U) +#endif +#ifndef FALSE +#define FALSE (0U) +#endif + +/* End of code generation (rtwtypes.h) */ diff --git a/TBM/GP/codegen/mex/GPReduce/sumMatrixIncludeNaN.c b/TBM/GP/codegen/mex/GPReduce/sumMatrixIncludeNaN.c new file mode 100644 index 0000000..a347098 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/sumMatrixIncludeNaN.c @@ -0,0 +1,28 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * sumMatrixIncludeNaN.c + * + * Code generation for function 'sumMatrixIncludeNaN' + * + */ + +/* Include files */ +#include "sumMatrixIncludeNaN.h" +#include "rt_nonfinite.h" + +/* Function Definitions */ +real_T sumColumnB(const real_T x[125]) +{ + real_T y; + int32_T k; + y = x[0]; + for (k = 0; k < 124; k++) { + y += x[k + 1]; + } + return y; +} + +/* End of code generation (sumMatrixIncludeNaN.c) */ diff --git a/TBM/GP/codegen/mex/GPReduce/sumMatrixIncludeNaN.h b/TBM/GP/codegen/mex/GPReduce/sumMatrixIncludeNaN.h new file mode 100644 index 0000000..fc2c603 --- /dev/null +++ b/TBM/GP/codegen/mex/GPReduce/sumMatrixIncludeNaN.h @@ -0,0 +1,26 @@ +/* + * Academic License - for use in teaching, academic research, and meeting + * course requirements at degree granting institutions only. Not for + * government, commercial, or other organizational use. + * + * sumMatrixIncludeNaN.h + * + * Code generation for function 'sumMatrixIncludeNaN' + * + */ + +#pragma once + +/* Include files */ +#include "rtwtypes.h" +#include "emlrt.h" +#include "mex.h" +#include +#include +#include +#include + +/* Function Declarations */ +real_T sumColumnB(const real_T x[125]); + +/* End of code generation (sumMatrixIncludeNaN.h) */ diff --git a/TBM/Installation.m b/TBM/Installation.m new file mode 100644 index 0000000..655e99d --- /dev/null +++ b/TBM/Installation.m @@ -0,0 +1,14 @@ +%Shinjini Kundu (c) 2016 +%Installation file for Transport-Based Morphometry + +%Go to the GP file in the TBM folder and run these lines of code +codegen GPReduce -args {coder.typeof(1,[Inf Inf Inf],[1 1 1])} -o GPReduce +codegen GPExpand -args {coder.typeof(1,[Inf Inf Inf],[1 1 1]), zeros(1,3)} -o GPExpand + +%Go to the DGradient file in the TBM folder and run this line of code + +%for windows and Mac: +mex -O DGradient.c + +%for Linux +mex -O CFLAGS="\$CFLAGS -std=c99" DGradient.c \ No newline at end of file diff --git a/TBM/Main.asv b/TBM/Main.asv new file mode 100644 index 0000000..4d8df51 --- /dev/null +++ b/TBM/Main.asv @@ -0,0 +1,372 @@ +clc +clear all %first make sure you complete the installation as instructed by installation.m +filename = ''; %input filename here +cd(filename); +addpath(strcat(filename,'TBM/Alternative_OT')); +addpath(strcat(filename,'TBM/DGradient')); +addpath(strcat(filename,'TBM/GP')); + + +%% 1. Load the preprocessed files and convert to matlab + +imagefolder = (strcat(filename,'')); %folder with nifti images, can be saved as '.nii.gz' or '.nii' +matfolder = (strcat(filename,'')); %folder to save matfiles +addpath(strcat(filename1, '/Load_nii/')) +a = dir(fullfile(imagefolder,'*.nii')); %can also read in '.nii.gz', just change the suffix +n = numel(a); +numfiles = length(a); +for i=1:numfiles + file = (strcat(imagefolder, a(i).name)); + nii = load_nii(file); %calls the load_nii function + [filepath,name,ext] = fileparts(file); + newname = strsplit(name, '.'); %stores the name of the original file + image = nii.img; + image(image<0)=0; %sets any negative pixels to 0 + image = image+0.1; %adds a small positive to background pixels, this helps the TBM + image = image./sum(image(:))*10^6; %normalize all the images so the total value of the pixels adds to 10^6 + disp(sum(image(:))) %sanity check + disp(min(image(:))) + save (strcat(matfolder, newname{1}, '.mat'), "image") %saves the .matfiles +end +%% Load the template and convert to matlab. +%You may also wish to threshold the template image to create sharp edges using thresh_template function +nii = load_nii(strcat(filename, '')); % load your template file. This is the euclidean mean of the images. +template = nii.img; +%template = thresh_template(template) use this to threshold the template +template(template<0)=0; +template = template+0.1; +template = template./sum(template(:))*10^6; %normalize the template using same method as above +disp(sum(template(:))) %sanity check +disp(min(template(:))) +save (strcat(filename, ''), "template") + +%% 2. Run TBM forward transformation and save the transport maps + % The multVOT function takes the following input parameters: (I0,I1,lambda,tot,sigma,numScales,level,gamma) + % Lambda is the tradeoff between minimizing MSE and curl, the recommended parameter is 50 + % Tot is the total sum of the pixel values. + % Sigma controls the smoothness of the image. Recommended parameter is 1 + % Recommended numScales is 3 or 4. + % Gamma penalizes the mass transport, recommended is 0.1. Making this larger can make it harder to converge. + % Ringing in the descent of curl and MSE is due to a step size that is too high. Look for the variable step_size and decrease it from 0.01 of a voxel to 0.005 of a voxel. + % The multVOT will have a hard time producing deformations at the edges of the image if they are too close to the border. Zero pad the images sufficiently to avoid problems with matching the edges. The tradeoff of low step size is time it takes to converge. + % If slow to converge, downsample the images. The ideal size is between 128 x 128 x 128 and 256 x 256 x 256. + % The default level of convergence is MSE= 2×10^(-4), which is indicated by the variable cutoff the VOT3D function. This can be changed if the match of the images is not satisfactory based on visual appearance. +matfolder = (strcat(filename,'')) %folder where you saved the matfiles +transportfolder = (strcat(filename,'')); %folder to save the transport maps +b = dir(fullfile(matfolder,'*.mat')); +n = numel(b); +numfiles1 = length(b); +for i=1:numfiles1 + file1 = (strcat(matfolder, b(i).name)) + [filepath,name,ext] = fileparts(file1) + newname = strsplit(name, '.') + template = load(strcat(filename,'')) + I0 = template.template; %I0 is the Euclidean mean template. You are computing the optimal transport distance from the template to each image. + source = load(file1) + I1 = source.image; %I1 is the segmented image + results = multVOT(double(I0),double(I1),50,10^6,1,4,0.25,0.1); %Apply 3D linear optimal transportation. + save(strcat(transportfolder, newname{1}, '.mat'), "results") %saving the results for each image +end +%% 3. Perform train:test split and concatenate transport maps +transportfolder = (strcat(filename,'')) +template = load(strcat(filename,'')); +I0 = template.template; +labels = load(strcat(filename, 'labels.mat')); %loading labels for pLDA classification analysis, these should be saved as 1 (disease), and -1 (no disease) +labels = labels.labels; +growth = load(strcat(filename, 'growth.mat')); %loading continuous y variable for CCA regression analysis. Comment out if not needed. +growth = growth.growth; +covariates = load(strcat(filename, 'covariates.mat')); %loading covariates if using demographic/clinical information +covariates = covariates.covariates; +[X,Y,Z] = meshgrid(1:size(I0,2),1:size(I0,1),1:size(I0,3)); +c = dir(fullfile(transportfolder,'*.mat')); +disp(c) +n = numel(c); +numfiles2 = length(c) +train = randsample(170, 103) %randomsampling enter the following: (total files, number for training) +a = 1 +b = 1 +n = 1 +m = 1 +for i=1:numfiles2 + file1 = (strcat(transportfolder, c(i).name)) + load(file1); + if any(train==i) + featurestrain(a,:) = single([results.f1(:)-X(:); results.f2(:)-Y(:); results.f3(:)-Z(:)]); %concatenating the transport maps of the images, subtracts the template from each transport map + labelstrain(n,:) = single(labels(i,:)) + growthtrain(n,:) = single(growth(i,:)) + covariatestrain(n,:) = single(covariates(i,:,:)) + a = a+1 + n = n+1 + elseif any(train~=1) + featurestest(b,:) = single([results.f1(:)-X(:); results.f2(:)-Y(:); results.f3(:)-Z(:)]); %concatenating the transport maps of the images, subtracts the template from each transport map + labelstest(m,:) = single(labels(i,:)) + growthtest(m,:) = single(growth(i,:)) + covariatestest(m,:) = single(covariates(i,:,:)) + m = m+1 + b = b+1 + end +end +%% 4. Run PCA to perform dimensionality reduction in the training and testing data +%If you are using demographic/clinical covariates, you need to save additional eigenvectors to the PCA_decomp code. See the function for more information. +%For subsequent regressions, you will need the following variables: Z96_train, Z96_test, A_mean, EIGENV1 +[Z96_train,Z96_test,A_mean,EIGENV, EIGENV1, Z_train,Z_test] = PCA_decomp(featurestrain, featurestest); +%If you are using demographic/clinical covariates these should be +%concatenated with Z96_train and Z96_test prior to subsequent regressions: +% Z96_train = [Z96_train, covariatestrain] +% Z96_test = [Z96_test, covariatestest] +%% 5. Run PLDA to perform classification +%Inputs: +% I0 is the template image +% Z96_train, Z96_test are the dimensionality reduced data matrices from PCA +% Labelstrain, labelstest are the labels (-1 or +1) +% A_mean is the mean of all feature vectors +% featurestrain are the original transport maps training data +% [] - leave blank to calculate the optimal alpha value +% EIGENV1 is the eigenvector matrix +%Outputs: +% sensstrain is training ROC curve X-axis +% specstrain is training ROC curve y-axis +% sensstest is testing ROC curve X-axis +% specstest is testing ROC curve y-axis +% projtest are the scores in the testing data - can be used to calculate +% AUROC +% projtrain are the scores in the training data +% sigmatest is the sigma value in the testing dataset +% sigmatrain is the sigma value in the training dataset +% specificitytest is the specificity in the testing dataset +% specificitytrain is the specificity in the training dataset +% sensitivitytest is the sensitivity in the testing dataset +% sensitivitytrain is the sensitivity in the training dataset +% accuracytest is the accuracy in the testing dataset +% accuracytrain is the accuracy in the training dataset +% v1 is the principal PLDA direction +% pvaluehisttest is the p-value for the separation of histogram means in the +% testing dataset +% pvaluehisttrain is the p-value for the separation of histogram means in the +% training dataset +% histdiseasetest is the histogram for the disease/true value in the testing dataset +% histcontroltest is the histogram for the control/false value in the testing dataset +% histdiseasetrain is the histogram for the disease/true value in the training dataset +% histcontroltrain is the histogram for the control/false value in the +% training dataset +[sensstrain, specstrain, sensstest, specstest, projtest, projtrain, sigmatest, sigmatrain, specificitytest, specificitytrain, sensitivitytest, sensitivitytrain, accuracytest, accuracytrain, v1, pvaluehisttest, pvaluehisttrain, histdiseasetest, histcontroltest, histdiseasetrain, histcontroltrain] = visualizePLDA2(I0, Z96_train, Z96_test, labelstrain, labelstest, A_mean, featurestrain, [], 1, EIGENV1) +%% 6. Create histogram plots +n_std = [-2 -1 0 1 2] +figure; +nb_disease = histfit2(histdiseasetest) +hold on; +nb_control = histfit1(histcontroltest) +nb = [nb_disease' nb_control']; +h_leg = legend('','','',''); % enter group names here +set(h_leg,'box','off'); +center =0; +ax = gca; +%xlim([n_std(1)*sigmatest,n_std(5)*sigmatest+center]) +ax.XTick = [n_std(1)*sigmatest + center,n_std(2)*sigmatest+ center,center,n_std(4)*sigmatest+center,n_std(5)*sigmatest+center]; +ax.XTickLabel = {strcat(num2str(n_std(1)),'\sigma'),strcat(num2str(n_std(2)),'\sigma'),'0',strcat(num2str(n_std(4)),'\sigma'),strcat(num2str(n_std(5)),'\sigma')}; +set(gca,'fontsize',14); +xlabel('Projection score') +ylabel('Probability density'); +set(gca, 'FontName','Arial'); + +%% 7. Creat ROC plots +figure; plot(1-sensstest, specstest,'LineWidth',3) +xlabel('1-Specificity (%)'); +ylabel('Sensitivity (%)'); +title('ROC Curve'); +set(gca,'FontName','Arial'); +set(gca,'FontSize',14); +xlim([-0.05 1]) +ylim([0 1.05]) +x = 0:0.1:1; y = x; +hold on; plot(x,y,'Color','k','linewidth',0.01,'linestyle','--'); +clear x y +%% 8. Run CCA to perform regression analysis against a continuous variable +%Inputs: +% Z96_train, Z96_test are the dimensionality reduced data matrices from PCA +% growthtrain, growthtest are the continous independent variables +% covariatestrain, covariatestest are co-variates/confounding variables +% to adjust for, these should be normalised and scaled from 0 to 1 before +% inclusion, this can be left [] if no covariates +%Outputs: +%results, containing +%y is the continuous variable for the training dataset +%z is the continuous variable for the testing dataset +%wcorr is the most correlated direction +%CC_train is the correlation co-efficient in the training dataset +%CC_test is the correlation co-efficient in the testing dataset +%train_inds is the number of training samples +%test_inds is the number of testing samples +% Xw_train is used for the regression plot for training data +% Xw_test is used for the regression plot for testing data +% lambda is the standard deviation for wcorr +% ptrain is the pvalue for the training data +% ptest is the pvalue for the testing data +[ results ] = Regression(Z96_train, Z96_test, growthtrain, growthtest, covariatestrain, covariatestest) + +%% 9. Create regression scatter plots +figure; +s = scatter(results.Xw_test, results.z,'filled'); %this can be changed to Xw_train and y for training data plots +hold on; +s.MarkerFaceAlpha = '0.5'; +s.MarkerEdgeColor = [0.8500 0.3250 0.0980] +s.MarkerFaceColor = [0.8500 0.3250 0.0980]; +hold on +set(gca,'FontSize',14); +set(gca,'FontName','Arial'); +xlabel({'Projection score'}); +ylabel({'\delta volume, mL'})%change ylabel according to continous variable +ylim([-20, 120])%change ylim to suit continous variable scale +set(gca,'XTick',[-2*results.lambda, -results.lambda, 0, results.lambda, 2*results.lambda]); +set(gca,'XTickLabel',[{'-2\sigma','-\sigma','0','\sigma','2\sigma'}]); +hold on; +coefficientstest = polyfit([results.Xw_test], [results.z],1); +line = coefficientstest(1).*[results.Xw_test] + coefficientstest(2); +hold on; +plot([results.Xw_test], line,'k','LineWidth',3); %line of best fit computed using all the data +%% 10. Reconstruct images using inverse transformation +% Inputs: +% I0 is the template image +% v1 is the principal PLDA direction, this can be substituted for wcorr for +% the CCA direction +% A_mean is the mean of all feature vectors +% sigmatrain is the sigma value in the training dataset, this can be +% substituted for wcorr for the CCA direction +% EIGENV1 is the eigenvector matrix +% Outputs: +% Generates 5 images in series with less to more likelihood of the discriminant tested (i.e. less and more hematoma expansion) the third image should be equivalent in +% appearance to I0 +% Images can be viewed in 3D using imshow3Dfull +clear image +n_std = [-2 -1 0 1 2]; +[M,N,K] = size(I0); +[X,Y,Z] = meshgrid(1:N, 1:M, 1:K); +V1 = zeros(3*M*N*K,1); +i = 1:size(EIGENV1,2); +V1 = real(V1 + EIGENV1*v1(i)); +V1 = V1/norm(V1); +fprintf('Now computing the images... \n'); +for i = 1:length(n_std) + n = n_std(i); + i + fprintf('the std dev of the PLDA dir in the feature space is %d \n', sigmatrain); + fprintf('the norm of the matrix V1 is %d \n', norm(V1)); + + disp = A_mean + n*sigmatrain*V1'; + + sz = size(disp,2)/3; + + u = reshape(disp(1:sz),M,N,K); + v = reshape(disp(sz+1:2*sz),M,N,K); + w = reshape(disp(2*sz+1:3*sz),M,N,K); + + f = double(X + u); + g = double(Y + v); + h = double(Z + w); + + fields{i,1} = u; + fields{i,2} = v; + fields{i,3} = w; + + [dfdx,dfdy,dfdz] = gradient(f); %compute Jacobian map + [dgdx,dgdy,dgdz] = gradient(g); + [dhdx,dhdy,dhdz] = gradient(h); + + %And Jacobian determinant |Du| + D = (dfdx.*dgdy.*dhdz + dfdy.*dgdz.*dhdx + dfdz.*dgdx.*dhdy - dfdx.*dgdz.*dhdy - dfdy.*dgdx.*dhdz - dgdy.*dhdx.*dfdz); %determinant + + image{i} = inpaint_nans3(griddata(double(f),double(g),double(h),double((I0./D)),double(X),double(Y),double(Z))); + image{i}(image{i}>max(I0(:))) = max(I0(:)); + image{i}(image{i}max(I0(:))) = max(I0(:)); + image{i}(image{i}= 0.96 + cutoff = i; + cutoff2 = i; %% add to i the number of demographic/clinical covariates i.e. if there are four co-variates cutoff2 = i+4; + break; + end +end + +for i = 1:cutoff2 + eigenv = EIGENV(:,i); %column vectors of EIGENV + EIGENV1(:,i) = eigenv; +end +for j = 1:cutoff + eigenv1 = EIGENV(:,j); + Z96_train(:,j) = A*eigenv1; + Z96_test(:,j) = B*eigenv1; +end +end + diff --git a/TBM/PLDA.m b/TBM/PLDA.m new file mode 100644 index 0000000..4f6af74 --- /dev/null +++ b/TBM/PLDA.m @@ -0,0 +1,52 @@ +function [ Vec,eigval ] = PLDA(Data,Labels,Alpha,nPLDA) +%Penalized LDA +% Detailed explanation goes here +%Input: +%Data = The data matrix each column represents one sample +%Labels= Labels corresponding the data matrix +%Alpha = The weight of PCA in (LDA+Alpha*PCA); +%nPLDA = Number of PLDA directions +%Output: +%PLDA: Vector of PLDA directions +% +%Author: Soheil Kolouri +%Date: 09/26/2012 +[nfeatures,nsamples]=size(Data); +if ~(exist('nPLDA')) + if nfeatures 1: #selects which segmentation to use if multi-segmented image\n", + " mask_1 = mask.new_image_like(mask_array)\n", + " masked_image = ants.mask_image(scan, mask_1, 2, binarize=False) #apply segmentation to the scan. Set binarize to true if you want a binary mask\n", + " scan = ants.threshold_image(scan, low_thresh=0, high_thresh=100, inval=1, outval=0, binary=False) #thresholds CT image to help skull stripping to work better. This is not necessary for MRI.\n", + " ants.image_write(masked_image, new_dir + study + '_Label.nii.gz') #writes masks and scan to new directory \n", + " ants.image_write(scan, new_dir + study + '.nii.gz')\n", + " else:\n", + " mask_1 = mask.new_image_like(mask_array)\n", + " masked_image = ants.mask_image(scan, mask_1, 1, binarize=False)\n", + " scan = ants.threshold_image(scan, low_thresh=0, high_thresh=100, inval=1, outval=0, binary=False)\n", + " ants.image_write(masked_image, new_dir + study + '_Label.nii.gz')\n", + " ants.image_write(scan, new_dir + study + '.nii.gz')\n", + " \n", + "call_files()\n", + "\n", + " \n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "625191cd", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "*.nii.gz\n", + "[]\n", + "0 files found. Examples: []\n" + ] + } + ], + "source": [ + "def skull_strip (): #loads scans and applies skull stripping. Download here: https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/\n", + " filename = retreive_filelist('nii.gz', new_dir, include_subfolders=False)\n", + " print(len(filename), ' files found. Examples: ', filename)\n", + " for file in filename:\n", + " study = file.split('/')[5].split('.')[0]\n", + " if not file.endswith('_Label.nii.gz'):\n", + " print(file)\n", + " mybet = fsl.BET() \n", + " result = mybet.run(in_file=file, out_file=new_dir + study + '.nii.gz', frac=0.1)\n", + "\n", + "skull_strip()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "fdf0c18c", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "*.nii.gz\n", + "[]\n", + "0 files found. Examples: []\n" + ] + } + ], + "source": [ + "def resize_volume(img): #downsamples image. Recommend 256 x 256 x 256\n", + " \n", + " desired_depth = 256\n", + " desired_width = 256\n", + " desired_height = 256\n", + "\n", + " current_depth = img.shape[0]\n", + " current_width = img.shape[1]\n", + " current_height = img.shape[2]\n", + " \n", + " depth = current_depth / desired_depth\n", + " width = current_width / desired_width\n", + " height = current_height / desired_height\n", + " \n", + " depth_factor = 1 / depth\n", + " width_factor = 1 / width\n", + " height_factor = 1 / height\n", + " \n", + " img = ndimage.zoom(img, (depth_factor, width_factor, height_factor), order=1)\n", + " return img\n", + "\n", + "def register_files ():\n", + " filename = retreive_filelist('nii.gz', home_dir, include_subfolders=False)\n", + " \n", + " print(len(filename), ' files found. Examples: ', filename)\n", + " for file in filename:\n", + " study = file.split('/')[7].split('.')[0]\n", + " mask = file.split('.')[0] + '_Label.nii.gz'\n", + " try:\n", + " scan = ants.image_read(file)\n", + " mask1 = ants.image_read(mask)\n", + " print('loading', file)\n", + " except:\n", + " print('unable to load', file)\n", + " continue\n", + " template = ants.image_read('') #loads population based template see https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3376197/\n", + " mytx = ants.registration(fixed=template, moving=scan, type_of_transform='SyN' ) #registers using Symmetric Normalization method\n", + " mywarpedimage = ants.apply_transforms( fixed=template, moving=scan,\n", + " transformlist=mytx['fwdtransforms'] )\n", + " mywarpedmask = ants.apply_transforms( fixed=template, moving=mask1,\n", + " transformlist=mytx['fwdtransforms'] )\n", + " mywarpedmasknp = mywarpedmask.numpy() \n", + " mywarpedmaskresize = resize_volume(mywarpedmasknp) #downsample image\n", + " mywarpedmaskants = ants.from_numpy(mywarpedmaskresize)\n", + " mywarpedimagenp = mywarpedimage.numpy()\n", + " mywarpedimageresize = resize_volume(mywarpedimagenp)\n", + " mywarpedimageants = ants.from_numpy(mywarpedimageresize)\n", + " print(mywarpedimageresize.shape)\n", + " ants.image_write(mywarpedimage, new_dir + study + '.nii.gz') #saves registered image\n", + " #ants.image_write(mywarpedimage, new_dir + study + '.tiff') #can also save as tiff files if desired\n", + " ants.image_write(mywarpedmask, new_dir + study + '_Label.nii.gz') #saves registered mask\n", + " #ants.image_write(mywarpedmask, new_dir + study + '_Label.tiff')\n", + " \n", + "register_files()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f0676249", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import sys\n", + "import copy\n", + "from tqdm import tqdm\n", + "import nibabel as nib\n", + "from nibabel.testing import data_path\n", + "\n", + "## Flip brain lesions across midline, code obtained from https://github.com/hokifung/3D-Brain-Midsagittal-Flip.\n", + "## Either choose a separate folder to save lesions on left side and flip to right or vice versa.\n", + "## All lesions should be on same hemisphere.\n", + "\n", + "supported_extensions = ('nii', 'gz', 'img', 'gii', 'mnc', 'mgh', 'REC')\n", + "\n", + "def MirrorVoxels(original_data):\n", + " for slice_number in range(0, int(original_data.shape[0] / 2)):\n", + " # Copy Data from Memory (Incase Numpy Uses Shallow Copy)\n", + " temporary_slice = copy.deepcopy(original_data[slice_number, :, :])\n", + " # Calculate Mirror Index\n", + " mirror_idx = original_data.shape[0] - 1 - slice_number\n", + " # Offset Additional 1 from Indexing\n", + " original_data[slice_number,:,:] = copy.deepcopy(original_data[mirror_idx,:,: ])\n", + " # Return Temporary Slice Data to Right Side\n", + " original_data[mirror_idx,:,:] = copy.deepcopy(temporary_slice)\n", + "\n", + "input_path = ''\n", + "output_path = ''\n", + "\n", + "files = os.listdir(path=input_path)\n", + "for nfile in tqdm(range(len(files))):\n", + " if files[nfile].lower().endswith(supported_extensions) == False: #sanity check\n", + " continue\n", + " output_name = output_path + \"/\" + files[nfile]\n", + " filepath = input_path + \"/\" + files[nfile]\n", + " main = nib.load(filepath)\n", + " header = main.header\n", + " main_data = main.get_fdata() \n", + " edited_data = copy.deepcopy(main_data)\n", + " MirrorVoxels(edited_data) \n", + " mirror = nib.Nifti1Image(edited_data, main.affine, main.header)\n", + " nib.save(mirror, output_name)\n", + " \n", + " #Announce\n", + " print(\"Completed : Files Exported to /{}\".format(output_path))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a0704e8a", + "metadata": {}, + "outputs": [], + "source": [ + "def smooth_masks(): #smooth the masks using SITK curvature flow \n", + " filename = retreive_filelist('nii.gz', new_dir, include_subfolders=False)\n", + " print(len(filename), ' files found. Examples: ', filename)\n", + " for file in filename:\n", + " study = file.split('/')[6].split('.')[0]\n", + " mask = file.split('.')[0] + '_Label.nii.gz'\n", + " try:\n", + " #scan = ants.image_read(file) #load files\n", + " mask = ants.image_read(mask) #load files\n", + " print('loading', file)\n", + " except:\n", + " print('unable to load', file)\n", + " continue\n", + " mask_array = mask.numpy() #convert to numpy \n", + " mask_array = sitk.GetImageFromArray(mask_array)\n", + " mask_array = sitk.CurvatureFlow(image1=mask_array,\n", + " timeStep=0.125,\n", + " numberOfIterations=5)\n", + " thresholdFilter = sitk.ThresholdImageFilter()\n", + " thresholdFilter.SetLower(0)\n", + " thresholdFilter.SetUpper(150)\n", + " thresholdFilter.SetOutsideValue(0)\n", + " mask_array = thresholdFilter.Execute(mask_array)\n", + " mask_array = sitk.GetArrayFromImage(mask_array)\n", + " img = nb.Nifti1Image(mask_array, affine=np.eye(4))\n", + " nb.save(img, file)\n", + "smooth_masks()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4f02757f", + "metadata": {}, + "outputs": [], + "source": [ + "home_dir = ''\n", + "new_dir = ''\n", + "\n", + "def mean_image (): #creates the euclidean mean template and reference scan to visualize\n", + " scans=[]\n", + " masks=[]\n", + " filename = retreive_filelist('nii.gz', new_dir, include_subfolders=False)\n", + " print(len(filename), ' files found. Examples: ', filename)\n", + " for file in filename:\n", + " study = file.split('/')[6].split('.')[0]\n", + " mask = file.split('.')[0] + '_Label.nii.gz'\n", + " try:\n", + " scan = ants.image_read(file)\n", + " mask = ants.image_read(mask)\n", + " print('loading', file)\n", + " except:\n", + " print('unable to load', file)\n", + " continue\n", + " mask_array = mask.numpy() #convert to numpy \n", + " scan_array = scan.numpy()\n", + " masks.append(mask_array)\n", + " scans.append(scan_array)\n", + " masks = np.concatenate(masks, axis=0).reshape(-1, 256, 256, 256) #concatenate the masks\n", + " scans = np.concatenate(scans, axis=0).reshape(-1, 256, 256, 256) #concatenate the scans\n", + " masksmean = np.mean(masks, axis=0)\n", + " scansmean = np.mean(scans, axis=0)\n", + " mean_mask = masksmean.T\n", + " mean_scan = scansmean.T\n", + " img = nb.Nifti1Image(masksmean, affine=np.eye(4))\n", + " nb.save(img, '...template256.nii') #save the template\n", + " img2 = nb.Nifti1Image(scansmean, affine=np.eye(4))\n", + " nb.save(img2, '...meanscan256.nii') #save the scan\n", + "mask_mean()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "104ca571", + "metadata": {}, + "outputs": [], + "source": [ + "home_dir = ''\n", + "new_dir = ''\n", + "\n", + "def crop(): #crops the images to desired size to remove excess blank space. You also need to crop the Euclidean mean template and the population mean template used for registration with same parameters and save these separately for later visualizations.\n", + " filename = retreive_filelist('nii.gz', new_dir, include_subfolders=False)\n", + " print(len(filename), ' files found. Examples: ', filename)\n", + " for file in filename:\n", + " study = file.split('/')[8].split('.')[0]\n", + " mask = file.split('.')[0] + '_Label.nii.gz'\n", + " reader = sitk.ImageFileReader() #loads the mask\n", + " reader.SetFileName(mask)\n", + " template = reader.Execute()\n", + " array_mask = sitk.GetArrayFromImage(mask) #converts to numpy format\n", + " print(array_mask.shape)\n", + " maskcrop = array_mask[90:200, 30:220, 50:160] #selects parameters for cropping [x, y, z]\n", + " print(maskcrop.shape)\n", + " maskcrop1 = sitk.GetImageFromArray(maskcrop) #converts back to image format\n", + " outputfile = (new_dir + study + '.nii')\n", + " print(outputfile)\n", + " sitk.WriteImage(maskcrop1, outputfile)\n", + "crop()\n", + " " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "base", + "language": "python", + "name": "base" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/TBM/Preprocessing/scalingtranslation.m b/TBM/Preprocessing/scalingtranslation.m new file mode 100644 index 0000000..0cbae27 --- /dev/null +++ b/TBM/Preprocessing/scalingtranslation.m @@ -0,0 +1,96 @@ +%% 1. translate template to center of image +clear all +filename = ''; %load filename +addpath('View images/') +matfolder = (strcat(filename,'')) %folder with the images saved as matfiles +cd(filename); +b = dir(fullfile(matfolder,'*.mat')); +n = numel(b); +numfiles1 = length(b); +template = load(strcat(filename,'template.mat')) %load the template image +template = template.image; +template = thresh_template(template); %threshold template to create sharp edges +templatebin = imbinarize(templatethresh); %binarize template +stats1 = regionprops3(templatebin, 'Centroid', 'Volume'); %find center of mass and volume of template +centroidt = stats1.Centroid; +volumet = stats1.Volume; +xdim = size(template, 1); +ydim = size(template, 2); +xdim = size(template, 3); +translationt = [centroidt(2)-xdim/2, centroidt(1)-ydim/2, centroidt(3)-zdim/2]; %generate translation vector to center of image, with reference to the image dimensions +translationt = translationt*-1 %invert translation vector +translationt = [translationt(2), translationt(1), translationt(3)] +translatedtemplate = imtranslate(template, translationt); %translate template +%imshow3D(translatedtemplate); %visualize the translated template +translatedtemplatebin = imtranslate(templatebin, translationt); +newcentroid = regionprops3(translatedtemplatebin, 'Centroid'); %find center of mass of template +newcentroid = newcentroid.Centroid; %sanity check +%% 2. translate images to center of template and scale +scaledtfolder = (strcat(filename, '')) %if you wish to save scaled and translated images +scaledfolder = (strcat(filename,'Scaledonly/')) %if you wish to save scaled only images +for i=1:numfiles1 + file1 = (strcat(matfolder, b(i).name)); + [filepath,name,ext] = fileparts(file1) + newname = strsplit(name, '.') + originalimage = load(file1); + originalimage = originalimage.image; + originalimagebin = imbinarize(originalimage); %binarize image + stats2 = regionprops3(originalimagebin, 'Centroid', 'Volume'); %find center of mass and volume of image + centroid = stats2.Centroid; + centroidi = centroid(1,:) + volume = stats2.Volume; + volumei = volume(1,1) + translationb = [centroidi(1)-newcentroid(1), centroidi(2)-newcentroid(2), centroidi(3)-newcentroid(3)];%generate translation vector to center of template, with reference to the template + translationi = translationb*-1 + translatedimage = imtranslate(originalimage, translationi); %translate image + %figure;imshow3D(translatedimage); %visualize the translated image + sf = (volumet/volumei); %define scale factor + sf = nthroot(sf, 3);%cube root because we are dealing with volume + resizedimage = imresize3(translatedimage, sf, 'linear'); %resize image + %figure;imshow3D(resizedimage);%show resized image + targetsize = size(translatedimage);%crop or pad the resized image to correct dimensions + resized = size(resizedimage) + if sf>=1 + win = centerCropWindow3d(size(resizedimage), targetsize); + scaled = imcrop3(resizedimage, win); + else + Xpadpr = floor((targetsize(1)-resized(1))/2); + Ypadpr = floor((targetsize(2)-resized(2))/2); + Zpadpr = floor((targetsize(3)-resized(3))/2); + Xpadpo = round((targetsize(1)-resized(1))/2); + Ypadpo = round((targetsize(2)-resized(2))/2); + Zpadpo = round((targetsize(3)-resized(3))/2); + scaled = padarray(resizedimage, [Xpadpr, Ypadpr, Zpadpr], 0, 'pre'); + scaled = padarray(scaled, [Xpadpo, Ypadpo, Zpadpo], 0, 'post'); + end + translatedback = imtranslate(scaled, translationb); %translate the image back to original coordinates + %figure;imshow3D(scaledcrop) + save(strcat(scaledtfolder, newname{1}, '.mat'), 'scaled', 'translationi', 'sf') %savescaledandtranslated + save(strcat(scaledfolder, newname{1}, '.mat'), 'translatedback', 'sf') %savescaledonly + clear 'scaled' 'translatedback' 'translatedimage' 'originalimage' +end +%% 3. translate images to center of template without scaling +translatedfolder = (strcat(filename,'')) %if you wish to save translated images only +matfolder = (strcat(filename,'')) %folder with the images saved as matfiles +template = load(strcat(filename,'template.mat')) %load the template image +template = template.image; +template = thresh_template(template); %threshold template to create sharp edges +templatebin = imbinarize(templatethresh); %binarize template +stats1 = regionprops3(templatebin, 'Centroid', 'Volume'); %find center of mass and volume of template +centroidt = stats1.Centroid; +for i=1:numfiles1 + file1 = (strcat(matfolder, b(i).name)); + [filepath,name,ext] = fileparts(file1) + newname = strsplit(name, '.') + originalimage = load(file1); + originalimage = originalimage.image; + originalimagebin = imbinarize(originalimage); %binarize image + stats2 = regionprops3(originalimagebin, 'Centroid', 'Volume'); %find center of mass and volume of image + centroid = stats2.Centroid; + centroidi = centroid(1,:) + translationb = [centroidi(1)-centroidt(1), centroidi(2)-centroidt(2), centroidi(3)-centroidt(3)];%generate translation vector to center of template, with reference to the template + translationi = translationb*-1 %invert translation vector + translatedimage = imtranslate(originalimage, translationi); + save(strcat(translatedfolder, newname{1}, '.mat'), 'translatedimage', 'translationi')%save translation + clear 'translatedimage' 'translationi' +end \ No newline at end of file diff --git a/TBM/Projection_metric.m b/TBM/Projection_metric.m new file mode 100644 index 0000000..30525e0 --- /dev/null +++ b/TBM/Projection_metric.m @@ -0,0 +1,26 @@ +function [ d ] = Projection_metric( A,B ) +%This function calculates the projection metric based on the principal +%angles between the columns of matrix A and B +%Input: +% A: Orthonormal matrix N*M +% B: Orthonormal matrix N*M +%Output: +% d: Distnace between column spaces of A and B +%Author: +% Soheil Kolouri, modified by Shinjini Kundu +%Date: +% 09/27/2012 + +[~,M] = size(A); +A = orth(double(A)); +B = orth(double(B)); +for i = 1:M + A(:,i) = A(:,i)/norm(A(:,i)); + B(:,i) = B(:,i)/norm(B(:,i)); +end +[~,S,~] = svd(A'*B); +costheta = diag(S); +d = sqrt(M-sum(costheta.^2)); + +end + diff --git a/TBM/Regression.m b/TBM/Regression.m new file mode 100644 index 0000000..fb2987b --- /dev/null +++ b/TBM/Regression.m @@ -0,0 +1,86 @@ +%Shinjini Kundu (c) 2016 +%Note: when using covariates, check to make sure that scaling of each +%column is in the same order of magnitude as the other columns. If not, +%must whiten the covariates matrix (column mean 0 and standard deviation 1) + +function [ results ] = Regression( matrixtrain, matrixtest, y, z, covariatestrain, covariatestest) +%Finds regression direction in the TBM space or image space that correlates +%most with the independent variable of interest. Code also can adjust to +%remove the effects of confounding variables +%inputs: matrixtrain Training data matrix, oriented NxD, where N is +% subjects (this is PCA-reduced +% data matrix). +% matrixtest Test data matrix, oriented NxD, where N is +% subjects (this is PCA-reduced +% data matrix). +% y independent variable in column matrix for +% training +% z independent variable in column matrix for +% testing +% covariatestrain matrices of confounding variables/covariates, oriented +% Nxd for training and testing +% covariatestest +%output: wcorr most correlated direction in the space +% lambda std of projection scores +% CC_train Pearson's correlation coefficient for +% training set +% CC_test Pearson's correlation coefficient for +% testing set +% scores projection scores +% train_inds indices used for training +% test_inds indices used for testing +% ptrain p value for training +% ptest pvalue for testing + + +Data = matrixtrain'; %orient matrix DxN +Datatest = matrixtest'; +num = size(Data,2); +numtest = size(Datatest,2); +vizaxis = 'y'; %determine whether you want to visualize brains acros the projection score(y) or independent variable(x) + + %create testing and training indices + train_inds = 1:num; %randomly select 70% of samples for training + test_inds = 1:numtest; + + if ~isempty(covariatestrain) + v = y - covariatestrain/(covariatestrain'*covariatestrain)*covariatestrain'*y; + z = z - covariatestest/(covariatestest'*covariatestest)*covariatestest'*z; + elseif isempty(covariatestrain) + v = y; + z = z; + end + + wcorr = Data(:,train_inds)*(v(train_inds)-mean(v(train_inds)))/sqrt((v(train_inds)-mean(v(train_inds)))'*Data(:,train_inds)'*Data(:,train_inds)*(v(train_inds)-mean(v(train_inds)))); + lambda = std(Data'*wcorr); + + + Xw_train=Data(:,train_inds)'*wcorr; %Projection of the dataset onto the most correlative direction + Xw_test=Datatest(:,test_inds)'*wcorr; + + scores(train_inds) = Xw_train; scores(test_inds) = Xw_test; + + + %Calculate the correlation coefficient + + [CC_train, ptrain] = corr(double(Xw_train),v(train_inds)); %computes Pearson's correlation coefficient + [CC_test, ptest] = corr(double(Xw_test),z(test_inds)); + + results.y = v; + results.z = z; + +results.wcorr = wcorr; +results.CC_train = CC_train; +results.CC_test = CC_test; +results.train_inds = train_inds; +results.test_inds = test_inds; +results.Xw_train = Xw_train; +results.Xw_test = Xw_test; +results.lambda = lambda; +results.ptrain = ptrain; +results.ptest = ptest; + + + + +end \ No newline at end of file diff --git a/TBM/histfit1.m b/TBM/histfit1.m new file mode 100644 index 0000000..7e08da8 --- /dev/null +++ b/TBM/histfit1.m @@ -0,0 +1,130 @@ +function h = histfit(varargin) +%HISTFIT Histogram with superimposed fitted normal density. +% HISTFIT(DATA,NBINS) plots a histogram of the values in the vector DATA, +% along with a normal density function with parameters estimated from the +% data. NBINS is the number of bars in the histogram. With one input +% argument, NBINS is set to the square root of the number of elements in +% DATA. +% +% HISTFIT(AX,...) plots into AX instead of GCA. +% +% HISTFIT(DATA,NBINS,DIST) plots a histogram with a density from the DIST +% distribution. DIST can take the following values: +% +% 'beta' Beta +% 'birnbaumsaunders' Birnbaum-Saunders +% 'exponential' Exponential +% 'extreme value' or 'ev' Extreme value +% 'gamma' Gamma +% 'generalized extreme value' 'gev' Generalized extreme value +% 'generalized pareto' or 'gp' Generalized Pareto (threshold 0) +% 'inverse gaussian' Inverse Gaussian +% 'logistic' Logistic +% 'loglogistic' Log logistic +% 'lognormal' Lognormal +% 'negative binomial' or 'nbin' Negative binomial +% 'nakagami' Nakagami +% 'normal' Normal +% 'poisson' Poisson +% 'rayleigh' Rayleigh +% 'rician' Rician +% 'tlocationscale' t location-scale +% 'weibull' or 'wbl' Weibull +% +% H = HISTFIT(...) returns a vector of handles to the plotted lines. +% H(1) is a handle to the histogram, H(2) is a handle to the density curve. + +% Copyright 1993-2020 The MathWorks, Inc. + +% Allow uipanel/figure input as the first argument (parent) +nin = nargin; +if isempty(varargin) + error(message('stats:histfit:VectorRequired')); +elseif isa(varargin{1},'matlab.graphics.axis.Axes') + ax = varargin{1}; + varargin = varargin(2:end); + nin = nin - 1; +else + ax = newplot; +end + +if nin > 2 % nin == 3, all params case + [~,nbins,dist] = varargin{:}; + dist = convertStringsToChars(dist); +elseif nin == 2 + dist=[];nbins = varargin{2}; +else + nbins=[];dist=[]; +end + +if nin <= 0 + error(message('stats:histfit:VectorRequired')); +end + +data = varargin{1}; +if ~isvector(data) + error(message('stats:histfit:VectorRequired')); +end + +data = data(:); +data(isnan(data)) = []; +n = numel(data); + +if nin<2 || isempty(nbins) % nin == 1, give nbins value + nbins = ceil(sqrt(n)); +elseif ~isscalar(nbins) || ~isnumeric(nbins) || ~isfinite(nbins) ... + || nbins~=round(nbins) || nbins<=0 + error(message('stats:histfit:BadNumBins')) +end + +% Fit distribution to data +if nin<3 || isempty(dist) % nin == 1 and nin == 2, give dist value + dist = 'normal'; +end +try + pd = fitdist(data,dist); +catch myException + if isequal(myException.identifier,'stats:ProbDistUnivParam:fit:NRequired') || ... + isequal(myException.identifier,'stats:binofit:InvalidN') + % Binomial is not allowed because we have no N parameter + error(message('stats:histfit:BadDistribution')) + else + % Pass along another other errors + throw(myException) + end +end + +% Find range for plotting +q = icdf(pd,[0.0013499 0.99865]); % three-sigma range for normal distribution +x = linspace(q(1),q(2)); +if ~pd.Support.iscontinuous + % For discrete distribution use only integers + x = round(x); + x(diff(x)==0) = []; +end + +% Do histogram calculations +[bincounts,binedges] = histcounts(data,nbins); +bincenters = binedges(1:end-1)+diff(binedges)/2; + +% Plot the histogram with no gap between bars. +%hh = bar(ax, bincenters,bincounts,1); + +% Normalize the density to match the total area of the histogram +binwidth = binedges(2)-binedges(1); % Finds the width of each bin +area = n * binwidth; +y = area * pdf(pd,x); + +y = y/sum(y(:)); +% Overlay the density +np = get(ax,'NextPlot'); +set(ax,'NextPlot','add'); +hh1 = plot(ax, x,y,'b-','LineWidth',2); +c = [0 0.4470 0.7410]; +data2 = fill(x, y, c, 'FaceAlpha',0.8) + +if nargout == 1 + h = [hh1]; +end + +set(ax,'NextPlot',np); diff --git a/TBM/histfit2.m b/TBM/histfit2.m new file mode 100644 index 0000000..e70b359 --- /dev/null +++ b/TBM/histfit2.m @@ -0,0 +1,128 @@ +function h = histfit(varargin) +%HISTFIT Histogram with superimposed fitted normal density. +% HISTFIT(DATA,NBINS) plots a histogram of the values in the vector DATA, +% along with a normal density function with parameters estimated from the +% data. NBINS is the number of bars in the histogram. With one input +% argument, NBINS is set to the square root of the number of elements in +% DATA. +% +% HISTFIT(AX,...) plots into AX instead of GCA. +% +% HISTFIT(DATA,NBINS,DIST) plots a histogram with a density from the DIST +% distribution. DIST can take the following values: +% +% 'beta' Beta +% 'birnbaumsaunders' Birnbaum-Saunders +% 'exponential' Exponential +% 'extreme value' or 'ev' Extreme value +% 'gamma' Gamma +% 'generalized extreme value' 'gev' Generalized extreme value +% 'generalized pareto' or 'gp' Generalized Pareto (threshold 0) +% 'inverse gaussian' Inverse Gaussian +% 'logistic' Logistic +% 'loglogistic' Log logistic +% 'lognormal' Lognormal +% 'negative binomial' or 'nbin' Negative binomial +% 'nakagami' Nakagami +% 'normal' Normal +% 'poisson' Poisson +% 'rayleigh' Rayleigh +% 'rician' Rician +% 'tlocationscale' t location-scale +% 'weibull' or 'wbl' Weibull +% +% H = HISTFIT(...) returns a vector of handles to the plotted lines. +% H(1) is a handle to the histogram, H(2) is a handle to the density curve. + +% Copyright 1993-2020 The MathWorks, Inc. + +% Allow uipanel/figure input as the first argument (parent) +nin = nargin; +if isempty(varargin) + error(message('stats:histfit:VectorRequired')); +elseif isa(varargin{1},'matlab.graphics.axis.Axes') + ax = varargin{1}; + varargin = varargin(2:end); + nin = nin - 1; +else + ax = newplot; +end + +if nin > 2 % nin == 3, all params case + [~,nbins,dist] = varargin{:}; + dist = convertStringsToChars(dist); +elseif nin == 2 + dist=[];nbins = varargin{2}; +else + nbins=[];dist=[]; +end + +if nin <= 0 + error(message('stats:histfit:VectorRequired')); +end + +data = varargin{1}; +if ~isvector(data) + error(message('stats:histfit:VectorRequired')); +end + +data = data(:); +data(isnan(data)) = []; +n = numel(data); + +if nin<2 || isempty(nbins) % nin == 1, give nbins value + nbins = ceil(sqrt(n)); +elseif ~isscalar(nbins) || ~isnumeric(nbins) || ~isfinite(nbins) ... + || nbins~=round(nbins) || nbins<=0 + error(message('stats:histfit:BadNumBins')) +end + +% Fit distribution to data +if nin<3 || isempty(dist) % nin == 1 and nin == 2, give dist value + dist = 'normal'; +end +try + pd = fitdist(data,dist); +catch myException + if isequal(myException.identifier,'stats:ProbDistUnivParam:fit:NRequired') || ... + isequal(myException.identifier,'stats:binofit:InvalidN') + % Binomial is not allowed because we have no N parameter + error(message('stats:histfit:BadDistribution')) + else + % Pass along another other errors + throw(myException) + end +end + +% Find range for plotting +q = icdf(pd,[0.0013499 0.99865]); % three-sigma range for normal distribution +x = linspace(q(1),q(2)); +if ~pd.Support.iscontinuous + % For discrete distribution use only integers + x = round(x); + x(diff(x)==0) = []; +end + +% Do histogram calculations +[bincounts,binedges] = histcounts(data,nbins); +bincenters = binedges(1:end-1)+diff(binedges)/2; + +% Plot the histogram with no gap between bars. +%hh = bar(ax, bincenters,bincounts,1); + +% Normalize the density to match the total area of the histogram +binwidth = binedges(2)-binedges(1); % Finds the width of each bin +area = n * binwidth; +y = area * pdf(pd,x); +y = y/sum(y(:)) +% Overlay the density +np = get(ax,'NextPlot'); +set(ax,'NextPlot','add'); +hh1 = plot(ax, x,y,'r-','LineWidth',2); +c = [0.8500 0.3250 0.0980]; +data1 = fill(x, y, c, 'FaceAlpha',0.8) +if nargout == 1 + h = [hh1]; +end + +set(ax,'NextPlot',np); \ No newline at end of file diff --git a/TBM/imshow3Dfull.m/imshow3Dfull.m b/TBM/imshow3Dfull.m/imshow3Dfull.m new file mode 100644 index 0000000..7cd19ba --- /dev/null +++ b/TBM/imshow3Dfull.m/imshow3Dfull.m @@ -0,0 +1,439 @@ +function imshow3Dfull( Img, disprange ) +%IMSHOW3DFULL displays 3D grayscale or RGB images from three perpendicular +%views (i.e. axial, sagittal, and coronal) in slice by slice fashion with +%mouse based slice browsing and window and level adjustment control. +% +% Usage: +% imshow3Dfull ( Image ) +% imshow3Dfull ( Image , [] ) +% imshow3Dfull ( Image , [LOW HIGH] ) +% +% Image: 3D image MxNxKxC (K slices of MxN images) C is either 1 +% (for grayscale images) or 3 (for RGB images) +% [LOW HIGH]: display range that controls the display intensity range of +% a grayscale image (default: the widest available range) +% +% Use the scroll bar or mouse scroll wheel to switch between slices. To +% adjust window and level values keep the mouse right button pressed and +% drag the mouse up and down (for level adjustment) or right and left (for +% window adjustment). Window and level adjustment control works only for +% grayscale images. +% +% Use 'A', 'S', and 'C' buttons to switch between axial, sagittal and +% coronal views, respectivelly. +% +% "Auto W/L" button adjust the window and level automatically +% +% While "Fine Tune" check box is checked the window/level adjustment gets +% 16 times less sensitive to mouse movement, to make it easier to control +% display intensity rang. +% +% Note: The sensitivity of mouse based window and level adjustment is set +% based on the user defined display intensity range; the wider the range +% the more sensitivity to mouse drag. +% +% +% Example +% -------- +% % Display an image (MRI example) +% load mri +% Image = squeeze(D); +% figure, +% imshow3Dfull(Image) +% +% % Display the image, adjust the display range +% figure, +% imshow3Dfull(Image,[20 100]); +% +% See also IMSHOW. + +% +% - Maysam Shahedi (mshahedi@gmail.com) +% - Released: 1.0.0 Date: 2013/04/15 +% - Revision: 1.1.0 Date: 2013/04/19 +% - Revision: 2.0.0 Date: 2014/08/05 +% - Revision: 2.5.0 Date: 2016/09/22 +% - Revision: 2.5.1 Date: 2018/10/29 +% + +sno = size(Img); % image size +sno_a = sno(3); % number of axial slices +S_a = round(sno_a/2); +sno_s = sno(2); % number of sagittal slices +S_s = round(sno_s/2); +sno_c = sno(1); % number of coronal slices +S_c = round(sno_c/2); +S = S_a; +sno = sno_a; + +global InitialCoord; + +MinV = 0; +MaxV = max(Img(:)); +LevV = (double( MaxV) + double(MinV)) / 2; +Win = double(MaxV) - double(MinV); +WLAdjCoe = (Win + 1)/1024; +FineTuneC = [1 1/16]; % Regular/Fine-tune mode coefficients + +if isa(Img,'uint8') + MaxV = uint8(Inf); + MinV = uint8(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'uint16') + MaxV = uint16(Inf); + MinV = uint16(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'uint32') + MaxV = uint32(Inf); + MinV = uint32(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'uint64') + MaxV = uint64(Inf); + MinV = uint64(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'int8') + MaxV = int8(Inf); + MinV = int8(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'int16') + MaxV = int16(Inf); + MinV = int16(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'int32') + MaxV = int32(Inf); + MinV = int32(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'int64') + MaxV = int64(Inf); + MinV = int64(-Inf); + LevV = (double( MaxV) + double(MinV)) / 2; + Win = double(MaxV) - double(MinV); + WLAdjCoe = (Win + 1)/1024; +elseif isa(Img,'logical') + MaxV = 0; + MinV = 1; + LevV =0.5; + Win = 1; + WLAdjCoe = 0.1; +end + +ImgAx = Img; +if verLessThan('matlab', '8') + ImgSg = flipdim(permute(Img, [3 1 2 4]),1); % Sagittal view image + ImgCr = flipdim(permute(Img, [3 2 1 4]),1); % Coronal view image +else + ImgSg = flip(permute(Img, [3 1 2 4]),1); % Sagittal view image + ImgCr = flip(permute(Img, [3 2 1 4]),1); % Coronal view image +end + +View = 'A'; + +SFntSz = 9; +LFntSz = 10; +WFntSz = 10; +VwFntSz = 10; +LVFntSz = 9; +WVFntSz = 9; +BtnSz = 10; +ChBxSz = 10; + +if (nargin < 2) + [Rmin Rmax] = WL2R(Win, LevV); +elseif numel(disprange) == 0 + [Rmin Rmax] = WL2R(Win, LevV); +else + LevV = (double(disprange(2)) + double(disprange(1))) / 2; + Win = double(disprange(2)) - double(disprange(1)); + WLAdjCoe = (Win + 1)/1024; + [Rmin Rmax] = WL2R(Win, LevV); +end + +clf +hdl_im = axes('position',[0,0.2,1,0.8]); +imshow(squeeze(Img(:,:,S,:)), [Rmin Rmax]) + +FigPos = get(gcf,'Position'); +S_Pos = [50 50 uint16(FigPos(3)-100)+1 20]; +Stxt_Pos = [50 70 uint16(FigPos(3)-100)+1 15]; +Wtxt_Pos = [20 20 60 20]; +Wval_Pos = [75 20 60 20]; +Ltxt_Pos = [140 20 45 20]; +Lval_Pos = [180 20 60 20]; +BtnStPnt = uint16(FigPos(3)-210)+1; +if BtnStPnt < 360 + BtnStPnt = 360; +end +Btn_Pos = [BtnStPnt 20 80 20]; +ChBx_Pos = [BtnStPnt+90 20 100 20]; +Vwtxt_Pos = [255 20 35 20]; +VAxBtn_Pos = [290 20 15 20]; +VSgBtn_Pos = [310 20 15 20]; +VCrBtn_Pos = [330 20 15 20]; + +if sno > 1 + shand = uicontrol('Style', 'slider','Min',1,'Max',sno,'Value',S,'SliderStep',[1/(sno-1) 10/(sno-1)],'Position', S_Pos,'Callback', {@SliceSlider, Img}); + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String',sprintf('Slice# %d / %d',S, sno), 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); +else + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String','2D image', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); +end +ltxthand = uicontrol('Style', 'text','Position', Ltxt_Pos,'String','Level: ', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', LFntSz); +wtxthand = uicontrol('Style', 'text','Position', Wtxt_Pos,'String','Window: ', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', WFntSz); +lvalhand = uicontrol('Style', 'edit','Position', Lval_Pos,'String',sprintf('%6.0f',LevV), 'BackgroundColor', [1 1 1], 'FontSize', LVFntSz,'Callback', @WinLevChanged); +wvalhand = uicontrol('Style', 'edit','Position', Wval_Pos,'String',sprintf('%6.0f',Win), 'BackgroundColor', [1 1 1], 'FontSize', WVFntSz,'Callback', @WinLevChanged); +Btnhand = uicontrol('Style', 'pushbutton','Position', Btn_Pos,'String','Auto W/L', 'FontSize', BtnSz, 'Callback' , @AutoAdjust); +ChBxhand = uicontrol('Style', 'checkbox','Position', ChBx_Pos,'String','Fine Tune', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', ChBxSz); +Vwtxthand = uicontrol('Style', 'text','Position', Vwtxt_Pos,'String','View: ', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', LFntSz); +VAxBtnhand = uicontrol('Style', 'pushbutton','Position', VAxBtn_Pos,'String','A', 'FontSize', BtnSz, 'Callback' , @AxialView); +VSgBtnhand = uicontrol('Style', 'pushbutton','Position', VSgBtn_Pos,'String','S', 'FontSize', BtnSz, 'Callback' , @SagittalView); +VCrBtnhand = uicontrol('Style', 'pushbutton','Position', VCrBtn_Pos,'String','C', 'FontSize', BtnSz, 'Callback' , @CoronalView); + +set (gcf, 'WindowScrollWheelFcn', @mouseScroll); +set (gcf, 'ButtonDownFcn', @mouseClick); +set(get(gca,'Children'),'ButtonDownFcn', @mouseClick); +set(gcf,'WindowButtonUpFcn', @mouseRelease) +set(gcf,'ResizeFcn', @figureResized) + + +% -=< Figure resize callback function >=- + function figureResized(object, eventdata) + FigPos = get(gcf,'Position'); + S_Pos = [50 45 uint16(FigPos(3)-100)+1 20]; + Stxt_Pos = [50 65 uint16(FigPos(3)-100)+1 15]; + BtnStPnt = uint16(FigPos(3)-210)+1; + if BtnStPnt < 360 + BtnStPnt = 360; + end + Btn_Pos = [BtnStPnt 20 80 20]; + ChBx_Pos = [BtnStPnt+90 20 100 20]; + if sno > 1 + set(shand,'Position', S_Pos); + end + set(stxthand,'Position', Stxt_Pos); + set(ltxthand,'Position', Ltxt_Pos); + set(wtxthand,'Position', Wtxt_Pos); + set(lvalhand,'Position', Lval_Pos); + set(wvalhand,'Position', Wval_Pos); + set(Btnhand,'Position', Btn_Pos); + set(ChBxhand,'Position', ChBx_Pos); + set(Vwtxthand,'Position', Vwtxt_Pos); + set(VAxBtnhand,'Position', VAxBtn_Pos); + set(VSgBtnhand,'Position', VSgBtn_Pos); + set(VCrBtnhand,'Position', VCrBtn_Pos); + end + +% -=< Slice slider callback function >=- + function SliceSlider (hObj,event, Img) + S = round(get(hObj,'Value')); + set(get(gca,'children'),'cdata',squeeze(Img(:,:,S,:))) + caxis([Rmin Rmax]) + if sno > 1 + set(stxthand, 'String', sprintf('Slice# %d / %d',S, sno)); + else + set(stxthand, 'String', '2D image'); + end + end + +% -=< Mouse scroll wheel callback function >=- + function mouseScroll (object, eventdata) + UPDN = eventdata.VerticalScrollCount; + S = S - UPDN; + if (S < 1) + S = 1; + elseif (S > sno) + S = sno; + end + if sno > 1 + set(shand,'Value',S); + set(stxthand, 'String', sprintf('Slice# %d / %d',S, sno)); + else + set(stxthand, 'String', '2D image'); + end + set(get(gca,'children'),'cdata',squeeze(Img(:,:,S,:))) + end + +% -=< Mouse button released callback function >=- + function mouseRelease (object,eventdata) + set(gcf, 'WindowButtonMotionFcn', '') + end + +% -=< Mouse click callback function >=- + function mouseClick (object, eventdata) + MouseStat = get(gcbf, 'SelectionType'); + if (MouseStat(1) == 'a') % RIGHT CLICK + InitialCoord = get(0,'PointerLocation'); + set(gcf, 'WindowButtonMotionFcn', @WinLevAdj); + end + end + +% -=< Window and level mouse adjustment >=- + function WinLevAdj(varargin) + PosDiff = get(0,'PointerLocation') - InitialCoord; + + Win = Win + PosDiff(1) * WLAdjCoe * FineTuneC(get(ChBxhand,'Value')+1); + LevV = LevV - PosDiff(2) * WLAdjCoe * FineTuneC(get(ChBxhand,'Value')+1); + if (Win < 1) + Win = 1; + end + + [Rmin, Rmax] = WL2R(Win,LevV); + caxis([Rmin, Rmax]) + set(lvalhand, 'String', sprintf('%6.0f',LevV)); + set(wvalhand, 'String', sprintf('%6.0f',Win)); + InitialCoord = get(0,'PointerLocation'); + end + +% -=< Window and level text adjustment >=- + function WinLevChanged(varargin) + + LevV = str2double(get(lvalhand, 'string')); + Win = str2double(get(wvalhand, 'string')); + if (Win < 1) + Win = 1; + end + + [Rmin, Rmax] = WL2R(Win,LevV); + caxis([Rmin, Rmax]) + end + +% -=< Window and level to range conversion >=- + function [Rmn Rmx] = WL2R(W,L) + Rmn = L - (W/2); + Rmx = L + (W/2); + if (Rmn >= Rmx) + Rmx = Rmn + 1; + end + end + +% -=< Window and level auto adjustment callback function >=- + function AutoAdjust(object,eventdata) + Win = double(max(Img(:))-min(Img(:))); + Win (Win < 1) = 1; + LevV = double(min(Img(:)) + (Win/2)); + [Rmin, Rmax] = WL2R(Win,LevV); + caxis([Rmin, Rmax]) + set(lvalhand, 'String', sprintf('%6.0f',LevV)); + set(wvalhand, 'String', sprintf('%6.0f',Win)); + end + +% -=< Axial view callback function >=- + function AxialView(object,eventdata) + if View == 'S' + S_s = S; + elseif View == 'C' + S_c = S; + end + View = 'A'; + + Img = ImgAx; + S = S_a; + sno = sno_a; + cla(hdl_im); + hdl_im = axes('position',[0,0.2,1,0.8]); + imshow(squeeze(Img(:,:,S,:)), [Rmin Rmax]) + + if sno > 1 + shand = uicontrol('Style', 'slider','Min',1,'Max',sno,'Value',S,'SliderStep',[1/(sno-1) 10/(sno-1)],'Position', S_Pos,'Callback', {@SliceSlider, Img}); + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String',sprintf('Slice# %d / %d',S, sno), 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); + else + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String','2D image', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); + end + + caxis([Rmin Rmax]) + if sno > 1 + set(stxthand, 'String', sprintf('Slice# %d / %d',S, sno)); + else + set(stxthand, 'String', '2D image'); + end + + set(get(gca,'children'),'cdata',squeeze(Img(:,:,S,:))) + set (gcf, 'ButtonDownFcn', @mouseClick); + set(get(gca,'Children'),'ButtonDownFcn', @mouseClick); + end + +% -=< Sagittal view callback function >=- + function SagittalView(object,eventdata) + if View == 'A' + S_a = S; + elseif View == 'C' + S_c = S; + end + View = 'S'; + + Img = ImgSg; + S = S_s; + sno = sno_s; + cla(hdl_im); + hdl_im = axes('position',[0,0.2,1,0.8]); + imshow(squeeze(Img(:,:,S,:)), [Rmin Rmax]) + + if sno > 1 + shand = uicontrol('Style', 'slider','Min',1,'Max',sno,'Value',S,'SliderStep',[1/(sno-1) 10/(sno-1)],'Position', S_Pos,'Callback', {@SliceSlider, Img}); + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String',sprintf('Slice# %d / %d',S, sno), 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); + else + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String','2D image', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); + end + + caxis([Rmin Rmax]) + if sno > 1 + set(stxthand, 'String', sprintf('Slice# %d / %d',S, sno)); + else + set(stxthand, 'String', '2D image'); + end + + set(get(gca,'children'),'cdata',squeeze(Img(:,:,S,:))) + set (gcf, 'ButtonDownFcn', @mouseClick); + set(get(gca,'Children'),'ButtonDownFcn', @mouseClick); + + end + +% -=< Coronal view callback function >=- + function CoronalView(object,eventdata) + if View == 'A' + S_a = S; + elseif View == 'S' + S_s = S; + end + View = 'C'; + + Img = ImgCr; + S = S_c; + sno = sno_c; + cla(hdl_im); + hdl_im = axes('position',[0,0.2,1,0.8]); + imshow(squeeze(Img(:,:,S,:)), [Rmin Rmax]) + + if sno > 1 + shand = uicontrol('Style', 'slider','Min',1,'Max',sno,'Value',S,'SliderStep',[1/(sno-1) 10/(sno-1)],'Position', S_Pos,'Callback', {@SliceSlider, Img}); + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String',sprintf('Slice# %d / %d',S, sno), 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); + else + stxthand = uicontrol('Style', 'text','Position', Stxt_Pos,'String','2D image', 'BackgroundColor', [0.8 0.8 0.8], 'FontSize', SFntSz); + end + + caxis([Rmin Rmax]) + if sno > 1 + set(stxthand, 'String', sprintf('Slice# %d / %d',S, sno)); + else + set(stxthand, 'String', '2D image'); + end + + set(get(gca,'children'),'cdata',squeeze(Img(:,:,S,:))) + set (gcf, 'ButtonDownFcn', @mouseClick); + set(get(gca,'Children'),'ButtonDownFcn', @mouseClick); + end + +end +% -=< Maysam Shahedi (mshahedi@gmail.com), September 22, 2016>=- \ No newline at end of file diff --git a/TBM/imshow3Dfull.m/license.txt b/TBM/imshow3Dfull.m/license.txt new file mode 100644 index 0000000..16883bc --- /dev/null +++ b/TBM/imshow3Dfull.m/license.txt @@ -0,0 +1,25 @@ +Copyright (c) 2016, Maysam Shahedi +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution +* Neither the name of University of Western Ontario nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/TBM/inpaint_nans3.m b/TBM/inpaint_nans3.m new file mode 100644 index 0000000..b61e2e3 --- /dev/null +++ b/TBM/inpaint_nans3.m @@ -0,0 +1 @@ +function B=inpaint_nans3(A,method) % INPAINT_NANS3: in-paints over nans in a 3-D array % usage: B=INPAINT_NANS3(A) % default method (0) % usage: B=INPAINT_NANS3(A,method) % specify method used % % Solves approximation to a boundary value problem to % interpolate and extrapolate holes in a 3-D array. % % Note that if the array is large, and there are many NaNs % to be filled in, this may take a long time, or run into % memory problems. % % arguments (input): % A - n1 x n2 x n3 array with some NaNs to be filled in % % method - (OPTIONAL) scalar numeric flag - specifies % which approach (or physical metaphor to use % for the interpolation.) All methods are capable % of extrapolation, some are better than others. % There are also speed differences, as well as % accuracy differences for smooth surfaces. % % method 0 uses a simple plate metaphor. % method 1 uses a spring metaphor. % % method == 0 --> (DEFAULT) Solves the Laplacian % equation over the set of nan elements in the % array. % Extrapolation behavior is roughly linear. % % method == 1 --+ Uses a spring metaphor. Assumes % springs (with a nominal length of zero) % connect each node with every neighbor % (horizontally, vertically and diagonally) % Since each node tries to be like its neighbors, % extrapolation is roughly a constant function where % this is consistent with the neighboring nodes. % % There are only two different methods in this code, % chosen as the most useful ones (IMHO) from my % original inpaint_nans code. % % % arguments (output): % B - n1xn2xn3 array with NaNs replaced % % % Example: % % A linear function of 3 independent variables, % % used to test whether inpainting will interpolate % % the missing elements correctly. % [x,y,z] = ndgrid(-10:10,-10:10,-10:10); % W = x + y + z; % % % Pick a set of distinct random elements to NaN out. % ind = unique(ceil(rand(3000,1)*numel(W))); % Wnan = W; % Wnan(ind) = NaN; % % % Do inpainting % Winp = inpaint_nans3(Wnan,0); % % % Show that the inpainted values are essentially % % within eps of the originals. % std(Winp(ind) - W(ind)) % ans = % 4.3806e-15 % % % See also: griddatan, inpaint_nans % % Author: John D'Errico % e-mail address: woodchips@rochester.rr.com % Release: 1 % Release date: 8/21/08 % Need to know which elements are NaN, and % what size is the array. Unroll A for the % inpainting, although inpainting will be done % fully in 3-d. NA = size(A); A = A(:); nt = prod(NA); k = isnan(A(:)); % list the nodes which are known, and which will % be interpolated nan_list=find(k); known_list=find(~k); % how many nans overall nan_count=length(nan_list); % convert NaN indices to (r,c) form % nan_list==find(k) are the unrolled (linear) indices % (row,column) form [n1,n2,n3]=ind2sub(NA,nan_list); % both forms of index for all the nan elements in one array: % column 1 == unrolled index % column 2 == index 1 % column 3 == index 2 % column 4 == index 3 nan_list=[nan_list,n1,n2,n3]; % supply default method if (nargin<2) || isempty(method) method = 0; elseif ~ismember(method,[0 1]) error 'If supplied, method must be one of: {0,1}.' end % alternative methods switch method case 0 % The same as method == 1, except only work on those % elements which are NaN, or at least touch a NaN. % horizontal and vertical neighbors only talks_to = [-1 0 0;1 0 0;0 -1 0;0 1 0;0 0 -1;0 0 1]; neighbors_list=identify_neighbors(NA,nan_list,talks_to); % list of all nodes we have identified all_list=[nan_list;neighbors_list]; % generate sparse array with second partials on row % variable for each element in either list, but only % for those nodes which have a row index > 1 or < n L = find((all_list(:,2) > 1) & (all_list(:,2) < NA(1))); nL=length(L); if nL>0 fda=sparse(repmat(all_list(L,1),1,3), ... repmat(all_list(L,1),1,3)+repmat([-1 0 1],nL,1), ... repmat([1 -2 1],nL,1),nt,nt); else fda=spalloc(nt,nt,size(all_list,1)*7); end % 2nd partials on column index L = find((all_list(:,3) > 1) & (all_list(:,3) < NA(2))); nL=length(L); if nL>0 fda=fda+sparse(repmat(all_list(L,1),1,3), ... repmat(all_list(L,1),1,3)+repmat([-NA(1) 0 NA(1)],nL,1), ... repmat([1 -2 1],nL,1),nt,nt); end % 2nd partials on third index L = find((all_list(:,4) > 1) & (all_list(:,4) < NA(3))); nL=length(L); if nL>0 ntimesm = NA(1)*NA(2); fda=fda+sparse(repmat(all_list(L,1),1,3), ... repmat(all_list(L,1),1,3)+repmat([-ntimesm 0 ntimesm],nL,1), ... repmat([1 -2 1],nL,1),nt,nt); end % eliminate knowns rhs=-fda(:,known_list)*A(known_list); k=find(any(fda(:,nan_list(:,1)),2)); % and solve... B=A; B(nan_list(:,1))=fda(k,nan_list(:,1))\rhs(k); case 1 % Spring analogy % interpolating operator. % list of all springs between a node and a horizontal % or vertical neighbor hv_list=[-1 -1 0 0;1 1 0 0;-NA(1) 0 -1 0;NA(1) 0 1 0; ... -NA(1)*NA(2) 0 0 -1;NA(1)*NA(2) 0 0 1]; hv_springs=[]; for i=1:size(hv_list,1) hvs=nan_list+repmat(hv_list(i,:),nan_count,1); k=(hvs(:,2)>=1) & (hvs(:,2)<=NA(1)) & ... (hvs(:,3)>=1) & (hvs(:,3)<=NA(2)) & ... (hvs(:,4)>=1) & (hvs(:,4)<=NA(3)); hv_springs=[hv_springs;[nan_list(k,1),hvs(k,1)]]; end % delete replicate springs hv_springs=unique(sort(hv_springs,2),'rows'); % build sparse matrix of connections nhv=size(hv_springs,1); springs=sparse(repmat((1:nhv)',1,2),hv_springs, ... repmat([1 -1],nhv,1),nhv,prod(NA)); % eliminate knowns rhs=-springs(:,known_list)*A(known_list); % and solve... B=A; B(nan_list(:,1))=springs(:,nan_list(:,1))\rhs; end % all done, make sure that B is the same shape as % A was when we came in. B=reshape(B,NA); % ==================================================== % end of main function % ==================================================== % ==================================================== % begin subfunctions % ==================================================== function neighbors_list=identify_neighbors(NA,nan_list,talks_to) % identify_neighbors: identifies all the neighbors of % those nodes in nan_list, not including the nans % themselves % % arguments (input): % NA - 1x3 vector = size(A), where A is the % array to be interpolated % nan_list - array - list of every nan element in A % nan_list(i,1) == linear index of i'th nan element % nan_list(i,2) == row index of i'th nan element % nan_list(i,3) == column index of i'th nan element % nan_list(i,4) == third index of i'th nan element % talks_to - px2 array - defines which nodes communicate % with each other, i.e., which nodes are neighbors. % % talks_to(i,1) - defines the offset in the row % dimension of a neighbor % talks_to(i,2) - defines the offset in the column % dimension of a neighbor % % For example, talks_to = [-1 0;0 -1;1 0;0 1] % means that each node talks only to its immediate % neighbors horizontally and vertically. % % arguments(output): % neighbors_list - array - list of all neighbors of % all the nodes in nan_list if ~isempty(nan_list) % use the definition of a neighbor in talks_to nan_count=size(nan_list,1); talk_count=size(talks_to,1); nn=zeros(nan_count*talk_count,3); j=[1,nan_count]; for i=1:talk_count nn(j(1):j(2),:)=nan_list(:,2:4) + ... repmat(talks_to(i,:),nan_count,1); j=j+nan_count; end % drop those nodes which fall outside the bounds of the % original array L = (nn(:,1)<1) | (nn(:,1)>NA(1)) | ... (nn(:,2)<1) | (nn(:,2)>NA(2)) | ... (nn(:,3)<1) | (nn(:,3)>NA(3)); nn(L,:)=[]; % form the same format 4 column array as nan_list neighbors_list=[sub2ind(NA,nn(:,1),nn(:,2),nn(:,3)),nn]; % delete replicates in the neighbors list neighbors_list=unique(neighbors_list,'rows'); % and delete those which are also in the list of NaNs. neighbors_list=setdiff(neighbors_list,nan_list,'rows'); else neighbors_list=[]; end \ No newline at end of file diff --git a/TBM/thresh_template.m b/TBM/thresh_template.m new file mode 100644 index 0000000..44b050d --- /dev/null +++ b/TBM/thresh_template.m @@ -0,0 +1,9 @@ +function[templatethresh] = thresh_template(template) +n_slices = size(template, 3); +for a=1:n_slices %threshold the template image to create sharp edges + t=template(:,:,a); + in=find(t<5); + t(in)=0; + templatethresh(:,:,a)=t; + templatethresh(templatethresh<5)=0; +end \ No newline at end of file diff --git a/TBM/visualizePLDA2.m b/TBM/visualizePLDA2.m new file mode 100644 index 0000000..87706d9 --- /dev/null +++ b/TBM/visualizePLDA2.m @@ -0,0 +1,208 @@ +%Shinjini Kundu (c) 2014 +%Discrimination of images by PLDA, visualization code + +function [sensstrain, specstrain, sensstest, specstest, projtest, projtrain, sigmatest, sigmatrain, specificitytest, specificitytrain, sensitivitytest, sensitivitytrain, accuracytest, accuracytrain, v1, pvaluehisttest, pvaluehisttrain, histdiseasetest, histcontroltest, histdiseasetrain, histcontroltrain] = visualizePLDA2(I0, Z96_train, Z96_test, labelstrain, labelstest, A_mean, features_matrix, alpha, dir, EIGENV1) +%Inputs: +% Z96_train, Z96_test reduced dimension feature matrices +% labels labels (either -1 or +1) +% A_mean feature mean of original matrix +% feature_matrix original feature matrix +% alpha penalty value for PLDA (needed when +% visualizing discriminant direction) +% dir which PLDA direction you want to +% visualize (can only be one number), or w vector showing the direction to visualize + + +n_std = [-2 -1 0 1 2]; +type = 'brain'; %will rotate images if brain data +NUM_SUBJECTS = numel(labelstrain); +NUM_TEST = numel(labelstest) +[M,N,K] = size(I0); +[X,Y,Z] = meshgrid(1:N, 1:M, 1:K); + +labelstest = double(labelstest); +labelstrain = double(labelstrain); +Curveoption.low = 0.01; %lower bound of alpha +Curveoption.high = 100; % 75 upper bound of alpha +Curveoption.step = 7; % 5 step size of increaseing alpha +Curveoption.nPLDA = 3; %the dimension of subspaces to be compared + + +fprintf('Now calculating alpha \n'); +%if isempty(alpha) && numel(dir)==1 +alpha = Calculate_Alpha(Z96_train, EIGENV1, labelstrain, Curveoption); +fprintf('The chosen alpha is %d \n', alpha); +%end + +%A = feature_matrix - repmat(A_mean,NUM_SUBJECTS,1); %mean-subtracted original feature matrix + +fprintf('Now running PLDA \n'); +v1 = 1 + [Vec, ~] = PLDA(Z96_train', labelstrain, alpha); + v1 = real(Vec(:,1)); + + +V1 = zeros(3*M*N*K,1); +i = 1:size(Z96_train,2) +V1 = real(V1 + EIGENV1*v1(i)); + + +projtest = Z96_test*v1; +sigmatest = std(projtest); +projtrain = Z96_train*v1; +sigmatrain = std(projtrain); + +%get p values +classifiedtest(projtest<0) = -1; +classifiedtest(projtest>0) = 1; +C = confusionmat(labelstest,classifiedtest); +acc = (C(1,1) + C(2,2))/sum(C(:)); +if (acc < 0.5) + classifiedtest = classifiedtest*-1; +end + +[C, order] = confusionmat(classifiedtest,labelstest); +posInd = find(order == -1); negInd = find(order == 1); + +sensitivitytest = C(posInd, posInd)/(C(posInd,posInd)+C(posInd,negInd)); +specificitytest = C(negInd,negInd)/(C(negInd,negInd)+C(negInd,posInd)); +accuracytest = (C(1,1) + C(2,2))/sum(C(:)); + +[h,pvaluehisttest] = ttest2(projtest(labelstest==1), projtest(labelstest==-1)) + +classifiedtrain(projtrain<0) = -1; +classifiedtrain(projtrain>0) = 1; +C = confusionmat(labelstrain,classifiedtrain); +acc = (C(1,1) + C(2,2))/sum(C(:)); +if (acc < 0.5) + classifiedtrain = classifiedtrain*-1; +end + +[C, order] = confusionmat(classifiedtrain,labelstrain); +posInd = find(order == -1); negInd = find(order == 1); + +sensitivitytrain = C(posInd, posInd)/(C(posInd,posInd)+C(posInd,negInd)); +specificitytrain = C(negInd,negInd)/(C(negInd,negInd)+C(negInd,posInd)); +accuracytrain = (C(1,1) + C(2,2))/sum(C(:)); + +[h,pvaluehisttrain] = ttest2(projtrain(labelstrain==1), projtrain(labelstrain==-1)) + +%create ROC curve + +roc = unique(projtest); +classifiedtest(projtest<0) = -1; +classifiedtest(projtest>0) = 1; +[C, order] = confusionmat(labelstest,classifiedtest); +posInd = find(order == -1); negInd = find(order == 1); +acc = (C(1,1)+C(2,2))/sum(C(:)); +if acc < 0.5 + mult = -1; +else + mult = 1; +end + +for i = 1:numel(roc) + classifiedtest(projtest=roc(i)) = 1; + [C, order] = confusionmat(labelstest,classifiedtest*mult); + posInd = find(order == -1); negInd = find(order == 1); + senstest = C (posInd, posInd)/(C(posInd,posInd)+C(posInd,negInd)); + spectest = C (negInd,negInd)/(C(negInd,negInd)+C(negInd,posInd)); + accutest = (C(1,1) + C(2,2))/sum(C(:)); + specstest(i) = spectest; sensstest(i) = senstest; +end + +if sensstest(1) <0.5 + sensstest = flipud(sensstest) + specstest = flipud(specstest) +end + +roc = unique(projtrain); +classified(projtrain<0) = -1; +classified(projtrain>0) = 1; +[C, order] = confusionmat(labelstrain,classified); +posInd = find(order == -1); negInd = find(order == 1); +acc = (C(1,1)+C(2,2))/sum(C(:)); +if acc < 0.5 + mult = -1; +else + mult = 1; +end + +for i = 1:numel(roc) + classified(projtrain=roc(i)) = 1; + [C, order] = confusionmat(labelstrain,classified*mult); + posInd = find(order == -1); negInd = find(order == 1); + senstrain = C (posInd, posInd)/(C(posInd,posInd)+C(posInd,negInd)); + spectrain = C (negInd,negInd)/(C(negInd,negInd)+C(negInd,posInd)); + accutrain = (C(1,1) + C(2,2))/sum(C(:)); + specstrain(i) = spectrain; sensstrain(i) = senstrain; +end + +if sensstrain(1) <0.5 + sensstrain = flipud(sensstrain) + specstrain = flipud(specstrain) +end + + + +figure; plot(1-specstrain,sensstrain,'LineWidth',3) +xlabel('False positive rate'); +ylabel('True positive rate'); +title('Classifier ROC Curve'); +set(gca,'FontName','Times New Roman'); +set(gca,'FontSize',18); +xlim([-0.05 1]) +ylim([0 1.05]) +x = 0:0.1:1; y = x; +hold on; plot(x,y,'Color','k','linewidth',0.01,'linestyle','--'); +clear x y +%grid on; + + +%create histogram and remaining figures + +figure; +histdiseasetest = projtest(labelstest==1) +histcontroltest = projtest(labelstest==-1) +if mean(histdiseasetest) < mean(histcontroltest) + histdiseasetest = histdiseasetest(:)*-1; + histcontroltest = histcontroltest(:)*-1; + V1 = V1(:)*-1; +end + +histdiseasetrain = projtrain(labelstrain==1) +histcontroltrain = projtrain(labelstrain==-1) +if mean(histdiseasetrain) < mean(histcontroltrain) + histdiseasetrain = histdiseasetrain(:)*-1; + histcontroltrain = histcontroltrain(:)*-1; +end +xbtest = linspace(min(projtest),max(projtest),15); +xbtrain = linspace(min(projtrain),max(projtrain),15); +[nb_disease,xbtest]=hist(projtest(labelstest==-1),xbtest); +%bh=bar(xb,nb_disease./NUM_SUBJECTS*100); +%set(bh,'facecolor',[1 1 0]); +hold on; +[nb_control,xbtest]=hist(projtest(labelstest==1),xbtest); +%bh=bar(xb,nb_control./NUM_SUBJECTS*100); +nb = [nb_disease' nb_control']; +bh = bar(xbtest,nb./NUM_SUBJECTS*100,1.3,'grouped'); +%set(bh,'facecolor',[0 1 1]); +h_leg = legend('no growth','growth'); +set(h_leg,'box','off'); + +center =0; %mean(proj); + +ax = gca; +ax.XTick = [n_std(1)*sigmatest + center,n_std(2)*sigmatest+ center,center,n_std(4)*sigmatest+center,n_std(5)*sigmatest+center]; +ax.XTickLabel = {strcat(num2str(n_std(1)),'\sigma'),strcat(num2str(n_std(2)),'\sigma'),'0',strcat(num2str(n_std(4)),'\sigma'),strcat(num2str(n_std(5)),'\sigma')}; +set(gca,'fontsize',18); +xlabel('Projection score') +ylabel('Percentage incidents'); +set(gca, 'FontName','Times New Roman'); + +end + + +