Я пишу сценарий Matlab, который предназначен для обработки данных массива.Мой стиль кодирования использует абсолютные ссылки на данные и итеративные вызовы ячеек массива.Этот скрипт будет обрабатывать много данных, и я был бы признателен за советы по повышению эффективности, прежде чем уделять больше времени неэффективному кодированию.
Код следующий:
%{
Code to examine sparse masked thermal field data from a single layer of a
selective laser melting process
The data is provided in a .txt file such as
MaskedScaledLayer_83.txt
The data is comma separated in form -
frame, xloc, yloc, Temp, region
1,6.273125,91.29987,255.651,7
1,5.894271,91.28776,396.2053,7
1,5.515417,91.27564,446.6481,7
2,6.273125,91.29987,472.6041,7
2,5.894271,91.28776,472.6041,7
2,5.515417,91.27564,512.7625,7
2,6.651979,90.97992,432.9355,7
...
Goal is to determine the following at each spatial location during layer:
Max Temperature
Cooling Duration
Cooling Rate
Thermal Gradients
%}
%%
% run this from the code directory
close all; clear;
% Parameters
frame_freq=300; % Hz - camera frame rate
tolAng=10; % deg - acceptable angle from X-Y grid
tol=0.4; % mm - largest distance to adjacent pixel
%T_upper=500; % degC - upper value for cool times
%T_lower=300; % degC - lower value for cool times
% File location
pathName='C:\temp\FromJon\';
%pathName='K:\SEH\SAMME\subjects\THERM\3_Data_from_Jon\';
testData='MaskedScaledLayer_83.txt';
LayerNumber=83;
%%
% Read in data
m1=dlmread([pathName,testData],',',0,0);
frame_data=m1(:,1);
x_data=m1(:,2);
y_data=m1(:,3);
temp_data=m1(:,4);
region_data=m1(:,5);
%%
%Vizualise data locations
plot3(x_data,y_data,region_data,'.');
%%
% Determine unique x-y locations
A=m1(:,1:3);
[C,ia,ic] = unique(A(:,2:3),'rows');
numUniquePoints=length(ia);
%%
% Isolate region for fcz2, region=6
AT6=m1(region_data==6,1:4);
temp_data6=AT6(:,4);
frame_data6=AT6(:,1);
[C6,ia6,ic6] = unique(AT6(:,2:3),'rows');
numUniquePts6=length(ia6);
% Vizualise isolated data
figure
plot(C6(:,1),C6(:,2),'.')
% Store in point cloud at z=0
Z0ptCloud6=pointCloud([C6(:,1:2) zeros(numUniquePts6,1)]);
%%
%Prepare for Thermal Gradient calculations
%find nearest neighbours for each point
%indices relative to unique points
Xneg6I=NaN*ones(numUniquePts6,1);
Xpos6I=NaN*ones(numUniquePts6,1);
Yneg6I=NaN*ones(numUniquePts6,1);
Ypos6I=NaN*ones(numUniquePts6,1);
%locations and distances
Xneg6=NaN*ones(numUniquePts6,4);
Xpos6=NaN*ones(numUniquePts6,4);
Yneg6=NaN*ones(numUniquePts6,4);
Ypos6=NaN*ones(numUniquePts6,4);
for i=1:numUniquePts6
point=Z0ptCloud6.Location(i,:);
[indices,dists] = findNearestNeighbors(Z0ptCloud6,point,9);
%identify direction of each neighbour
for ind=2:5 % 1 is same point, 2:5 are candidates for nearest x/y neighbours
if dists(ind)<tol % exclude points that aren't adjacent
ii=indices(ind); %ii is index in Z0ptCloud6
% at each nearby point determine direction
pointii=Z0ptCloud6.Location(ii,:);
u=pointii-point; %direction
v = [1 0 0];
Angle_Degrees = atan2d(u(2)*v(1)-u(1)*v(2),u(1)*v(1)+u(2)*v(2));
if abs(Angle_Degrees-0)<tolAng
Xpos6I(i,1)=ii;
Xpos6(i,:)=[pointii(1) pointii(2) u(1) u(2)];
elseif abs(Angle_Degrees-90)<tolAng
Ypos6I(i,1)=ii;
Ypos6(i,:)=[pointii(1) pointii(2) u(1) u(2)];
elseif abs(Angle_Degrees-(-90))<tolAng
Yneg6I(i,1)=ii;
Yneg6(i,:)=[pointii(1) pointii(2) u(1) u(2)];
elseif (180-abs(Angle_Degrees))<tolAng
Xneg6I(i,1)=ii;
Xneg6(i,:)=[pointii(1) pointii(2) u(1) u(2)];
else
fprintf('WARNING Points not aligned with X-Y grid');
end
end
end
end
%Possible time saving:
%C/C6 is sorted for x then y so don't need to compare every location
%{
%tol=0.4;
for i=1:length(ia6)
ThisX=C6(i,1);
ThisY=C6(i,2);
NextX=C6(i+1,1);
%find next y
if NextX==ThisX %C6(i+1,1)==C6(i,1)
NextY=C6(i+1,2);
if NextY-ThisY<tol
end
end
end
%}
%%
%find max temp at each location
temp_max=zeros(numUniquePts6,1);
frame_Tmax=zeros(numUniquePts6,1);
for i=1:numUniquePts6
indices=ic6==i;
[temp_max(i,1),ii]=max(temp_data6(indices,1));
framed=frame_data6(indices,1);
frame_Tmax(i,1)=framed(ii);
end
% vizualise max Temp
figure
subplot(1,2,1)
pcshow(Z0ptCloud6.Location,temp_max,'MarkerSize',50)
view([0 0 1]);
colorbar
title(['Maximum Temperature, Layer ',num2str(LayerNumber)]);
xlabel('X (mm)');
ylabel('Y (mm)');
subplot(1,2,2)
pcshow(Z0ptCloud6.Location,frame_Tmax,'MarkerSize',50)
view([0 0 1]);
colorbar
title(['Frame of Maximum Temperature, Layer ',num2str(LayerNumber)]);
xlabel('X (mm)');
ylabel('Y (mm)');
%%
%Find thermal gradient for each point in frame of their Tmax .
%{
for i=1:numUniquePts6
forw_dT_dx=temp_max(i,1) ...
%[temp_max(i,1),I_Tmax(i,1)]=max(temp_data6(ic6==i,1));
end
%}
%%
% Find Temperature History at a point
% extract multiple peaks and determine longest time between thresholds
%unique Frames
lastFrame=max(frame_data);
temp_history=239*ones(lastFrame,1);
Tmax_perim=NaN*ones(numUniquePts6,1);
Tmax_perimFrame=NaN*ones(numUniquePts6,1);
Tmax_fill=NaN*ones(numUniquePts6,1);
Tmax_fillFrame=NaN*ones(numUniquePts6,1);
coolTime6=zeros(numUniquePts6,1);
T_upper=500;
T_lower=300;
%for i=1149 %200:200:numUniquePts6 % a few cases to test.
for i=1:numUniquePts6 % COMMENT OUT FIGURE AND PLOT
temp_history=239*ones(lastFrame,1);
indices=ic6==i;
temp_history(frame_data6(indices))=temp_data6(indices);
%longest contiguous time between thresholds
bound_indices=temp_history>T_lower&temp_history<T_upper;
%longest=max(accumarray(nonzeros((cumsum(~n)+1).*n),1));
longest=max(accumarray(nonzeros((cumsum(~bound_indices)+1).*bound_indices),1));
coolTime6(i)=longest/frame_freq;
[pks,locs]=findpeaks(temp_history,'MinPeakDistance',50,'MinPeakHeight',400,'NPeaks',2);%,'SortStr','descend');
%{
%figure
findpeaks(temp_history,'MinPeakDistance',50,'MinPeakHeight',400,'NPeaks',2,'Annotate','extents');
text(locs+.02,pks,num2str((1:numel(pks))'))
% plot(1:lastFrame,temp_history)
hold on
plot(1:lastFrame,210+20*bound_indices)
hold off
title(['Temperature history at (x,y)=(',num2str(C6(i,1)),',',num2str(C6(i,2)),') layer ',num2str(LayerNumber),', i=',num2str(i)]);
xlabel('Frame number');
ylabel('Temperature (\circC)');
%pause(1)
%}
if isempty(pks)
i
elseif length(pks)==1
%Tmax_perim(i,1)=pks(1);
%Tmax_perimFrame(i,1)=locs(1);
Tmax_fill(i,1)=pks(1);
Tmax_fillFrame(i,1)=locs(1);
else % need special cases for order and closeness of peaks
Tmax_perim(i,1)=pks(1);
Tmax_perimFrame(i,1)=locs(1);
Tmax_fill(i,1)=pks(2);
Tmax_fillFrame(i,1)=locs(2);
end
end
figure
subplot(1,2,1)
pcshow(Z0ptCloud6.Location,coolTime6,'MarkerSize',50)
view([0 0 1]);
colorbar
title(['Cool Time (sec), Layer ',num2str(LayerNumber)]);
xlabel('X (mm)');
ylabel('Y (mm)');
subplot(1,2,2)
pcshow(Z0ptCloud6.Location,frame_Tmax,'MarkerSize',50)
view([0 0 1]);
colorbar
title(['Frame of Maximum Temperature, Layer ',num2str(LayerNumber)]);
xlabel('X (mm)');
ylabel('Y (mm)');
%%
figure
subplot(1,2,1)
pcshow([C6(:,1) C6(:,2) 83*ones(numUniquePts6,1)],Tmax_perim,'MarkerSize',50)
view([0 0 1]);
colorbar
title(['Maximum Temperature Perimeter, Layer ',num2str(LayerNumber)]);
xlabel('X (mm)');
ylabel('Y (mm)');
subplot(1,2,2)
pcshow([C6(:,1) C6(:,2) 83*ones(numUniquePts6,1)],Tmax_fill,'MarkerSize',50)
view([0 0 1]);
colorbar
title(['Maximum Temperature Fill, Layer ',num2str(LayerNumber)]);
xlabel('X (mm)');
ylabel('Y (mm)');