plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_9_cov_tol_batch.m
|
.m
|
slam_matlab-master/Localization/vro_icp_9_cov_tol_batch.m
| 11,537 |
utf_8
|
59fe048123dca9a364123c99bde295e7
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
% ICP6 + convexhull = ICP9
% ICP9_cov + tolerance adjustment = ICP9_cov_tol
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
if size(op_pset1,2) <= 8 || size(op_pset2,2) <= 8
fprintf('Error in less point for convex hull.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% compute 3D convex hull
t_convex = tic;
convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
convexhull_1_x =[];
convexhull_1_y =[];
convexhull_1_z =[];
for i=1:size(convexhull_1,1)
for j=1:3
convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
end
end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z,'d-');
% grid;
% axis equal;
%draw_data = [convexhull_1_x' convexhull_1_y' convexhull_1_z'];
%mesh(draw_data);
%M = op_pset1;
%D = op_pset2;
%M_k = 1;
%D_k = 1;
M=[];
D=[];
%convex_check = 1; % check convex hull
convexhull_tolerance = 0.1; %[m]
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
%M_test=[];
%D_test=[];
M_cf=[];
D_cf=[];
sample_idx=1;
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M = [M; -x1(i,j) z1(i,j) y1(i,j)];
D = [D; -x2(i,j) z2(i,j) y2(i,j)];
%if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M_cf(sample_idx,1)=1;
%M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
%M_k = M_k + 1;
else
M_cf(sample_idx,1)=0;
end
%end
%if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D_cf(sample_idx,1)=1;
%D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
%D_k = D_k + 1;
else
D_cf(sample_idx,1)=0;
end
%end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
sample_idx = sample_idx + 1;
end
end
m_cf_idx = M_cf(:) == 0;
d_cf_idx = D_cf(:) == 0;
M(m_cf_idx,:)=[];
D(d_cf_idx,:)=[];
M_in_flag = inhull(M,op_pset1',convexhull_1,convexhull_tolerance);
D_in_flag = inhull(D,op_pset2',convexhull_2,convexhull_tolerance);
M_in_flag_idx = M_in_flag(:) == 0;
D_in_flag_idx = D_in_flag(:) == 0;
M(M_in_flag_idx,:)=[];
D(D_in_flag_idx,:)=[];
M=M';
D=D';
elapsed_convex = toc(t_convex);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
pose_std = pose_std';
M = [];
D = [];
pt1 = [];
pt2 = [];
op_pset1_icp = [];
op_pset2_icp = [];
tree = [];
convexhull_1=[];
convexhull_2=[];
convexhull_1_x =[];
convexhull_1_y =[];
convexhull_1_z =[];
M_cf=[];
D_cf=[];
M_in_flag=[];
D_in_flag=[];
M_in_flag_idx=[];
D_in_flag_idx=[];
op_pset1=[];
op_pset2=[];
x1=[];
y1=[];
z1=[];
img1=[];
c1=[];
x2=[];
y2=[];
z2=[];
img2=[];
c2=[];
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_icp2_cov_fast_fast.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_icp2_cov_fast_fast.m
| 19,935 |
utf_8
|
b2230e5879dca9b7519e5b3b37483454
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 8/30/12
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_icp2_cov_fast(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, icp_mode, dis)
if nargin < 14
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') % Dynamic data
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
%[frm1,des1] = vl_sift(single(img1)) ;
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature')% Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
%[frm2,des2] = vl_sift(single(img2)) ;
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%[match, scores] = vl_ubcmatch(des1,des2) ;
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= 0 && img2(ROW2, COL2) >= 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
% stdev_threshold = 0.1;
% stdev_count = 0;
% count_threshold = 15;
% mean_threshold = 0.1;
% mean_count = 0;
% window_size = 30;
% debug_data=[];
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% if cnum >= valid_ransac
% break;
% end
% if cnum/pnum >= inlier_ratio
% break;
% enddynamic_data_index
% total_cnum(i)=cnum;
% if i > window_size && inliers_std ~= 0
% inliers_std_prev = inliers_std;
% inliers_std = std(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_std_delta = abs(inliers_std - inliers_std_prev)/inliers_std_prev;
%
% inliers_mean_prev = inliers_mean;
% inliers_mean = mean(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_mean_delta = abs(inliers_mean - inliers_mean_prev)/inliers_mean_prev;
%
% if inliers_std_delta < stdev_threshold
% stdev_count = stdev_count + 1;
% else
% stdev_count = 0;
% end
%
% if inliers_mean_delta < mean_threshold
% mean_count = mean_count + 1;
% else
% mean_count = 0;
% end
%
% inlier_ratio = max(total_cnum)/pnum;
% % count_threshold = 120000 / ((inlier_ratio*100)^2); %-26 * (inlier_ratio*100 - 20) + 800;
%
% if stdev_count > count_threshold %&& mean_count > count_threshold
% break;
% end
% else
% inliers_std = std(total_cnum);
% inliers_mean = mean(total_cnum);
% end
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%% Run SVD
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2);
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe);
t_svd = tic;
end
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Test LM
%[rot_lm, trans_lm] = lm_point(op_pset1, op_pset2);
% [rot_lm, trans_lm] = lm_point2plane(op_pset1, op_pset2);
% [phi_lm, theta_lm, psi_lm] = rot_to_euler(rot_lm);
% [theta*180/pi theta_lm*180/pi]
% [phi*180/pi phi_lm*180/pi]
% [psi*180/pi psi_lm*180/pi]
% Save feature points
%feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
% Compute RMSE
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse = rmse + unit_rmse;
% end
% rmse_feature = rmse / size(op_pset1,2);
%rmse_feature = rms_error(op_pset1, op_pset2_transed);
% Show correspondent points
% plot3(op_pset1(1,:),op_pset1(2,:),op_pset1(3,:),'b*-');
% hold on;
% plot3(op_pset2(1,:),op_pset2(2,:),op_pset2(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
%Compute the elapsed time
%rt_total = etime(clock,t);
%elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
%% Run ICP
%[phi_icp, theta_icp, psi_icp, trans_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_2(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_3(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_4(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_5(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
if strcmp(icp_mode, 'icp_ch')
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
else
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_6_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
end
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_10(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_13(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%Check status of SVD
if sta_icp == 0 || error ~= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta_icp == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%elapsed_icp = toc(t_icp);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
%rot = rot_icp;
% [rmse_feature rmse_icp]
% [theta*180/pi theta_icp*180/pi]
% [trans(1) trans_icp(1)]
%if rmse_icp <= rmse_feature
trans = trans_icp;
phi = phi_icp;
theta = theta_icp;
psi = psi_icp;
%end
%convert degree
% r2d=180.0/pi;
% phi=phi*r2d;
% theta=theta*r2d;
% psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_9_cov_tol_dist.m
|
.m
|
slam_matlab-master/Localization/vro_icp_9_cov_tol_dist.m
| 10,953 |
utf_8
|
db7a3f2c470869a3f34f6a0b48cec836
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
% ICP6 + convexhull = ICP9
% ICP9_cov + tolerance adjustment = ICP9_cov_tol
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_9_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
if size(op_pset1,2) <= 8 || size(op_pset2,2) <= 8
fprintf('Error in less point for convex hull.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% compute 3D convex hull
t_convex = tic;
convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
convexhull_1_x =[];
convexhull_1_y =[];
convexhull_1_z =[];
for i=1:size(convexhull_1,1)
for j=1:3
convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
end
end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z,'d-');
% grid;
% axis equal;
%draw_data = [convexhull_1_x' convexhull_1_y' convexhull_1_z'];
%mesh(draw_data);
%M = op_pset1;
%D = op_pset2;
M_k = 1;
D_k = 1;
M=[];
D=[];
convex_check = 1; % check convex hull
convexhull_tolerance = 0.1; %[m]
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M_test = [-x1(i,j) z1(i,j) y1(i,j)];
M_in_flag = inhull(M_test,op_pset1',convexhull_1,convexhull_tolerance);
D_test = [-x2(i,j) z2(i,j) y2(i,j)];
D_in_flag = inhull(D_test,op_pset2',convexhull_2,convexhull_tolerance);
if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
M_k = M_k + 1;
end
end
if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
D_k = D_k + 1;
end
end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
end
end
elapsed_convex = toc(t_convex);
%distance filter
[M, D] = check_feature_distance_icp(M, D);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
pose_std = pose_std';
M = [];
D = [];
pt1 = [];
pt2 = [];
pt1_new=[];
pt2_new=[];
op_pset1 = [];
op_pset2 = [];
op_pset1_icp = [];
op_pset2_icp = [];
tree = [];
convexhull_1=[];
convexhull_2=[];
M_in_flag=[];
D_in_flag=[];
end
|
github
|
rising-turtle/slam_matlab-master
|
check_stored_matched_points.m
|
.m
|
slam_matlab-master/Localization/check_stored_matched_points.m
| 1,184 |
utf_8
|
1620fb7c613849c92ba3def37bcd39da
|
% Check if there is the stored matched points
%
% Author : Soonhac Hong ([email protected])
% Date : 3/11/2013
function [exist_flag] = check_stored_matched_points(data_name, dm, first_cframe, second_cframe, isgframe, sequence_data)
exist_flag = 0;
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
end
if strcmp(isgframe, 'gframe')
dataset_dir = sprintf('%s/matched_points_gframe',dataset_dir);
else
dataset_dir = sprintf('%s/matched_points',dataset_dir);
end
file_name = sprintf('d1_%04d_%04d.mat',first_cframe, second_cframe);
dirData = dir(dataset_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
if isempty(file_list)
return;
else
for i=1:size(file_list,1)
if strcmp(file_list{i}, file_name)
exist_flag = 1;
break;
end
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
rot_to_euler.m
|
.m
|
slam_matlab-master/Localization/rot_to_euler.m
| 1,068 |
utf_8
|
5338a4d30525b25e07f1db2f561d509b
|
% Calculate the euler angle(yaw, pitch, roll) from rotation matrix
%
% Yaw is a counterclockwise rotation of phi(alpha) about the z-axis
% Pitch is a counterclockwise rotation of theta(beta) about the y-axis
% Roll is a counterclockwise rotation of psi(gamma) about the x-axis
%
% Author : Soonhac Hong ([email protected])
% Date : 3/19/2011
% Reference : S.M. Lavalle : Planning Algorithm (p.97-100)
function [phi, theta, psi] = rot_to_euler(rot)
% phi= atan2(rot(2,1), rot(1,1));
% theta = atan2(-rot(3,1), sqrt(rot(3,2)^2+rot(3,3)^2));
% psi = atan2(rot(3,2), rot(3,3));
% psi= atan2(rot(2,1), rot(1,1));
% phi = atan2(-rot(3,1), sqrt(rot(3,2)^2+rot(3,3)^2));
% theta = atan2(rot(3,2), rot(3,3));
% Original code from Dr. Ye
psi = atan2(-rot(1,2), rot(2, 2)); % yaw about z --->this code is right, but the thesis is wrong.
theta = atan2(rot(3,2), -rot(1,2)*sin(psi)+rot(2,2)*cos(psi)); % pitch about x
phi = atan2(rot(1,3)*cos(psi)+rot(2,3)*sin(psi),rot(1,1)*cos(psi)+rot(2,1)*sin(psi)); % roll about y
end
|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_9_cov_tol_batch_dist.m
|
.m
|
slam_matlab-master/Localization/vro_icp_9_cov_tol_batch_dist.m
| 11,663 |
utf_8
|
012db11e606c43c3d00d9a83614fbd7c
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
% ICP6 + convexhull = ICP9
% ICP9_cov + tolerance adjustment = ICP9_cov_tol
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch_dist(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
if size(op_pset1,2) <= 8 || size(op_pset2,2) <= 8
fprintf('Error in less point for convex hull.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% compute 3D convex hull
t_convex = tic;
convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
% convexhull_1_x =[];
% convexhull_1_y =[];
% convexhull_1_z =[];
%
% for i=1:size(convexhull_1,1)
% for j=1:3
% convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
% convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
% convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
% end
% end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z,'d-');
% grid;
% axis equal;
%draw_data = [convexhull_1_x' convexhull_1_y' convexhull_1_z'];
%mesh(draw_data);
%M = op_pset1;
%D = op_pset2;
%M_k = 1;
%D_k = 1;
M=[];
D=[];
%convex_check = 1; % check convex hull
convexhull_tolerance = 0.1; %[m]
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
%M_test=[];
%D_test=[];
M_cf=[];
D_cf=[];
sample_idx=1;
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M = [M; -x1(i,j) z1(i,j) y1(i,j)];
D = [D; -x2(i,j) z2(i,j) y2(i,j)];
%if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M_cf(sample_idx,1)=1;
%M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
%M_k = M_k + 1;
else
M_cf(sample_idx,1)=0;
end
%end
%if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D_cf(sample_idx,1)=1;
%D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
%D_k = D_k + 1;
else
D_cf(sample_idx,1)=0;
end
%end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
sample_idx = sample_idx + 1;
end
end
m_cf_idx = M_cf(:) == 0;
d_cf_idx = D_cf(:) == 0;
M(m_cf_idx,:)=[];
D(d_cf_idx,:)=[];
M_in_flag = inhull(M,op_pset1',convexhull_1,convexhull_tolerance);
D_in_flag = inhull(D,op_pset2',convexhull_2,convexhull_tolerance);
M_in_flag_idx = M_in_flag(:) == 0;
D_in_flag_idx = D_in_flag(:) == 0;
M(M_in_flag_idx,:)=[];
D(D_in_flag_idx,:)=[];
M=M';
D=D';
elapsed_convex = toc(t_convex);
%distance filter
[M, D] = check_feature_distance_icp(M, D);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
pose_std = pose_std';
M = [];
D = [];
pt1 = [];
pt2 = [];
pt1_new=[];
pt2_new=[];
op_pset1 = [];
op_pset2 = [];
op_pset1_icp = [];
op_pset2_icp = [];
tree = [];
convexhull_1=[];
convexhull_2=[];
% convexhull_1_x =[];
% convexhull_1_y =[];
% convexhull_1_z =[];
M_cf=[];
D_cf=[];
m_cf_idx=[];
d_cf_idx=[];
M_in_flag=[];
D_in_flag=[];
M_in_flag_idx=[];
D_in_flag_idx=[];
op_pset1_icp_normal=[];
op_pset2_icp_transed=[];
end
|
github
|
rising-turtle/slam_matlab-master
|
load_icp_pose.m
|
.m
|
slam_matlab-master/Localization/load_icp_pose.m
| 1,573 |
utf_8
|
0187e4f56957260f4e18836e5804c8cf
|
% Load matched points from a file
%
% Author : Soonhac Hong ([email protected])
% Date : 3/11/2013
%function [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, isgframe, sequence_data)
function [phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = load_icp_pose(data_name, dm, first_cframe, second_cframe, icp_mode, sequence_data)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
dataset_dir = strrep(prefix, '/d1','');
if strcmp(icp_mode, 'icp_ch')
file_name = sprintf('%s/icp_ch_pose/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
else
file_name = sprintf('%s/icp_pose/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
if strcmp(icp_mode, 'icp_ch')
file_name = sprintf('%s/icp_ch_pose/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
else
file_name = sprintf('%s/icp_pose/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
end
end
% if strcmp(isgframe, 'gframe')
% file_name = sprintf('%s/matched_points_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% else
% file_name = sprintf('%s/matched_points/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% end
load(file_name);
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist.m
| 16,414 |
utf_8
|
6d555711bc67c37d10257bef2804a3ea
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, dis)
if nargin < 13
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none') == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none');
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none');
t_svd = tic;
end
[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta == 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_addpath_creative.m
|
.m
|
slam_matlab-master/Localization/localization_addpath_creative.m
| 434 |
utf_8
|
d744a68621891ab087fb12d5c0431645
|
% Add the path for graph slam
%
% Author : Soonhac Hong ([email protected])
% Date : 10/16/12
function localization_addpath_creative
%addpath('D:\Soonhac\SW\icp');
%addpath('D:\Soonhac\SW\kdtree');
%addpath('D:\Soonhac\SW\LevenbergMarquardt');
addpath('..\SIFT\sift-0.9.19-bin\sift');
%addpath('D:\Soonhac\SW\GradientConcensus');
%addpath('D:\Soonhac\SW\OpenSURF_version1c');
%addpath('E:\data\Amir\code\code3\code_from_dr_ye');
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2.m
| 17,174 |
utf_8
|
9d45403332d443c4e248983141bed911
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe, sequence_data) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data);
end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe, sequence_data) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
if is_10M_data == 1
valid_dist_max = 8; % 5m
else
valid_dist_max = 5; % 5m
end
valid_dist_min = 0.8; % 0.8m
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
t_svd = tic;
end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta == 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
save_depth_features.m
|
.m
|
slam_matlab-master/Localization/save_depth_features.m
| 429 |
utf_8
|
ac126f69540fa93b52e177bf4693644c
|
% Save sift visual feature into a file
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function save_depth_features(data_name, dm, cframe, depth_frm, depth_des, depth_ct)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
dataset_dir = strrep(prefix, '/d1','');
file_name = sprintf('%s/depth_feature/d1_%04d.mat',dataset_dir, cframe);
save(file_name, 'depth_frm', 'depth_des', 'depth_ct');
end
|
github
|
rising-turtle/slam_matlab-master
|
get_kinect_tum_dir_name.m
|
.m
|
slam_matlab-master/Localization/get_kinect_tum_dir_name.m
| 823 |
utf_8
|
54ffe57adc759fb2881357d54c5bc99e
|
% Get directory name of kinect_tum data set
%
% Parameters
% dm : index of directory of data
%
% Author : Soonhac Hong ([email protected])
% Date : 9/25/12
function [dir_name_list]=get_kinect_tum_dir_name()
dir_name_list={'rgbd_dataset_freiburg1_xyz','rgbd_dataset_freiburg1_floor','rgbd_dataset_freiburg2_large_no_loop','rgbd_dataset_freiburg2_large_with_loop','rgbd_dataset_freiburg2_pioneer_slam','rgbd_dataset_freiburg2_pioneer_slam2','rgbd_dataset_freiburg2_pioneer_slam3','rgbd_dataset_freiburg3_long_office_household','rgbd_dataset_freiburg3_nostructure_texture_near_withloop','rgbd_dataset_freiburg3_structure_notexture_far','rgbd_dataset_freiburg3_structure_notexture_near','rgbd_dataset_freiburg3_structure_texture_far','rgbd_dataset_freiburg3_structure_texture_near'};
%dir_name=dir_name_list{dir_index};
end
|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_9_cov_tol_dist_EKF.m
|
.m
|
slam_matlab-master/Localization/vro_icp_9_cov_tol_dist_EKF.m
| 11,437 |
utf_8
|
9c985fd9089bbf1de243e1f8f0ab0be1
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
% ICP6 + convexhull = ICP9
% ICP9_cov + tolerance adjustment = ICP9_cov_tol
% ICP9_cov_tol_dist + adjust coordinate for EKF = ICP9_cov_tol_dist_EKF
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_9_cov_tol_dist_EKF(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
if size(op_pset1,2) <= 8 || size(op_pset2,2) <= 8
fprintf('Error in less point for convex hull.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% compute 3D convex hull
t_convex = tic;
convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
convexhull_1_x =[];
convexhull_1_y =[];
convexhull_1_z =[];
for i=1:size(convexhull_1,1)
for j=1:3
convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
end
end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z,'d-');
% grid;
% axis equal;
%draw_data = [convexhull_1_x' convexhull_1_y' convexhull_1_z'];
%mesh(draw_data);
%M = op_pset1;
%D = op_pset2;
M_k = 1;
D_k = 1;
M=[];
D=[];
convex_check = 1; % check convex hull
convexhull_tolerance = 0.1; %[m]
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M_test = [-x1(i,j) -y1(i,j) z1(i,j)];
M_in_flag = inhull(M_test,op_pset1',convexhull_1,convexhull_tolerance);
D_test = [-x2(i,j) -y2(i,j) z2(i,j)];
D_in_flag = inhull(D_test,op_pset2',convexhull_2,convexhull_tolerance);
if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
M_k = M_k + 1;
end
end
if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
D_k = D_k + 1;
end
end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
end
end
elapsed_convex = toc(t_convex);
%distance filter
[M, D] = check_feature_distance_icp(M, D);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
%[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
[t_init(1:3)] = R2e(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point_EKF(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
[euler_icp] = R2e(rot_icp); %rot_to_euler(rot_icp);
phi_icp = euler_icp(1);
theta_icp = euler_icp(2);
psi_icp = euler_icp(3);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
%[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
%pose_std = pose_std';
pose_std = [];
% M = [];
% D = [];
% pt1 = [];
% pt2 = [];
% pt1_new=[];
% pt2_new=[];
% op_pset1 = [];
% op_pset2 = [];
% op_pset1_icp = [];
% op_pset2_icp = [];
% tree = [];
% convexhull_1=[];
% convexhull_2=[];
% M_in_flag=[];
% D_in_flag=[];
clear M D pt1 pt2 pt1_new pt2_new op_pset1 op_pset2 op_pset1_icp op_pset2_icp tree convexhull_1 convexhull_2 M_in_flag D_in_flag convexhull_1_x convexhull_1_y convexhull_1_z
clear FUN
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadSR_no_bpc_time_single_binary.m
|
.m
|
slam_matlab-master/Localization/LoadSR_no_bpc_time_single_binary.m
| 6,295 |
utf_8
|
c01368aeffe7d712b1c93d366697a3ee
|
% Load data from Swiss Ranger
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
% No bad pixel compensation
function [img, x, y, z, c, rtime, error] = LoadSR_no_bpc_time_single_binary(data_name, filter_name, boarder_cut_off, dm, j, scale, type_value)
% if nargin < 6
% scale = 1;
% end
%apitch=-43+3*dm;
%[prefix, err]=sprintf('../data/d%d_%d/d%d', dm, apitch, dm);
% [prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
%
% if j<10
% [s, err]=sprintf('%s_000%d.dat', prefix, j);
% elseif j<100
% [s, err]=sprintf('%s_00%d.dat', prefix, j);
% elseif j<1000
% [s, err]=sprintf('%s_0%d.dat', prefix, j);
% else
% [s, err]=sprintf('%s_%d.dat', prefix, j);
% end
img=[];
x=[];
y=[];
z=[];
c=[];
error=0;
rtime=0;
%s_binary='D:\soonhac\Project\PNBD\SW\sr4000\SwissRangerSampleGui\data\d1_0001.bdat';
%s_binary='d1_0001.bdat';
%s_binary=sprintf('E:\\data\\motive\\m5_swing_loop_2\\processed_data\\binary_data\\d1_%04d.bdat',j);
%s_binary=sprintf('E:\\data\\swing\\revisiting2_10m\\processed_data\\binary_data\\d1_%04d.bdat',j);
%s_binary=sprintf('E:\\data\\Amir\\processed_data\\exp1_bus_door_straight_150_Copy\\binary_data\\d1_%04d.bdat',j);
%s_binary=sprintf('D:\\Soonhac\\Data\\sr4k\\exp1_bus_door_straight_150_Copy\\binary_data\\d1_%04d.bdat',j);
%s_binary=sprintf('D:\\Soonhac\\Data\\sr4k\\smart_cane\\binary_data\\d1_%04d.bdat',j); % for KCLCD test
%s_binary=sprintf('C:\\SC-DATA-TRANSFER\\d1_0001.bdat');
s_binary=sprintf('C:\\SC-DATA-TRANSFER\\d1_%04d.bdat',j); % for running demo
%s_binary=sprintf('D:\\Soonhac\\Data\\sr4k\\smart_cane\\exp2_etas523_lefthallway_exp1\\d1_%04d.bdat',j); % for KCLCD test
confidence_read=1;
fw=1;
sr4k_image_width = 176;
sr4k_image_height = 144;
sr4k_image_size=[sr4k_image_height sr4k_image_width];
%t_pre = clock; %cputime;
t_pre = tic;
%a = load(s); % text file
fileID=fopen(s_binary);
if fileID==-1
%disp('File open fails !!');
error=-1;
return;
end
%a=fread(fileID,[sr4k_image_width*3,sr4k_image_height],'float');
%fseek(fileID,sr4k_image_height*3*sr4k_image_width,'bof');
%b=fread(fileID,[sr4k_image_width*2,sr4k_image_height],'uint16');
%a=vec2mat(a',sr4k_image_width);
z=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
x=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
y=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
img=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
c=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
fclose(fileID);
z=z';
x=x';
y=y';
img=img';
c=c';
% k=144*3+1;
% img = double(b(1:sr4k_image_height, :));
% z = a(1:144, :);
% x = a(145:288, :);
% y = a(289:144*3, :);
% z = medfilt2(z,[fw fw]); x = medfilt2(x, [fw fw]); y = medfilt2(y, [fw fw]);
%time_stamp = a(721,1); % time stamp
time_stamp=0;
% if confidence_read == 1
% c = b(sr4k_image_height+1:sr4k_image_height*2, :);
% %c = a(144*4+1:144*5, :);
% % Apply median filter to a pixel which confidence leve is zero.
% %confidence_cut_off = 1;
% %[img, x, y, z, c] = compensate_badpixel(img, x, y, z, c, confidence_cut_off);
% else
% c = 0;
% end
img_size=size(img);
x_size=size(x);
y_size=size(y);
z_size=size(z);
c_size=size(c);
if sum(img_size-sr4k_image_size)~=0 || sum(x_size-sr4k_image_size)~=0 || sum(y_size-sr4k_image_size)~=0 || sum(z_size-sr4k_image_size)~=0 || sum(c_size-sr4k_image_size)~=0
%disp('One of matrix is corrupted.');
error=-1;
return;
end
%Cut-off on the horizontal boarder
if boarder_cut_off > 0
img=cut_boarder(img,boarder_cut_off);
x=cut_boarder(x,boarder_cut_off);
y=cut_boarder(y,boarder_cut_off);
z=cut_boarder(z,boarder_cut_off);
end
%Scale intensity image to [0 255]
if scale == 1
img = scale_img(img, fw, type_value, 'intensity');
end
% % Adaptive histogram equalization
img = adapthisteq(img);
%img = histeq(img);
%filtering
%filter_list={'none','median','gaussian'};
gaussian_h = fspecial('gaussian',[3 3],1); %sigma = 1
gaussian_h_5 = fspecial('gaussian',[5 5],1); %sigma = 1
switch filter_name
case 'median'
img=medfilt2(img, [3 3]);
x=medfilt2(x, [3 3]);
y=medfilt2(y, [3 3]);
z=medfilt2(z, [3 3]);
case 'median5'
img=medfilt2(img, [5 5]);
x=medfilt2(x, [5 5]);
y=medfilt2(y, [5 5]);
z=medfilt2(z, [5 5]);
case 'gaussian'
img=imfilter(img, gaussian_h,'replicate');
x=imfilter(x, gaussian_h,'replicate');
y=imfilter(y, gaussian_h,'replicate');
z=imfilter(z, gaussian_h,'replicate');
case 'gaussian_edge_std'
img=imfilter(img, gaussian_h,'replicate');
x_g=imfilter(x, gaussian_h,'replicate');
y_g=imfilter(y, gaussian_h,'replicate');
z_g=imfilter(z, gaussian_h,'replicate');
x = check_edges(x, x_g);
y = check_edges(y, y_g);
z = check_edges(z, z_g);
case 'gaussian5'
img=imfilter(img, gaussian_h_5,'replicate');
x=imfilter(x, gaussian_h_5,'replicate');
y=imfilter(y, gaussian_h_5,'replicate');
z=imfilter(z, gaussian_h_5,'replicate');
end
%rtime = etime(clock, t_pre); %cputime - t_pre;
%delete('d1_0001.bdat');
rtime = toc(t_pre);
end
function [img]=cut_boarder(img, cut_off)
image_size=size(img);
h_cut_off_pixel=round(image_size(2)*cut_off/100);
v_cut_off_pixel=round(image_size(1)*cut_off/100);
img(:,(image_size(2)-h_cut_off_pixel+1):image_size(2))=[]; %right side of Horizontal
img(:,1:h_cut_off_pixel)=[]; %left side of Horizontal
img((image_size(1)-v_cut_off_pixel+1):image_size(1),:)=[]; %up side of vertical
img(1:v_cut_off_pixel,:)=[]; %bottom side of vertical
end
function [data] = check_edges(data, data_g)
%edges = 0;
for i = 2:size(data,1)-1
for j= 2:size(data,2)-1
%if var(data(i-1:i+1,j-1:j+1)) <= 0.001
unit_vector = [data(i-1,j-1:j+1) data(i, j-1:j+1) data(i+1, j-1:j+1)];
%if std(unit_vector)/(max(unit_vector) - min(unit_vector)) <= 0.4
if std(unit_vector) <= 0.1
data(i,j) = data_g(i,j);
%else
% edges = edges + 1;
end
end
end
%edges
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadPrimesense_newmodel.m
|
.m
|
slam_matlab-master/Localization/LoadPrimesense_newmodel.m
| 2,811 |
utf_8
|
fe8af725cda408eb2b6b0fd64fd56a85
|
% Load data from Kinect
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
function [img, X, Y, Z] = LoadPrimesense_model(dm, file_index)
if file_index<11
z_file_name=sprintf('D:/image/pm5_roll/image%d/depth/00%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/pm5_roll/image%d/rgb/00%d.png',dm-1,file_index-1);
elseif file_index<101
z_file_name=sprintf('D:/image/pm5_roll/image%d/depth/0%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/pm5_roll/image%d/rgb/0%d.png',dm-1,file_index-1);
elseif file_index<605
z_file_name=sprintf('D:/image/pm5_roll/image%d/depth/%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/pm5_roll/image%d/rgb/%d.png',dm-1,file_index-1);
end
depth_img=imread(z_file_name);
depth_img=double(depth_img);
img1=imread(img_file_name);
img=rgb2gray(img1);
gaussian_h = fspecial('gaussian',[3 3],1);
img=imfilter(img, gaussian_h,'replicate');
%img=im2double(img);
%Rt=[ 0.99977 0.010962 -0.018654 0.023278;
% -0.010059 0.9988 0.047831 -0.0097038;
% 0.019156 -0.047632 0.99868 -0.0093007 ]; % add calibration R and T
% R=[ 1.0000 -0.0033 0.0028 26.87065;
% 0.0033 1.0000 0.0043 0.9;
% -0.0028 -0.0042 1.0000 6.7;
% 0 0 0 1 ] ;
R=[ 1.0000 0 0 25;
0 1 0 0.9;
0 0 1 0.9;
0 0 0 1 ] ;
IR=[1 0 0 0;
0 1 0 0;
0 0 1 0];
Kr=[ 552 0 321;
0 552 227;
0 0 1];
[imh, imw] = size(depth_img);
X=zeros(imh,imw);
Y=zeros(imh,imw);
Z=zeros(imh,imw);
fx = 584; %# focal length x 551.0/420
fy = 584; %# focal length y 548.0/420
cx = 318; %# optical center x //319.5
cy = 238; %# optical center y ///239.5
ds = 1.0; %# depth scaling
factor = 1; %# for the 16-bit PNG files
for v=1:size(depth_img,1) %height
for u=1:size(depth_img,2) %width
z = (depth_img(v,u) / factor) * ds;
x = (u - cx) * z / fx;
y = (v - cy) * z / fy;
% X(v,u) = x;
% Y(v,u) = y;
% Z(v,u) = z;
uv_vector1=R*[x y z 1]';
uv_vector=Kr*IR*uv_vector1;
u_vector=ceil(uv_vector(1,:)/uv_vector(3,:));
v_vector=ceil(uv_vector(2,:)/uv_vector(3,:));
%u_vector=round(uv_vector(1,:)/uv_vector(3,:));
%v_vector=round(uv_vector(2,:)/uv_vector(3,:));
if u_vector>0 && u_vector<640 &&v_vector>0 && v_vector<480
X(v_vector,u_vector)=uv_vector1(1,:);
Y(v_vector,u_vector)=uv_vector1(2,:);
Z(v_vector,u_vector)=uv_vector1(3,:);
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
confidence_filter.m
|
.m
|
slam_matlab-master/Localization/confidence_filter.m
| 633 |
utf_8
|
736f36b137dc30db3995599cb4ed1cb3
|
% Eliminate the points by confidence map
function [updated_match] = confidence_filter(match, pset1_index, pset2_index, c1, c2)
% confidence_threshold = 3;
confidence_threshold_percentage = 0.4;
confidence_threshold_1 = floor((max(max(c1)) - min(min(c1))) * confidence_threshold_percentage);
confidence_threshold_2 = floor((max(max(c2)) - min(min(c2))) * confidence_threshold_percentage);
i = 1;
for m=1:size(match,2)
if c1(pset1_index(1,m), pset1_index(2,m)) > confidence_threshold_1 && c2(pset2_index(1,m), pset2_index(2,m)) > confidence_threshold_2
updated_match(:,i) = match(:,m);
i = i + 1;
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_9_cov_tol.m
|
.m
|
slam_matlab-master/Localization/vro_icp_9_cov_tol.m
| 10,748 |
utf_8
|
47385bb52bb3f1b4eda923d9ea20d7d9
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
% ICP6 + convexhull = ICP9
% ICP9_cov + tolerance adjustment = ICP9_cov_tol
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_9_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
if size(op_pset1,2) < 5
fprintf('Error in less point for convex hull.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% compute 3D convex hull
t_convex = tic;
convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
convexhull_1_x =[];
convexhull_1_y =[];
convexhull_1_z =[];
for i=1:size(convexhull_1,1)
for j=1:3
convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
end
end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z,'d-');
% grid;
% axis equal;
%draw_data = [convexhull_1_x' convexhull_1_y' convexhull_1_z'];
%mesh(draw_data);
%M = op_pset1;
%D = op_pset2;
M_k = 1;
D_k = 1;
M=[];
D=[];
convex_check = 1; % check convex hull
convexhull_tolerance = 0.1; %[m]
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M_test = [-x1(i,j) z1(i,j) y1(i,j)];
M_in_flag = inhull(M_test,op_pset1',convexhull_1,convexhull_tolerance);
D_test = [-x2(i,j) z2(i,j) y2(i,j)];
D_in_flag = inhull(D_test,op_pset2',convexhull_2,convexhull_tolerance);
if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
M_k = M_k + 1;
end
end
if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
D_k = D_k + 1;
end
end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
end
end
elapsed_convex = toc(t_convex);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
pose_std = pose_std';
M = [];
D = [];
pt1 = [];
pt2 = [];
op_pset1_icp = [];
op_pset2_icp = [];
tree = [];
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast.m
| 14,320 |
utf_8
|
4a81d4c1c55144dcff1bb08eb0eb1664
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, dis)
if nargin < 13
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') % Dynamic data
cframe = sframe;
else
cframe = j;
end
if check_stored_visual_feature(data_name, dm, cframe) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') % Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
if check_stored_visual_feature(data_name, dm, cframe) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta == 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_icp2_cov_fast_fast_dist2.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_icp2_cov_fast_fast_dist2.m
| 21,044 |
utf_8
|
f999be537c4198a4027573b0d293d8e8
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 8/30/12
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_icp2_cov_fast_fast_dist2(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, icp_mode, dis)
if nargin < 14
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') % Dynamic data
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
%[frm1,des1] = vl_sift(single(img1)) ;
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature')% Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
%[frm2,des2] = vl_sift(single(img2)) ;
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe,'none') == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%[match, scores] = vl_ubcmatch(des1,des2) ;
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
valid_dist_max = 5; % 5m
valid_dist_min = 0.8; % 0.8m
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= 0 && img2(ROW2, COL2) >= 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
% stdev_threshold = 0.1;
% stdev_count = 0;
% count_threshold = 15;
% mean_threshold = 0.1;
% mean_count = 0;
% window_size = 30;
% debug_data=[];
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% if cnum >= valid_ransac
% break;
% end
% if cnum/pnum >= inlier_ratio
% break;
% enddynamic_data_index
% total_cnum(i)=cnum;
% if i > window_size && inliers_std ~= 0
% inliers_std_prev = inliers_std;
% inliers_std = std(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_std_delta = abs(inliers_std - inliers_std_prev)/inliers_std_prev;
%
% inliers_mean_prev = inliers_mean;
% inliers_mean = mean(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_mean_delta = abs(inliers_mean - inliers_mean_prev)/inliers_mean_prev;
%
% if inliers_std_delta < stdev_threshold
% stdev_count = stdev_count + 1;
% else
% stdev_count = 0;
% end
%
% if inliers_mean_delta < mean_threshold
% mean_count = mean_count + 1;
% else
% mean_count = 0;
% end
%
% inlier_ratio = max(total_cnum)/pnum;
% % count_threshold = 120000 / ((inlier_ratio*100)^2); %-26 * (inlier_ratio*100 - 20) + 800;
%
% if stdev_count > count_threshold %&& mean_count > count_threshold
% break;
% end
% else
% inliers_std = std(total_cnum);
% inliers_mean = mean(total_cnum);
% end
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%% Run SVD
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2,'none');
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe,'none');
t_svd = tic;
end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Test LM
%[rot_lm, trans_lm] = lm_point(op_pset1, op_pset2);
% [rot_lm, trans_lm] = lm_point2plane(op_pset1, op_pset2);
% [phi_lm, theta_lm, psi_lm] = rot_to_euler(rot_lm);
% [theta*180/pi theta_lm*180/pi]
% [phi*180/pi phi_lm*180/pi]
% [psi*180/pi psi_lm*180/pi]
% Save feature points
%feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
% Compute RMSE
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse = rmse + unit_rmse;
% end
% rmse_feature = rmse / size(op_pset1,2);
%rmse_feature = rms_error(op_pset1, op_pset2_transed);
% Show correspondent points
% plot3(op_pset1(1,:),op_pset1(2,:),op_pset1(3,:),'b*-');
% hold on;
% plot3(op_pset2(1,:),op_pset2(2,:),op_pset2(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
%Compute the elapsed time
%rt_total = etime(clock,t);
%elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
%% Run ICP
%[phi_icp, theta_icp, psi_icp, trans_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_2(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_3(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_4(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_5(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
if strcmp(icp_mode, 'icp_ch')
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_dist(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch_dist(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
else
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_6_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
end
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_10(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_13(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%Check status of SVD
if sta_icp == 0 || error ~= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta_icp == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%elapsed_icp = toc(t_icp);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
%rot = rot_icp;
% [rmse_feature rmse_icp]
% [theta*180/pi theta_icp*180/pi]
% [trans(1) trans_icp(1)]
%if rmse_icp <= rmse_feature
trans = trans_icp;
phi = phi_icp;
theta = theta_icp;
psi = psi_icp;
%end
%convert degree
% r2d=180.0/pi;
% phi=phi*r2d;
% theta=theta*r2d;
% psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
save_icp_pose.m
|
.m
|
slam_matlab-master/Localization/save_icp_pose.m
| 1,449 |
utf_8
|
1dbca54b1c887539d2074a5459abc5db
|
% Save matched points into a file
%
% Author : Soonhac Hong ([email protected])
% Date : 8/12/2013
function save_icp_pose(data_name, dm, first_cframe, second_cframe, icp_mode, sequence_data, phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
dataset_dir = strrep(prefix, '/d1','');
if strcmp(icp_mode, 'icp_ch')
file_name = sprintf('%s/icp_ch_pose/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
else
file_name = sprintf('%s/icp_pose/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
if strcmp(icp_mode, 'icp_ch')
file_name = sprintf('%s/icp_ch_pose/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
else
file_name = sprintf('%s/icp_pose/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
end
end
% if strcmp(isgframe, 'gframe')
% file_name = sprintf('%s/matched_points_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% else
% file_name = sprintf('%s/matched_points/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% end
save(file_name, 'phi_icp', 'theta_icp', 'psi_icp', 'trans_icp', 'rmse_icp', 'match_num', 'elapsed_icp', 'sta_icp', 'error', 'pose_std');
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm1.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm1.m
| 20,682 |
utf_8
|
70768c121d2c12aee163d99545605f70
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm1(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'primesense')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
%[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
%[img1, x1, y1, z1] = LoadPrimesense_model(dm, cframe);
[img1, x1, y1, z1] = LoadPrimesense_newmodel(dm, cframe);
%[img1, x1, y1, z1] = LoadPrimesense_model(dm, cframe);
% f1 = figure(1);
%imshow(uint8(img1*255));
% f2=figure(2);
% imagesc(z1);
elapsed_pre=0;
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);
%% modify for read data from creative !!!
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
%[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'primesense')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
%[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
%[img2, x2, y2, z2] = LoadPrimesense_model(dm, cframe);
[img2, x2, y2, z2] = LoadPrimesense_newmodel(dm, cframe);
elapsed_pre2=0;
else
%[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
%[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max = 1400; % [m]
valid_dist_min = 450; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'primesense')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > valid_dist_min &&z1(ROW1, COL1)<valid_dist_max&& z2(ROW2, COL2) > valid_dist_min&&z2(ROW2, COL2)<valid_dist_max
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
% col1=SearchColumn(cor_i1,COL1,10);
% row1=SearchRow(cor_j1,ROW1,10); %ADD BY WEI
% col2=SearchColumn(cor_i2,COL2,10);
% row2=SearchRow(cor_j2,ROW2,10); %ADD BY WEI
[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
if col1~=0&&row1~=0&&col2~=0&&row2~=0
temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
% end
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
match_image1(:,cnt_new)=[ROW1 COL1]';
match_image2(:,cnt_new)=[ROW2 COL2]';
match_depth1(:,cnt_new)=[row1 col1]';
match_depth2(:,cnt_new)=[row2 col2]';
cnt_new = cnt_new + 1;
end
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
[n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'primesense')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(row1, col1); op_pset1(2,op_pset_cnt)=z1(row1, col1); op_pset1(3,op_pset_cnt)=y1(row1, col1);
op_pset2(1,op_pset_cnt)=-x2(row2, col2); op_pset2(2,op_pset_cnt)=z2(row2, col2); op_pset2(3,op_pset_cnt)=y2(row2, col2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadSR_no_bpc.m
|
.m
|
slam_matlab-master/Localization/LoadSR_no_bpc.m
| 4,431 |
utf_8
|
4949a8ca77cf111fa99a071ee8736c50
|
% Load data from Swiss Ranger
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
% No bad pixel compensation
function [img, x, y, z, c, rtime] = LoadSR_no_bpc(data_name, filter_name, ...
boarder_cut_off, dm, j, scale, type_value)
% if nargin < 6
% scale = 1;
% end
%apitch=-43+3*dm;
%[prefix, err]=sprintf('../data/d%d_%d/d%d', dm, apitch, dm);
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if j<10
[s, err]=sprintf('%s_000%d.dat', prefix, j);
elseif j<100
[s, err]=sprintf('%s_00%d.dat', prefix, j);
elseif j<1000
[s, err]=sprintf('%s_0%d.dat', prefix, j);
else
[s, err]=sprintf('%s_%d.dat', prefix, j);
end
%t_pre = clock; %cputime;
t_pre = tic;
fw=1;
a = load(s); % elapsed time := 0.2 sec
global g_data_height
k=g_data_height*3+1;
img = double(a(k:k+g_data_height-1, :));
z = a(1:g_data_height, :); x = a(g_data_height+1:2*g_data_height, :);
y = a(2*g_data_height+1:g_data_height*3, :);
% z = medfilt2(z,[fw fw]); x = medfilt2(x, [fw fw]); y = medfilt2(y, [fw fw]);
% [frm, des] = sift(img);
% imwrite(img, 'before_scale.png');
% imshow(img);
confidence_read = 0;
if confidence_read == 1
% c = a(144*4+1:144*5, :);
c = a(g_data_height*4 +1:g_data_height*5, :);
% Apply median filter to a pixel which confidence leve is zero.
%confidence_cut_off = 1;
%[img, x, y, z, c] = compensate_badpixel(img, x, y, z, c, confidence_cut_off);
else
c = 0;
end
%Cut-off on the horizontal boarder
if boarder_cut_off > 0
img=cut_boarder(img,boarder_cut_off);
x=cut_boarder(x,boarder_cut_off);
y=cut_boarder(y,boarder_cut_off);
z=cut_boarder(z,boarder_cut_off);
end
%Scale intensity image to [0 255]
if scale == 1
img = scale_img(img, fw, type_value, 'intensity');
end
% [frm, des] = sift(img);
% imwrite(img, 'after_scale.png');
% imshow(img);
% % Adaptive histogram equalization
img = adapthisteq(img);
% img = histeq(img);
% [frm, des] = sift(img);
% imshow(img);
%filtering
%filter_list={'none','median','gaussian'};
gaussian_h = fspecial('gaussian',[3 3],1); %sigma = 1
gaussian_h_5 = fspecial('gaussian',[5 5],1); %sigma = 1
% filter_name = '';
switch filter_name
case 'median'
img=medfilt2(img, [3 3]);
x=medfilt2(x, [3 3]);
y=medfilt2(y, [3 3]);
z=medfilt2(z, [3 3]);
case 'median5'
img=medfilt2(img, [5 5]);
x=medfilt2(x, [5 5]);
y=medfilt2(y, [5 5]);
z=medfilt2(z, [5 5]);
case 'gaussian'
img=imfilter(img, gaussian_h,'replicate');
% x=imfilter(x, gaussian_h,'replicate');
% y=imfilter(y, gaussian_h,'replicate');
% z=imfilter(z, gaussian_h,'replicate');
case 'gaussian_edge_std'
img=imfilter(img, gaussian_h,'replicate');
x_g=imfilter(x, gaussian_h,'replicate');
y_g=imfilter(y, gaussian_h,'replicate');
z_g=imfilter(z, gaussian_h,'replicate');
x = check_edges(x, x_g);
y = check_edges(y, y_g);
z = check_edges(z, z_g);
case 'gaussian5'
img=imfilter(img, gaussian_h_5,'replicate');
x=imfilter(x, gaussian_h_5,'replicate');
y=imfilter(y, gaussian_h_5,'replicate');
z=imfilter(z, gaussian_h_5,'replicate');
end
% [frm, des] = sift(img);
% imshow(img);
%rtime = etime(clock, t_pre); %cputime - t_pre;
rtime = toc(t_pre);
end
function [img]=cut_boarder(img, cut_off)
image_size=size(img);
h_cut_off_pixel=round(image_size(2)*cut_off/100);
v_cut_off_pixel=round(image_size(1)*cut_off/100);
img(:,(image_size(2)-h_cut_off_pixel+1):image_size(2))=[]; %right side of Horizontal
img(:,1:h_cut_off_pixel)=[]; %left side of Horizontal
img((image_size(1)-v_cut_off_pixel+1):image_size(1),:)=[]; %up side of vertical
img(1:v_cut_off_pixel,:)=[]; %bottom side of vertical
end
function [data] = check_edges(data, data_g)
%edges = 0;
for i = 2:size(data,1)-1
for j= 2:size(data,2)-1
%if var(data(i-1:i+1,j-1:j+1)) <= 0.001
unit_vector = [data(i-1,j-1:j+1) data(i, j-1:j+1) data(i+1, j-1:j+1)];
%if std(unit_vector)/(max(unit_vector) - min(unit_vector)) <= 0.4
if std(unit_vector) <= 0.1
data(i,j) = data_g(i,j);
%else
% edges = edges + 1;
end
end
end
%edges
end
|
github
|
rising-turtle/slam_matlab-master
|
get_motive_filename.m
|
.m
|
slam_matlab-master/Localization/get_motive_filename.m
| 358 |
utf_8
|
94ad2275c9cd7f075b6a46f6861a8908
|
% Get directory name of motive datasets
%
% Author : Soonhac Hong ([email protected])
% Date : 11/20/13
function motive_filename_lists=get_motive_filename()
motive_filename_lists = {'move_forward','swing_forward','move_loop','swing_loop','move_loop_2','move_loop_3','swing_loop_2','m5_loop','m5_loop_2','m5_swing_loop','m5_loop_3','m5_swing_loop_2'};
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_p.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_p.m
| 21,626 |
utf_8
|
e92b786caef4fe42399ac6059bfd97f2
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_p(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
%if strcmp(data_name, 'kinect_tum')
if strcmp(data_name, 'primesense') % change to primesense by wei wu
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
%[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
[img1, x1, y1, z1] = load_primesense(dm, cframe);
%[img1, x1, y1, z1] = LoadPrimesense_model(dm, cframe);
elapsed_pre=0;
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);
%% modify for read data from creative !!!
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
%[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
% if strcmp(data_name, 'kinect_tum')
% %[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
% [img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
if strcmp(data_name, 'primesense') % change to primesense by wei wu
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
%[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
[img2, x2, y2, z2] = load_primesense(dm, cframe);
% [img2, x2, y2, z2] = LoadPrimesense_model(dm, cframe);
elapsed_pre2=0;
else
%[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
%[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max = 1; % [m]
valid_dist_min = 0.350; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
%if strcmp(data_name, 'kinect_tum')
if strcmp(data_name, 'primesense')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) >valid_dist_min && z2(ROW2, COL2) > valid_dist_min&&z1(ROW1, COL1) <valid_dist_max && z2(ROW2, COL2) <valid_dist_max
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
% col1=SearchColumn(cor_i1,COL1,10);
% row1=SearchRow(cor_j1,ROW1,10); %ADD BY WEI
% col2=SearchColumn(cor_i2,COL2,10);
% row2=SearchRow(cor_j2,ROW2,10); %ADD BY WEI
[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
if col1~=0&&row1~=0&&col2~=0&&row2~=0
temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
% end
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
match_image1(:,cnt_new)=[ROW1 COL1]';
match_image2(:,cnt_new)=[ROW2 COL2]';
match_depth1(:,cnt_new)=[row1 col1]';
match_depth2(:,cnt_new)=[row2 col2]';
cnt_new = cnt_new + 1;
end
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2,match_image1,match_image2,match_depth1,match_depth2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
% if strcmp(data_name, 'kinect_tum')
if strcmp(data_name, 'primesense')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(row1, col1); op_pset1(2,op_pset_cnt)=z1(row1, col1); op_pset1(3,op_pset_cnt)=y1(row1, col1);
op_pset2(1,op_pset_cnt)=-x2(row2, col2); op_pset2(2,op_pset_cnt)=z2(row2, col2); op_pset2(3,op_pset_cnt)=y2(row2, col2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
% if strcmp(data_name, 'kinect_tum')
% elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
if strcmp(data_name, 'primesense')
% elapsed = [ elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov.m
| 13,451 |
utf_8
|
05fdb67deba8117bf940baeee024754b
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, dis)
if nargin < 13
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') % Dynamic data
cframe = sframe;
else
cframe = j;
end
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') % Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta == 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
run_ransac_points.m
|
.m
|
slam_matlab-master/Localization/run_ransac_points.m
| 2,268 |
utf_8
|
282c75429fdbf0eb0159f9aac971d395
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% pt1 : point cloud of data set (n x m) n : data dimensionality
% pt2 : point cloud of data set (n x m) n : data dimensionality
% match : match index
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 9/10/12
function [op_match, match_num, rtime, error] = run_ransac_points(pt1, pt2, match, dis)
error = 0;
pnum = size(match, 2);
ransac_error = 0;
if pnum<4
fprintf('too few sift points for ransac.\n');
op_num=0;
op_match=0;
rtime = 0;
match_num = [pnum; op_num];
error=1;
return;
else
t_ransac = tic;
%Standard termination criterion
valid_ransac = 12; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
max_iteration = 120000;
while eta > eta_0
i = i+1;
[n_match, rs_match, cnum] = ransac_gc(pt1, pt2);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
op_num=0;
op_match=0;
rtime = toc(t_ransac);
match_num = [pnum; op_num];
error=2;
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
rtime = toc(t_ransac);
match_num = [pnum; op_num];
end
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadSR.m
|
.m
|
slam_matlab-master/Localization/LoadSR.m
| 3,943 |
utf_8
|
baf1a3a507ef76292082b44303a3d65b
|
% Load data from Swiss Ranger
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
function [img, x, y, z, c, rtime] = LoadSR(data_name, filter_name, boarder_cut_off, dm, j, scale, type_value)
% if nargin < 6
% scale = 1;
% end
%apitch=-43+3*dm;
%[prefix, err]=sprintf('../data/d%d_%d/d%d', dm, apitch, dm);
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if j<10
[s, err]=sprintf('%s_000%d.dat', prefix, j);
elseif j<100
[s, err]=sprintf('%s_00%d.dat', prefix, j);
elseif j<1000
[s, err]=sprintf('%s_0%d.dat', prefix, j);
else
[s, err]=sprintf('%s_%d.dat', prefix, j);
end
%t_pre = clock; %cputime;
t_pre = tic;
fw=1;
a = load(s); % elapsed time := 0.2 sec
k=144*3+1;
img = double(a(k:k+143, :));
z = a(1:144, :); x = a(145:288, :); y = a(289:144*3, :);
z = medfilt2(z,[fw fw]); x = medfilt2(x, [fw fw]); y = medfilt2(y, [fw fw]);
if confidence_read == 1
c = a(144*4+1:144*5, :);
% Apply median filter to a pixel which confidence leve is zero.
confidence_cut_off = 1;
[img, x, y, z, c] = compensate_badpixel(img, x, y, z, c, confidence_cut_off);
else
c = 0;
end
%Cut-off on the horizontal boarder
if boarder_cut_off > 0
img=cut_boarder(img,boarder_cut_off);
x=cut_boarder(x,boarder_cut_off);
y=cut_boarder(y,boarder_cut_off);
z=cut_boarder(z,boarder_cut_off);
end
%Scale intensity image to [0 255]
if scale == 1
img = scale_img(img, fw, type_value, 'intensity');
end
% % Adaptive histogram equalization
%img = adapthisteq(img);
img = histeq(img);
%filtering
%filter_list={'none','median','gaussian'};
gaussian_h = fspecial('gaussian',[3 3],1); %sigma = 1
gaussian_h_5 = fspecial('gaussian',[5 5],1); %sigma = 1
switch filter_name
case 'median'
img=medfilt2(img, [3 3]);
x=medfilt2(x, [3 3]);
y=medfilt2(y, [3 3]);
z=medfilt2(z, [3 3]);
case 'median5'
img=medfilt2(img, [5 5]);
x=medfilt2(x, [5 5]);
y=medfilt2(y, [5 5]);
z=medfilt2(z, [5 5]);
case 'gaussian'
img=imfilter(img, gaussian_h,'replicate');
x=imfilter(x, gaussian_h,'replicate');
y=imfilter(y, gaussian_h,'replicate');
z=imfilter(z, gaussian_h,'replicate');
case 'gaussian_edge_std'
img=imfilter(img, gaussian_h,'replicate');
x_g=imfilter(x, gaussian_h,'replicate');
y_g=imfilter(y, gaussian_h,'replicate');
z_g=imfilter(z, gaussian_h,'replicate');
x = check_edges(x, x_g);
y = check_edges(y, y_g);
z = check_edges(z, z_g);
case 'gaussian5'
img=imfilter(img, gaussian_h_5,'replicate');
x=imfilter(x, gaussian_h_5,'replicate');
y=imfilter(y, gaussian_h_5,'replicate');
z=imfilter(z, gaussian_h_5,'replicate');
end
%rtime = etime(clock, t_pre); %cputime - t_pre;
rtime = toc(t_pre);
end
function [img]=cut_boarder(img, cut_off)
image_size=size(img);
h_cut_off_pixel=round(image_size(2)*cut_off/100);
v_cut_off_pixel=round(image_size(1)*cut_off/100);
img(:,(image_size(2)-h_cut_off_pixel+1):image_size(2))=[]; %right side of Horizontal
img(:,1:h_cut_off_pixel)=[]; %left side of Horizontal
img((image_size(1)-v_cut_off_pixel+1):image_size(1),:)=[]; %up side of vertical
img(1:v_cut_off_pixel,:)=[]; %bottom side of vertical
end
function [data] = check_edges(data, data_g)
%edges = 0;
for i = 2:size(data,1)-1
for j= 2:size(data,2)-1
%if var(data(i-1:i+1,j-1:j+1)) <= 0.001
unit_vector = [data(i-1,j-1:j+1) data(i, j-1:j+1) data(i+1, j-1:j+1)];
%if std(unit_vector)/(max(unit_vector) - min(unit_vector)) <= 0.4
if std(unit_vector) <= 0.1
data(i,j) = data_g(i,j);
%else
% edges = edges + 1;
end
end
end
%edges
end
|
github
|
rising-turtle/slam_matlab-master
|
get_dir_name.m
|
.m
|
slam_matlab-master/Localization/get_dir_name.m
| 2,093 |
utf_8
|
f5ada152c3bd0fa001f52118d5833176
|
% Get directory name of each data se
%
% Author : Soonhac Hong ([email protected])
% Date : 4/4/13
function dir_name = get_dir_name(data_name)
switch data_name
case 'c1'
dir_name = {'0','y-3_p6_x100','y-12_p9_x300','y-6_p12_x500'};
case 'c2'
dir_name = {'0','y-6_p3_y200','y-9_p12_y400','y-12_p6_y600'};
case 'c3'
dir_name = {'0','y3_p12_x100','y6_p9_x200','y9_p6_x300','y12_p3_x400'};
case 'c4'
dir_name = {'0','y-3_p9_y300'};
case 'm'
dir_name={'pitch_3degree','pitch_9degree','pan_3degree','pan_9degree','pan_30degree','pan_60degree','roll_3degree','roll_9degree','x_30mm','x_150mm','x_300mm','y_30mm','y_150mm','y_300mm','square_500','square_700','square_swing','square_1000','test'};
case 'etas'
dir_name = {'3th_straight','3th_swing','4th_straight','4th_swing','5th_straight','5th_swing'};
case 'loops'
dir_name = {'bus','bus_3','bus_door_straight_150','bus_straight_150','data_square_small_100','eit_data_150','exp1','exp2','exp3','exp4','exp5','lab_80_dynamic_1','lab_80_swing_1','lab_it_80','lab_lookforward_4','s2','second_floor_150_not_square','second_floor_150_square','second_floor_small_80_swing','third_floor_it_150'};
case 'loops2'
dir_name = get_loops2_filename();
case 'sparse_feature'
dir_name = get_sparse_feature_filename();
case {'swing', 'swing2'}
dir_name = get_swing_filename(); %{'forward1','forward2','forward3','forward4','forward5','forward6','forward7_10m','forward8_10m', 'forward9_10m','forward10_10m','forward11_10m','forward12_10m','forward13_10m','forward14_10m','forward15_10m'};
case {'object_recognition'}
dir_name = {'floor1','indoor_monitor_1','indoor_doorway_1','indoor_monitor_2','indoor_stairway_1','indoor_stairway_2', 'indoor_stairway_3', 'indoor_stairway_4', 'indoor_stairway_5', 'indoor_monitor_3', 'indoor_monitor_4'};
case {'motive'}
dir_name = get_motive_filename();
case {'kinect_tum'}
dir_name = get_kinect_tum_dir_name();
otherwise
dir_name = {'none'};
end
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm2.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm2.m
| 20,597 |
utf_8
|
20cef817a6696c63b8f58ea860601567
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm2(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'primesense')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
%[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
[img1, x1, y1, z1] = LoadPrimesense_model(dm, cframe);
elapsed_pre=0;
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);
%% modify for read data from creative !!!
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
%[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'primesense')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
%[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
[img2, x2, y2, z2] = LoadPrimesense_model(dm, cframe);
elapsed_pre2=0;
else
%[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
%[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max = 1000; % [m]
valid_dist_min = 150; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'primesense')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
% col1=SearchColumn(cor_i1,COL1,10);
% row1=SearchRow(cor_j1,ROW1,10); %ADD BY WEI
% col2=SearchColumn(cor_i2,COL2,10);
% row2=SearchRow(cor_j2,ROW2,10); %ADD BY WEI
[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
if col1~=0&&row1~=0&&col2~=0&&row2~=0
temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
% end
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
match_image1(:,cnt_new)=[ROW1 COL1]';
match_image2(:,cnt_new)=[ROW2 COL2]';
match_depth1(:,cnt_new)=[row1 col1]';
match_depth2(:,cnt_new)=[row2 col2]';
cnt_new = cnt_new + 1;
end
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
[n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2,match_image1,match_image2,match_depth1,match_depth2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'primesense')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(row1, col1); op_pset1(2,op_pset_cnt)=z1(row1, col1); op_pset1(3,op_pset_cnt)=y1(row1, col1);
op_pset2(1,op_pset_cnt)=-x2(row2, col2); op_pset2(2,op_pset_cnt)=z2(row2, col2); op_pset2(3,op_pset_cnt)=y2(row2, col2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'primesense')
%elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
save_pose_std.m
|
.m
|
slam_matlab-master/Localization/save_pose_std.m
| 1,374 |
utf_8
|
94abed80c2732098f1ef02641015c5f9
|
% Save matched points into a file
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, isgframe, sequence_data)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
if strcmp(isgframe, 'gframe')
file_name = sprintf('%s/pose_std_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
else
file_name = sprintf('%s/pose_std/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
if strcmp(isgframe, 'gframe')
file_name = sprintf('%s/pose_std_gframe/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
else
file_name = sprintf('%s/pose_std/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
end
end
% if strcmp(isgframe, 'gframe')
% file_name = sprintf('%s/matched_points_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% else
% file_name = sprintf('%s/matched_points/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% end
save(file_name, 'pose_std');
end
|
github
|
rising-turtle/slam_matlab-master
|
check_stored_icp_pose.m
|
.m
|
slam_matlab-master/Localization/check_stored_icp_pose.m
| 1,201 |
utf_8
|
7af72ceae02de07502cf86983c93c78b
|
% Check if there is the stored matched points
%
% Author : Soonhac Hong ([email protected])
% Date : 8/12/2013
function [exist_flag] = check_stored_icp_pose(data_name, dm, first_cframe, second_cframe, icp_mode, sequence_data)
exist_flag = 0;
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
dataset_dir = strrep(prefix, '/d1','');
file_name = sprintf('d1_%04d_%04d.mat',first_cframe, second_cframe);
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
file_name = sprintf('d1_%04d_d%d_%04d.mat',first_cframe, dm, second_cframe);
end
if strcmp(icp_mode, 'icp_ch')
dataset_dir = sprintf('%s/icp_ch_pose',dataset_dir);
else
dataset_dir = sprintf('%s/icp_pose',dataset_dir);
end
%file_name = sprintf('d1_%04d_%04d.mat',first_cframe, second_cframe);
dirData = dir(dataset_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
if isempty(file_list)
return;
else
for i=1:size(file_list,1)
if strcmp(file_list{i}, file_name)
exist_flag = 1;
break;
end
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_icp2_cov_fast_fast_dist.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_icp2_cov_fast_fast_dist.m
| 20,434 |
utf_8
|
c03980c62e56add66fadbcc1d0662a38
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 8/30/12
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_icp2_cov_fast_fast_dist(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, icp_mode, dis)
if nargin < 14
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') % Dynamic data
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
%[frm1,des1] = vl_sift(single(img1)) ;
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature')% Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
%[frm2,des2] = vl_sift(single(img2)) ;
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe,'none') == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%[match, scores] = vl_ubcmatch(des1,des2) ;
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= 0 && img2(ROW2, COL2) >= 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
% stdev_threshold = 0.1;
% stdev_count = 0;
% count_threshold = 15;
% mean_threshold = 0.1;
% mean_count = 0;
% window_size = 30;
% debug_data=[];
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% if cnum >= valid_ransac
% break;
% end
% if cnum/pnum >= inlier_ratio
% break;
% enddynamic_data_index
% total_cnum(i)=cnum;
% if i > window_size && inliers_std ~= 0
% inliers_std_prev = inliers_std;
% inliers_std = std(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_std_delta = abs(inliers_std - inliers_std_prev)/inliers_std_prev;
%
% inliers_mean_prev = inliers_mean;
% inliers_mean = mean(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_mean_delta = abs(inliers_mean - inliers_mean_prev)/inliers_mean_prev;
%
% if inliers_std_delta < stdev_threshold
% stdev_count = stdev_count + 1;
% else
% stdev_count = 0;
% end
%
% if inliers_mean_delta < mean_threshold
% mean_count = mean_count + 1;
% else
% mean_count = 0;
% end
%
% inlier_ratio = max(total_cnum)/pnum;
% % count_threshold = 120000 / ((inlier_ratio*100)^2); %-26 * (inlier_ratio*100 - 20) + 800;
%
% if stdev_count > count_threshold %&& mean_count > count_threshold
% break;
% end
% else
% inliers_std = std(total_cnum);
% inliers_mean = mean(total_cnum);
% end
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%% Run SVD
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2,'none');
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe,'none');
t_svd = tic;
end
[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
tmp_rsmatch = [];
tmp_cnum = [];
tmp_nmatch = [];
op_match = [];
%Test LM
%[rot_lm, trans_lm] = lm_point(op_pset1, op_pset2);
% [rot_lm, trans_lm] = lm_point2plane(op_pset1, op_pset2);
% [phi_lm, theta_lm, psi_lm] = rot_to_euler(rot_lm);
% [theta*180/pi theta_lm*180/pi]
% [phi*180/pi phi_lm*180/pi]
% [psi*180/pi psi_lm*180/pi]
% Save feature points
%feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
% Compute RMSE
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse = rmse + unit_rmse;
% end
% rmse_feature = rmse / size(op_pset1,2);
%rmse_feature = rms_error(op_pset1, op_pset2_transed);
% Show correspondent points
% plot3(op_pset1(1,:),op_pset1(2,:),op_pset1(3,:),'b*-');
% hold on;
% plot3(op_pset2(1,:),op_pset2(2,:),op_pset2(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
%Compute the elapsed time
%rt_total = etime(clock,t);
%elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
%% Run ICP
%[phi_icp, theta_icp, psi_icp, trans_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_2(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_3(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_4(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_5(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
if strcmp(icp_mode, 'icp_ch')
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch_dist(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
else
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_6_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
end
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_10(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_13(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%Check status of SVD
if sta_icp == 0 || error ~= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta_icp == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%elapsed_icp = toc(t_icp);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
%rot = rot_icp;
% [rmse_feature rmse_icp]
% [theta*180/pi theta_icp*180/pi]
% [trans(1) trans_icp(1)]
%if rmse_icp <= rmse_feature
trans = trans_icp;
phi = phi_icp;
theta = theta_icp;
psi = psi_icp;
%end
%convert degree
% r2d=180.0/pi;
% phi=phi*r2d;
% theta=theta*r2d;
% psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc.m
| 17,547 |
utf_8
|
cc4c56a90ef6a409e2b616c1da08c397
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% distance filtering
if is_10M_data == 1
valid_dist_max = 8; % 5m
else
valid_dist_max = 5; % 5m
end
valid_dist_min = 0.8; % 0.8m
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
t_svd = tic;
end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
else
[pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_addpath.m
|
.m
|
slam_matlab-master/Localization/localization_addpath.m
| 433 |
utf_8
|
e55d2d7d14b2ebe4c14e678200670c35
|
% Add the path for graph slam
%
% Author : Soonhac Hong ([email protected])
% Date : 10/16/12
function localization_addpath
addpath('D:\Soonhac\SW\icp');
addpath('D:\Soonhac\SW\kdtree');
addpath('D:\Soonhac\SW\LevenbergMarquardt');
addpath('D:\Soonhac\SW\SIFT\sift-0.9.19-bin\sift');
%addpath('D:\Soonhac\SW\GradientConcensus');
%addpath('D:\Soonhac\SW\OpenSURF_version1c');
%addpath('E:\data\Amir\code\code3\code_from_dr_ye');
end
|
github
|
rising-turtle/slam_matlab-master
|
save_matched_points.m
|
.m
|
slam_matlab-master/Localization/save_matched_points.m
| 1,099 |
utf_8
|
a1d872acde1b9be2e749a1768097b780
|
% Save matched points into a file
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, isgframe, sequence_data)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
end
if strcmp(isgframe, 'gframe')
file_name = sprintf('%s/matched_points_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
else
file_name = sprintf('%s/matched_points/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
end
save(file_name, 'match_num', 'ransac_iteration', 'op_pset1_image_index', 'op_pset2_image_index', 'op_pset_cnt', 'elapsed_match', 'elapsed_ransac', 'op_pset1', 'op_pset2');
end
|
github
|
rising-turtle/slam_matlab-master
|
get_kinect_tum_dir_name_vro_cpp.m
|
.m
|
slam_matlab-master/Localization/get_kinect_tum_dir_name_vro_cpp.m
| 355 |
utf_8
|
4dd3f8a1ba991e4517e0073c27ad290d
|
% Get directory name of kinect_tum data set
%
% Parameters
% dm : index of directory of data
%
% Author : Soonhac Hong ([email protected])
% Date : 9/25/12
function [dir_name_list]=get_kinect_tum_dir_name()
dir_name_list={'freiburg1_xyz','freiburg1_floor','freiburg2_large_no_loop','freiburg2_large_with_loop'};
%dir_name=dir_name_list{dir_index};
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadKinect.m
|
.m
|
slam_matlab-master/Localization/LoadKinect.m
| 1,839 |
utf_8
|
45cf2fbc839ba26005f6f0a47ddc3e1d
|
% Load data from Kinect
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
function [img, X, Y, Z, rtime] = LoadKinect(dm, j)
t_load = tic;
dir_name = get_kinect_tum_dir_name();
[rgb_data_dir, err] = sprintf('E:/data/kinect_tum/%s/rgb',dir_name{dm});
dirData = dir(rgb_data_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
[file_name, err]=sprintf('%s/%s',rgb_data_dir,file_list{j});
rgb_img = imread(file_name);
img = rgb2gray(rgb_img);
%figure;imshow(rgb_img);
%figure;imshow(img);
%Noise reduction by Gaussian filter
gaussian_h = fspecial('gaussian',[3 3],1);
img=imfilter(img, gaussian_h,'replicate');
[depth_data_dir, err] = sprintf('E:/data/kinect_tum/%s/depth',dir_name{dm});
dirData = dir(depth_data_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
[file_name, err]=sprintf('%s/%s',depth_data_dir,file_list{j});
depth_img = imread(file_name);
%figure;imshow(depth_img);
depth_img = double(depth_img);
fx = 525.0; %# focal length x
fy = 525.0; %# focal length y
cx = 319.5; %# optical center x
cy = 239.5; %# optical center y
ds = 1.0; %# depth scaling
factor = 5000.0; %# for the 16-bit PNG files
%# OR: factor = 1 %# for the 32-bit float images in the ROS bag files
for v=1:size(depth_img,1) %height
for u=1:size(depth_img,2) %width
z = (depth_img(v,u) / factor) * ds;
x = (u - cx) * z / fx;
y = (v - cy) * z / fy;
X(v,u) = x;
Y(v,u) = y;
Z(v,u) = z;
end
end
rtime = toc(t_load);
%figure;imagesc(X);
%figure;imagesc(Y);
%figure;imagesc(Z);
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadPrimesense_model.m
|
.m
|
slam_matlab-master/Localization/LoadPrimesense_model.m
| 4,098 |
utf_8
|
c81de6acde2583247da4ac18a068adff
|
% Load data from Kinect
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
function [img, X, Y, Z] = LoadPrimesense_model(dm, file_index)
%t_load = tic;
%dir_name_list = get_kinect_tum_dir_name();
%dir_name = dir_name_list{dm};
% Load depth image
%[depth_data_dir, err] = sprintf('D:/Soonhac/Data/kinect_tum/%s/depth',dir_name);
%dirData = dir(depth_data_dir); %# Get the data for the current directory
%dirIndex = [dirData.isdir]; %# Find the index for directories
%file_list = {dirData(~dirIndex).name}';
%[file_name_full, err]=sprintf('%s/%s',depth_data_dir,file_list{j});
%[file_name, err] = sprintf('%s',file_list{j});
%depth_time_stamp = str2double(strrep(file_name, '.png',''));
%depth_img = imread(file_name_full);
%figure;imshow(depth_img);
%depth_img = double(depth_img);
if file_index<11
z_file_name=sprintf('D:/image/prime/12mm_primesense_registered2/image%d/depth/00%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/prime/12mm_primesense_registered2/image%d/rgb/00%d.png',dm-1,file_index-1);
%x_file_name=sprintf('D:/image/image%d/depth/00%dx.dat',dm-1,file_index-1);
%y_file_name=sprintf('D:/image/image%d/depth/00%dy.dat',dm-1,file_index-1);
elseif file_index<101
z_file_name=sprintf('D:/image/prime/12mm_primesense_registered2/image%d/depth/0%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/prime/12mm_primesense_registered2/image%d/rgb/0%d.png',dm-1,file_index-1);
%x_file_name=sprintf('D:/image/image%d/depth/0%dx.dat',dm-1,file_index-1);
% y_file_name=sprintf('D:/image/image%d/depth/0%dy.dat',dm-1,file_index-1);
elseif file_index<605
z_file_name=sprintf('D:/image/prime/12mm_primesense_registered2/image%d/depth/%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/prime/12mm_primesense_registered2/image%d/rgb/%d.png',dm-1,file_index-1);
% x_file_name=sprintf('D:/image/image%d/depth/%dx.dat',dm-1,file_index-1);
% y_file_name=sprintf('D:/image/image%d/depth/%dy.dat',dm-1,file_index-1);
end
depth_img=imread(z_file_name);
depth_img=double(depth_img);
img1=imread(img_file_name);
img=rgb2gray(img1);
img=im2double(img);
% center=[320,240];
% [imh, imw] = size(depth_img);
% %constant = 570.3;
% constant = 573; %constant = focal;
% factor=1;
% % convert depth image to 3d point clouds
% %pclouds = zeros(imh,imw,3);
% xgrid = ones(imh,1)*(1:imw) - center(1);
% ygrid = (1:imh)'*ones(1,imw) - center(2);
% X = xgrid.*depth_img/constant/factor;
% Y = ygrid.*depth_img/constant/factor;
% Z = depth_img/factor;
fx = 543.0; %# focal length x
fy = 543.0; %# focal length y
cx = 319.5; %# optical center x
cy = 239.5; %# optical center y
ds = 1.0; %# depth scaling
factor = 1; %# for the 16-bit PNG files
%# OR: factor = 1 %# for the 32-bit float images in the ROS bag files
for v=1:size(depth_img,1) %height
for u=1:size(depth_img,2) %width
z = (depth_img(v,u) / factor) * ds;
x = (u - cx) * z / fx;
y = (v - cy) * z / fy;
X(v,u) = x;
Y(v,u) = y;
Z(v,u) = z;
end
end
% distance = sqrt(sum(pclouds.^2,3));
%rgb_img = imread(file_name);
%img = rgb2gray(rgb_img);
%figure;imshow(rgb_img);
%figure;imshow(img);
%Noise reduction by Gaussian filter
%gaussian_h = fspecial('gaussian',[3 3],1);
%img=imfilter(img, gaussian_h,'replicate');
% fx = 570.3; %# focal length x 551.0/420
% fy = 570.3; %# focal length y 548.0/420
% cx = 320; %# optical center x //319.5
% cy = 240; %# optical center y ///239.5
% ds = 1.0; %# depth scaling
%
% factor = 1; %# for the 16-bit PNG files
% % %# OR: factor = 1 %# for the 32-bit float images in the ROS bag files
% %
% for v=1:size(depth_img,1) %height
% for u=1:size(depth_img,2) %width
% z = (depth_img(v,u) / factor) * ds;
% x = (u - cx) * z / fx;
% y = (v - cy) * z / fy;
% X(v,u) = x;
% Y(v,u) = y;
% Z(v,u) = z;
% end
% end
%rtime = toc(t_load);
%figure;imagesc(X);
%figure;imagesc(Y);
%figure;imagesc(Z);
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_c.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_c.m
| 20,151 |
utf_8
|
1e5a7c5bc4ebf2876f8d7c79555abe21
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_c(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);
%% modify for read data from creative !!!
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
%[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
%[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
%[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max = 1000; % [m]
valid_dist_min = 150; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
% col1=SearchColumn(cor_i1,COL1,10);
% row1=SearchRow(cor_j1,ROW1,10); %ADD BY WEI
% col2=SearchColumn(cor_i2,COL2,10);
% row2=SearchRow(cor_j2,ROW2,10); %ADD BY WEI
[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
if col1~=0&&row1~=0&&col2~=0&&row2~=0
temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
% end
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
match_image1(:,cnt_new)=[ROW1 COL1]';
match_image2(:,cnt_new)=[ROW2 COL2]';
match_depth1(:,cnt_new)=[row1 col1]';
match_depth2(:,cnt_new)=[row2 col2]';
cnt_new = cnt_new + 1;
end
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
[n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,match_image1,match_image2,match_depth1,match_depth2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(row1, col1); op_pset1(2,op_pset_cnt)=z1(row1, col1); op_pset1(3,op_pset_cnt)=y1(row1, col1);
op_pset2(1,op_pset_cnt)=-x2(row2, col2); op_pset2(2,op_pset_cnt)=z2(row2, col2); op_pset2(3,op_pset_cnt)=y2(row2, col2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
plotmatches_multi.m
|
.m
|
slam_matlab-master/Localization/plotmatches_multi.m
| 10,894 |
utf_8
|
1abc9136006be4112288feadc80f61fa
|
function h=plotmatches_multi(I1,I2,P1,P2,matches,matches2,varargin)
% PLOTMATCHES Plot keypoint matches
% PLOTMATCHES(I1,I2,P1,P2,MATCHES) plots the two images I1 and I2
% and lines connecting the frames (keypoints) P1 and P2 as specified
% by MATCHES.
%
% P1 and P2 specify two sets of frames, one per column. The first
% two elements of each column specify the X,Y coordinates of the
% corresponding frame. Any other element is ignored.
%
% MATCHES specifies a set of matches, one per column. The two
% elementes of each column are two indexes in the sets P1 and P2
% respectively.
%
% The images I1 and I2 might be either both grayscale or both color
% and must have DOUBLE storage class. If they are color the range
% must be normalized in [0,1].
%
% The function accepts the following option-value pairs:
%
% 'Stacking' ['h']
% Stacking of images: horizontal ['h'], vertical ['v'], diagonal
% ['h'], overlap ['o']
%
% 'Interactive' [0]
% If set to 1, starts the interactive session. In this mode the
% program lets the user browse the matches by moving the mouse:
% Click to select and highlight a match; press any key to end.
% If set to a value greater than 1, the feature matches are not
% drawn at all (useful for cluttered scenes).
%
% See also PLOTSIFTDESCRIPTOR(), PLOTSIFTFRAME(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
stack='h' ;
interactive=0 ;
only_interactive=0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'stacking'
stack=varargin{k+1} ;
case 'interactive'
interactive=varargin{k+1};
otherwise
error(['[Unknown option ''', varargin{k}, '''.']) ;
end
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
[M1,N1,K1]=size(I1) ;
[M2,N2,K2]=size(I2) ;
switch stack
case 'h'
N3=N1+N2 ;
M3=max(M1,M2) ;
oj=N1 ;
oi=0 ;
case 'v'
M3=M1+M2 ;
N3=max(N1,N2) ;
oj=0 ;
oi=M1 ;
case 'd'
M3=M1+M2 ;
N3=N1+N2 ;
oj=N1 ;
oi=M1 ;
case 'o'
M3=max(M1,M2) ;
N3=max(N1,N2) ;
oj=0;
oi=0;
otherwise
error(['Unkown stacking type '''], stack, ['''.']) ;
end
% Combine the two images. In most cases just place one image next to
% the other. If the stacking is 'o', however, combine the two images
% linearly.
I=zeros(M3,N3,K1) ;
if stack ~= 'o'
I(1:M1,1:N1,:) = I1 ;
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
else
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
I(1:M1,1:N1,:) = I(1:M1,1:N1,:) + I1 ;
I(1:min(M1,M2),1:min(N1,N2),:) = 0.5 * I(1:min(M1,M2),1:min(N1,N2),:) ;
end
axes('Position', [0 0 1 1]) ;
imagesc(I) ; colormap gray ; hold on ; axis image ; axis off ;
K = size(matches, 2) ;
nans = NaN * ones(1,K) ;
x = [ P1(1,matches(1,:)) ; P2(1,matches(2,:))+oj ; nans ] ;
y = [ P1(2,matches(1,:)) ; P2(2,matches(2,:))+oi ; nans ] ;
% if interactive > 1 we do not drive lines, but just points.
if(interactive > 1)
h = plot(x(:),y(:),'g.') ;
else
h = line(x(:)', y(:)') ;
end
set(h,'Marker','.','Color','g') ;
new_matches = [];
for k = 1:size(matches2,2)
[row, col] = find(matches == matches2(1,k));
if size(row,1) ~= 0
for m = 1: size(row,2)
if matches(2, col(1,m)) ~= matches2(2, k)
new_matches = [new_matches matches2(:,K)];
end
end
else
new_matches = [new_matches matches2(:,k)];
end
end
K = size(new_matches, 2) ;
nans = NaN * ones(1,K) ;
x = [ P1(1,new_matches(1,:)) ; P2(1,new_matches(2,:))+oj ; nans ] ;
y = [ P1(2,new_matches(1,:)) ; P2(2,new_matches(2,:))+oi ; nans ] ;
% if interactive > 1 we do not drive lines, but just points.
if(interactive > 1)
h = plot(x(:),y(:),'r.') ;
else
h = line(x(:)', y(:)') ;
end
set(h,'Marker','.','Color','r') ;
% --------------------------------------------------------------------
% Interactive
% --------------------------------------------------------------------
if(~interactive), return ; end
sel1 = unique(matches(1,:)) ;
sel2 = unique(matches(2,:)) ;
K1 = length(sel1) ; %size(P1,2) ;
K2 = length(sel2) ; %size(P2,2) ;
X = [ P1(1,sel1) P2(1,sel2)+oj ;
P1(2,sel1) P2(2,sel2)+oi ; ] ;
fig = gcf ;
is_hold = ishold ;
hold on ;
% save the handlers for later to restore
dhandler = get(fig,'WindowButtonDownFcn') ;
uhandler = get(fig,'WindowButtonUpFcn') ;
mhandler = get(fig,'WindowButtonMotionFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'KeyPressFcn', @key_handler) ;
set(fig,'WindowButtonDownFcn',@click_down_handler) ;
set(fig,'WindowButtonUpFcn', @click_up_handler) ;
set(fig,'Pointer','crosshair') ;
data.exit = 0 ; % signal exit to the interactive mode
data.selected = [] ; % currently selected feature
data.X = X ; % feature anchors
highlighted = [] ; % currently highlighted feature
hh = [] ; % hook of the highlight plot
guidata(fig,data) ;
while ~ data.exit
uiwait(fig) ;
data = guidata(fig) ;
if(any(size(highlighted) ~= size(data.selected)) || ...
any(highlighted ~= data.selected) )
highlighted = data.selected ;
% delete previous highlight
if( ~isempty(hh) )
delete(hh) ;
end
hh=[] ;
% each selected feature uses its own color
c=1 ;
colors=[1.0 0.0 0.0 ;
0.0 1.0 0.0 ;
0.0 0.0 1.0 ;
1.0 1.0 0.0 ;
0.0 1.0 1.0 ;
1.0 0.0 1.0 ] ;
% more than one feature might be seleted at one time...
for this=highlighted
% find matches
if( this <= K1 )
sel=find(matches(1,:)== sel1(this)) ;
else
sel=find(matches(2,:)== sel2(this-K1)) ;
end
K=length(sel) ;
% plot matches
x = [ P1(1,matches(1,sel)) ; P2(1,matches(2,sel))+oj ; nan*ones(1,K) ] ;
y = [ P1(2,matches(1,sel)) ; P2(2,matches(2,sel))+oi ; nan*ones(1,K) ] ;
hh = [hh line(x(:)', y(:)',...
'Marker','*',...
'Color',colors(c,:),...
'LineWidth',3)];
if( size(P1,1) == 4 )
f1 = unique(P1(:,matches(1,sel))','rows')' ;
hp=plotsiftframe(f1);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
if( size(P2,1) == 4 )
f2 = unique(P2(:,matches(2,sel))','rows')' ;
f2(1,:)=f2(1,:)+oj ;
f2(2,:)=f2(2,:)+oi ;
hp=plotsiftframe(f2);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
c=c+1 ;
end
drawnow ;
end
end
if( ~isempty(hh) )
delete(hh) ;
end
if ~is_hold
hold off ;
end
set(fig,'WindowButtonDownFcn', dhandler) ;
set(fig,'WindowButtonUpFcn', uhandler) ;
set(fig,'WindowButtonMotionFcn',mhandler) ;
set(fig,'KeyPressFcn', khandler) ;
set(fig,'Pointer', pointer ) ;
% ====================================================================
function data=selection_helper(data)
% --------------------------------------------------------------------
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
d = (data.X(1,:) - P(1)).^2 + (data.X(2,:) - P(2)).^2 ;
dmin=min(d) ;
idx=find(d==dmin) ;
data.selected = idx ;
% ====================================================================
function click_down_handler(obj,event)
% --------------------------------------------------------------------
% select a feature and change motion handler for dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
data.mhandler = get(fig,'WindowButtonMotionFcn') ;
set(fig,'WindowButtonMotionFcn',@motion_handler) ;
data = selection_helper(data) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function click_up_handler(obj,event)
% --------------------------------------------------------------------
% stop dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
set(fig,'WindowButtonMotionFcn',data.mhandler) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function motion_handler(obj,event)
% --------------------------------------------------------------------
% select features while dragging
data = guidata(obj) ;
data = selection_helper(data);
guidata(obj,data) ;
uiresume(obj) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
% use keypress to exit
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
rising-turtle/slam_matlab-master
|
load_depth_features.m
|
.m
|
slam_matlab-master/Localization/load_depth_features.m
| 397 |
utf_8
|
73b869902c9029fed3f113649c1e42e6
|
% Load sift visual feature from a file
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function [depth_frm, depth_des, depth_ct] = load_depth_features(data_name, dm, cframe)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
dataset_dir = strrep(prefix, '/d1','');
file_name = sprintf('%s/depth_feature/d1_%04d.mat',dataset_dir, cframe);
load(file_name);
end
|
github
|
rising-turtle/slam_matlab-master
|
check_feature_distance.m
|
.m
|
slam_matlab-master/Localization/check_feature_distance.m
| 1,190 |
utf_8
|
17b466611fb0573eb8e7667c8b2663d2
|
% Check the distance of feaure points
%
% Author : Soonhac Hong ([email protected])
% Date : 4/5/13
function [op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index)
distance_min = 0.8;
distance_max = 5;
op_pset1_distance = sqrt(sum(op_pset1.^2));
op_pset2_distance = sqrt(sum(op_pset2.^2));
op_pset1_distance_flag = (op_pset1_distance < distance_min | op_pset1_distance > distance_max);
op_pset2_distance_flag = (op_pset2_distance < distance_min | op_pset2_distance > distance_max);
%debug
if sum(op_pset1_distance_flag) > 0 || sum(op_pset2_distance_flag) > 0
disp('Distance filter is working');
op_pset_cnt = op_pset_cnt - max(sum(op_pset1_distance_flag),sum(op_pset2_distance_flag));
end
op_pset1(:, (op_pset1_distance_flag|op_pset2_distance_flag))=[]; % delete invalid feature points
op_pset2(:, (op_pset1_distance_flag|op_pset2_distance_flag))=[]; % delete invalid feature points
op_pset1_image_index((op_pset1_distance_flag'|op_pset2_distance_flag'),:) = [];
op_pset2_image_index((op_pset1_distance_flag'|op_pset2_distance_flag'),:) = [];
end
|
github
|
rising-turtle/slam_matlab-master
|
get_nframe_nvro_npose.m
|
.m
|
slam_matlab-master/Localization/get_nframe_nvro_npose.m
| 8,552 |
utf_8
|
43e0c79509f888ceba43d604a05d6259
|
% Get nFrame, vro_size, pose_size
%
% Author : Soonhac Hong ([email protected])
% Date : 8/9/13
function [nFrame, vro_size, pose_size, vro_icp_size, pose_vro_icp_size, vro_icp_ch_size, pose_vro_icp_ch_size] = get_nframe_nvro_npose(file_index, dynamic_index)
%% nFrame list
etas_nFrame_list = [979 1488 988 1979 1889]; %[3rd_straight, 3rd_swing, 4th_straigth, 4th_swing, 5th_straight, 5th_swing]
loops_nFrame_list = [0 1359 2498 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2669];
kinect_tum_nFrame_list = [0 98 0 0];
m_nFrame_list = [0 5414 0 729];
sparse_feature_nFrame_list = [232 198 432 365 277 413 0 206 235 0 706 190 275 358 290 578];
swing_nFrame_list = [271 322 600 534 530 334 381 379 379 381 381 299 365 248 245 249 220 245 249 302 399 389 489 446 383 486];
swing2_nFrame_list = [99 128 221 176 210 110];
motive_nFrame_list =[82 145 231 200 227 260 254 236 196 242 184 186];
object_recognition_nFrame_list =[998 498 498 498 398 398 398 848 848 798 848];
%% vro size list
%etas_vro_size_list = [1940 0 1665 0 9490 0]; % NMMP < 13
etas_vro_size_list = [2629 0 1665 0 9490 0]; % NMMP < 6
%etas_vro_size_list_vro_icp_ch = [1938 0 1665 0 9490 0]; % NMMP < 13
etas_vro_size_list_vro_icp_ch = [2475 0 1665 0 9490 0]; % NMMP < 6
%etas_pose_size_list = [919 0 1665 0 9490 0]; % NMMP < 13
etas_pose_size_list = [964 0 1665 0 9490 0]; % NMMP < 6
%etas_pose_size_list_vro_icp_ch = [919 0 1665 0 9490 0]; % NMMP < 13
etas_pose_size_list_vro_icp_ch = [954 0 1665 0 9490 0];% NMMP < 6
loops_vro_size_list = [0 13098 12476 0 0 0 0 0 0 0 0 0 0 0 0 0 0 26613];
kinect_tum_vro_size_list = [0 98 0 0];
sparse_feature_vro_size_list_vro = [814 689 1452 1716 851 2104 0 483 0 0 4438 0 0 0 0 4939]; %232
sparse_feature_vro_size_list_vro_icp = [926 0 1783 365 1153 2328 0 674 0 0 4122 0 0 0 0 0]; %926 232
sparse_feature_vro_size_list_vro_icp_ch = [874 762 1616 1889 1153 2308 0 575 0 0 4738 0 0 0 0 5187];% 896 232 2040
sparse_feature_pose_size_list_vro = [232 195 432 364 258 408 0 184 0 0 701 0 0 0 0 576];
sparse_feature_pose_size_list_vro_icp = [232 0 432 365 274 413 0 201 0 0 708 0 0 0 0 0];
sparse_feature_pose_size_list_vro_icp_ch = [232 197 432 365 274 410 0 195 0 0 703 0 0 0 0 578]; %410
swing_vro_size_list_vro = [1525 1230 432 363 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
swing_vro_size_list_vro_icp = [1943 1815 1783 365 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; %232
swing_vro_size_list_vro_icp_ch = [1790 1437 1650 365 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]; %1494
swing_pose_size_list = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
swing_pose_size_list_vro_icp = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
swing_pose_size_list_vro_icp_ch = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0];
swing2_vro_size_list_vro = [171 0 0 0];
swing2_vro_size_list_vro_icp = [236 0 0 0]; %232
swing2_vro_size_list_vro_icp_ch = [206 0 0 0]; %1494
swing2_pose_size_list = [99 0 0 0];
loops2_nFrame_list = [830 582 830 832 649 930 479 580 699 458 368 239];
%loops2_nFrame_list = [830 0 832 832 649 932 479 580 699 458 398 239]; %2498 578
loops2_vro_size_list = [9508 7344 8915 7341 9157 5278 2777 9485 6435 4465 3035 673]; %4145 5754 with static5
%loops2_vro_size_list = [10792 9468 11700 7341 9157 5278 2777 9485 6435 4465 3035 673]; %4145 5754
loops2_vro_size_list_vro_icp = [830 0 11293 7427 649 932 479 580 699 458 398 1118]; %4145 5754
loops2_vro_size_list_vro_icp_ch = [10511 8762 11416 7427 10814 6473 3273 10685 7102 4612 3188 783]; % % NMMP < 6
%loops2_vro_size_list_vro_icp_ch = [9506 7329 10525 7427 9123 5275 2757 9481 6417 4463 3032 783]; % NMMP < 13
loops2_pose_size_list = [830 582 830 832 649 928 477 580 699 455 365 227];
loops2_pose_size_list_vro_icp = [830 582 830 832 649 932 479 580 699 458 398 238];
%loops2_pose_size_list_vro_icp_ch = [830 582 830 832 649 928 477 580 698 455 364 234]; % NMMP < 13
loops2_pose_size_list_vro_icp_ch = [830 582 830 832 649 929 479 580 698 458 366 234]; % NMMP < 6
motive_vro_size_list_vro = [1525 1230 432 363 0 0 0 0 0 0 0 0 0 0 0];
motive_vro_size_list_vro_icp = [1943 1815 1783 365 0 0 0 0 0 0 0 0 0 0 0]; %232
motive_vro_size_list_vro_icp_ch = [1790 1437 1650 365 0 0 0 0 0 0 0 0 0 0 0]; %1494
motive_pose_size_list = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0];
motive_pose_size_list_vro_icp = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0];
motive_pose_size_list_vro_icp_ch = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0];
object_recognition_vro_size_list_vro = [1525 1230 432 9706 0 0 0 0 0 0 16089];
object_recognition_vro_size_list_vro_icp = [1943 1815 1783 365 0 0 0 0 0 0 0 0 0 0 0]; %232
object_recognition_vro_size_list_vro_icp_ch = [1790 1437 1650 365 0 0 0 0 0 0 0 0 0 0 0]; %1494
object_recognition_pose_size_list = [269 321 432 365 0 0 0 0 0 0 848];
object_recognition_pose_size_list_vro_icp = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0];
object_recognition_pose_size_list_vro_icp_ch = [269 321 432 365 0 0 0 0 0 0 0 0 0 0 0];
switch file_index
case 5
nFrame = m_nFrame_list(dynamic_index - 14);
vro_size = 6992; %5382; %46; %5365; %5169;
case 6
nFrame = etas_nFrame_list(dynamic_index); %289; 5414; %46; %5468; %296; %46; %86; %580; %3920;
vro_size = etas_vro_size_list(dynamic_index); %etas_vro_size_list(dynamic_index); %1951; 1942; %5382; %46; %5365; %5169;
pose_size = etas_pose_size_list(dynamic_index);
vro_icp_size = 0;
pose_vro_icp_size = 0;
vro_icp_ch_size = etas_vro_size_list_vro_icp_ch(dynamic_index);
pose_vro_icp_ch_size =etas_pose_size_list_vro_icp_ch(dynamic_index);
case 7
nFrame = loops_nFrame_list(dynamic_index);
vro_size = loops_vro_size_list(dynamic_index);
case 8
nFrame = kinect_tum_nFrame_list(dynamic_index);
vro_size = kinect_tum_vro_size_list(dynamic_index);
case 9
nFrame = loops2_nFrame_list(dynamic_index);
vro_size = loops2_vro_size_list(dynamic_index);
pose_size = loops2_pose_size_list(dynamic_index);
vro_icp_size = loops2_vro_size_list_vro_icp(dynamic_index);
pose_vro_icp_size = loops2_pose_size_list_vro_icp(dynamic_index);
vro_icp_ch_size = loops2_vro_size_list_vro_icp_ch(dynamic_index);
pose_vro_icp_ch_size = loops2_pose_size_list_vro_icp_ch(dynamic_index);
case 11
nFrame = sparse_feature_nFrame_list(dynamic_index);
vro_size = sparse_feature_vro_size_list_vro(dynamic_index);
pose_size = sparse_feature_pose_size_list_vro(dynamic_index);
vro_icp_size = sparse_feature_vro_size_list_vro_icp(dynamic_index);
pose_vro_icp_size = sparse_feature_pose_size_list_vro_icp(dynamic_index);
vro_icp_ch_size = sparse_feature_vro_size_list_vro_icp_ch(dynamic_index);
pose_vro_icp_ch_size = sparse_feature_pose_size_list_vro_icp_ch(dynamic_index);
case 12
nFrame = swing_nFrame_list(dynamic_index);
vro_size = swing_vro_size_list_vro(dynamic_index);
pose_size = swing_pose_size_list(dynamic_index);
vro_icp_size = swing_vro_size_list_vro_icp(dynamic_index);
pose_vro_icp_size = swing_pose_size_list_vro_icp(dynamic_index);
vro_icp_ch_size = swing_vro_size_list_vro_icp_ch(dynamic_index);
pose_vro_icp_ch_size = swing_pose_size_list_vro_icp_ch(dynamic_index);
case 13
nFrame = swing2_nFrame_list(dynamic_index);
vro_size = swing2_vro_size_list_vro(dynamic_index);
pose_size = swing2_pose_size_list(dynamic_index);
case 14
nFrame = motive_nFrame_list(dynamic_index);
vro_size = motive_vro_size_list_vro(dynamic_index);
pose_size = motive_pose_size_list(dynamic_index);
vro_icp_size = motive_vro_size_list_vro_icp(dynamic_index);
pose_vro_icp_size = motive_pose_size_list_vro_icp(dynamic_index);
vro_icp_ch_size = motive_vro_size_list_vro_icp_ch(dynamic_index);
pose_vro_icp_ch_size = motive_pose_size_list_vro_icp_ch(dynamic_index);
case 15
nFrame = object_recognition_nFrame_list(dynamic_index);
vro_size = object_recognition_vro_size_list_vro(dynamic_index);
pose_size = object_recognition_pose_size_list(dynamic_index);
vro_icp_size = object_recognition_vro_size_list_vro_icp(dynamic_index);
pose_vro_icp_size = object_recognition_pose_size_list_vro_icp(dynamic_index);
vro_icp_ch_size = object_recognition_vro_size_list_vro_icp_ch(dynamic_index);
pose_vro_icp_ch_size = object_recognition_pose_size_list_vro_icp_ch(dynamic_index);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
check_stored_pose_std.m
|
.m
|
slam_matlab-master/Localization/check_stored_pose_std.m
| 1,321 |
utf_8
|
b4da71858b5b61210cfbb759eee86f78
|
% Check if there is the stored matched points
%
% Author : Soonhac Hong ([email protected])
% Date : 3/11/2013
function [exist_flag] = check_stored_pose_std(data_name, dm, first_cframe, second_cframe, isgframe, sequence_data)
exist_flag = 0;
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
file_name = sprintf('d1_%04d_%04d.mat',first_cframe, second_cframe);
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
file_name = sprintf('d1_%04d_d%d_%04d.mat',first_cframe, dm, second_cframe);
end
if strcmp(isgframe, 'gframe')
dataset_dir = sprintf('%s/pose_std_gframe',dataset_dir);
else
dataset_dir = sprintf('%s/pose_std',dataset_dir);
end
%file_name = sprintf('d1_%04d_%04d.mat',first_cframe, second_cframe);
dirData = dir(dataset_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
if isempty(file_list)
return;
else
for i=1:size(file_list,1)
if strcmp(file_list{i}, file_name)
exist_flag = 1;
break;
end
end
end
end
|
github
|
uoa1184615/EquationFreeGit-master
|
functionTemplate.m
|
.m
|
EquationFreeGit-master/functionTemplate.m
| 521 |
utf_8
|
a1e11c88c02bb31c1cfedaab3fe4023d
|
% Short explanation for users typing "help fun"
% Author, date
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{...}: ...}
\label{sec:...}
\localtableofcontents
\subsection{Introduction}
Overview LaTeX explanation.
\begin{matlab}
%}
function ...
%{
\end{matlab}
\paragraph{Input} ...
\paragraph{Output} ...
\begin{devMan}
Repeated as desired:
LaTeX between end-matlab and begin-matlab
\begin{matlab}
%}
Matlab code between %} and %{
%{
\end{matlab}
Concluding LaTeX before following final lines.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
validateDelta.m
|
.m
|
EquationFreeGit-master/SandpitPlay/validateDelta.m
| 804 |
utf_8
|
6bc74cb092b53e03ebbdf85b7cbdea9f
|
%{
Validates dD>log(bD)/bD rule for PIRK2 by finding the dD at
which the PIRK2 scheme reduces by a factor of 10 each step,
given the fast decay is a rate bD. Reducing by a factor of
two is barely any different. AJR, 5 Feb 2019
%}
clear all, close all
global betaD
betaDs=logspace(log10(exp(1)),3,41);
bTtenth=nan(size(betaDs));
for j=1:length(betaDs)
betaD=betaDs(j);
bT0=log(betaD)/betaD;
bTtenth(j)=fsolve(@pirk2fac,bT0);
end
clf()
loglog(betaDs,[log(betaDs)./betaDs; bTtenth]')
grid
xlabel('\beta\Delta'),ylabel('(\delta/\Delta)_{min}')
function raterr=pirk2fac(bT)
stepFactor=0.1;
x = PIRK2(@eburst, bT, 0:2, 1);
raterr=x(end,:)./x(end-1,:) - stepFactor;
end
function [ts, xs] = eburst(ti, xi, bT)
global betaD
ts = linspace(ti,ti+bT,11)';
xs = xi.*exp(-betaD.*(ts-ti));
end
|
github
|
uoa1184615/EquationFreeGit-master
|
ensHeteroDiff.m
|
.m
|
EquationFreeGit-master/SandpitPlay/ensHeteroDiff.m
| 1,172 |
utf_8
|
e15cc2732ea08d02271b756707ff2f8f
|
% Computes the time derivatives of heterogeneous diffusion
% in 1D on patches. Used by homogenisationExample.m,
% ensembleAverageExample.m
% AJR, 4 Apr 2019 -- 7 Feb 2020
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\subsection{\texttt{heteroDiff()}: heterogeneous diffusion}
\label{sec:heteroDiff}
This function codes the lattice heterogeneous diffusion
inside the patches. For 2D input arrays~\verb|u|
and~\verb|x| (via edge-value interpolation of
\verb|patchSys1|, \cref{sec:patchSys1}), computes the
time derivative~\cref{eq:HomogenisationExample} at each
point in the interior of a patch, output in~\verb|ut|. The
column vector (or possibly array) of diffusion
coefficients~\(c_i\) have previously been stored in
struct~\verb|patches|.
\begin{matlab}
%}
function ut = ensHeteroDiff(t,u,x)
global patches
dx = diff(x(2:3)); % space step
i = 2:size(u,1)-1; % interior points in a patch
m = size(u,3);
j=1:m; jp=[2:m 1]; jm=[m 1:m-1]; % ensemble indices
ut = nan(size(u)); % preallocate output array
ut(i,:,j) = (patches.c(1,1,jp).*(u(i+1,:,jp)-u(i,:,j)) ...
+patches.c(1,1,j).*(u(i-1,:,jm)-u(i,:,j)))/dx^2;
end% function
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
heteroLanLif1D.m
|
.m
|
EquationFreeGit-master/SandpitPlay/heteroLanLif1D.m
| 2,278 |
utf_8
|
205cf93e1f254b8cfc678ee3dc654256
|
% Computes the time derivatives of heterogeneous
% Landau--Lifshitz PDE on 1D lattice within spatial patches.
% From Leitenmaier & Runborg, arxiv.org/abs/2108.09463 and
% used by homoLanLif1D.m AJR, Sep 2021
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\subsection{\texttt{heteroLanLif1D()}: heterogeneous Landau--Lifshitz PDE}
\label{sec:heteroLanLif1D}
This function codes the lattice heterogeneous
Landau--Lifshitz PDE \cite[(1.1)]{Leitenmaier2021} inside
patches in 1D space. For 4D input array~\verb|M| storing
the three components of~\Mv\ (via edge-value interpolation
of \verb|patchSys1|, \cref{sec:patchSys1}), computes
the time derivative at each point in the interior of a
patch, output in~\verb|Mt|. The column vector of
coefficients \(c_i=1+\tfrac12\sin(2\pi x_i/\epsilon)\) have
previously been stored in struct~\verb|patches.cs|.
\begin{itemize}
\item With \verb|ex5p1=0| computes the example \textsc{ex1}
\cite[p.6]{Leitenmaier2021}.
\item With \verb|ex5p1=1| computes the first 'locally
periodic' example \cite[p.27]{Leitenmaier2021}.
\end{itemize}
\begin{matlab}
%}
function Mt = heteroLanLif1D(t,M,patches)
global alpha ex5p1
dx = diff(patches.x(2:3)); % space step
i = 2:size(M,1)-1; % interior points in a patch
%{
\end{matlab}
Compute the heterogeneous \(\Hv:=\divv(a\grad\Mv)\)
\begin{matlab}
%}
a = patches.cs ...
+ex5p1*(0.1+0.25*sin(2*pi*(patches.x(2:end,:,:,:)-dx/2)+1.1));
H = diff(a.*diff(M))/dx^2;
%{
\end{matlab}
At each microscale grid point, compute the cross-products
\(\Mv\times \Hv\) and \(\Mv\times(\Mv\times \Hv)\) to then
give the time derivative \(\Mv_t=-\Mv\times \Hv -\alpha \Mv\times (\Mv\times \Hv)\) \cite[(1.1)]{Leitenmaier2021}:
\begin{matlab}
%}
MH=nan+H; % preallocate for MxH
MH(:,3,:,:) = M(i,1,:,:).*H(:,2,:,:)-M(i,2,:,:).*H(:,1,:,:);
MH(:,2,:,:) = M(i,3,:,:).*H(:,1,:,:)-M(i,1,:,:).*H(:,3,:,:);
MH(:,1,:,:) = M(i,2,:,:).*H(:,3,:,:)-M(i,3,:,:).*H(:,2,:,:);
MMH=nan+H; % preallocate for MxMxH
MMH(:,3,:,:)= M(i,1,:,:).*MH(:,2,:,:)-M(i,2,:,:).*MH(:,1,:,:);
MMH(:,2,:,:)= M(i,3,:,:).*MH(:,1,:,:)-M(i,1,:,:).*MH(:,3,:,:);
MMH(:,1,:,:)= M(i,2,:,:).*MH(:,3,:,:)-M(i,3,:,:).*MH(:,2,:,:);
Mt = nan+M; % preallocate output array
Mt(i,:,:,:) = -MH-alpha*MMH;
end% function
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
rk2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/rk2.m
| 615 |
utf_8
|
fc1b911f55a37b5b71802b80ecf35a6a
|
% Second order Runge-Kutta. No adaptive stepping, no error
% control. Use when testing other schemes. Alternatively
% see RKint/rk2int.m for a documented code that also
% estimates errors.
% Inputs:
% differential equation dxdt = dxdt(t,x)
% vector of times tSpan
% initial condition xIC
function [tOut,xOut] = rk2(dxdt,tSpan,xIC)
deltas = diff(tSpan);
tOut = tSpan;
xOut = zeros(length(tSpan),length(xIC));
xOut(1,:) = xIC;
xIC = xIC(:);
for n = 1:length(deltas)
del = deltas(n);
t = tSpan(n);
k1 = dxdt(t,xIC);
k2 = dxdt(t+del,xIC+del*k1);
xIC = xIC+del*(k1+k2)/2;
xOut(n+1,:)=xIC;
end
|
github
|
uoa1184615/EquationFreeGit-master
|
homoDiffBdryEquil3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/homoDiffBdryEquil3.m
| 6,957 |
utf_8
|
d7383388286f2dd582ff26e30b2dc4ff
|
% Finds equilibrium of forced heterogeneous diffusion in 3D
% cube on 3D patches as an example application. Boundary
% conditions are Neumann on the right face of the cube, and
% Dirichlet on the other faces. The microscale is of known
% period so we interpolate next-to-edge values to get
% opposite edge values. AJR, 1 Feb 2023
%!TEX root = doc.tex
%{
\section{\texttt{homoDiffBdryEquil3}: equilibrium via
computational homogenisation of a 3D heterogeneous diffusion
on small patches}
\label{sec:homoDiffBdryEquil3}
Find the equilibrium of a forced heterogeneous diffusion in
3D space on 3D patches as an example application. Boundary
conditions are Neumann on the right face of the cube, and
Dirichlet on the other faces. \cref{fig:homoDiffBdryEquil3}
shows five isosurfaces of the 3D solution field.
\begin{figure}\centering
\caption{\label{fig:homoDiffBdryEquil3}% Equilibrium of the
macroscale of the random heterogeneous diffusion in 3D with
boundary conditions of zero on all faces except for the
Neumann condition on \(x=1\)
(\cref{sec:homoDiffBdryEquil3}). The small patches are
equispaced in space. }
\includegraphics[scale=0.8]{Figs/homoDiffBdryEquil3.png}
\end{figure}
Clear variables, and establish globals.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plots
%{
\end{matlab}
Set random heterogeneous diffusivities of random
(small) period in each of the three directions. Crudely
normalise by the harmonic mean so the decay time scale is
roughly one.
\begin{matlab}
%}
mPeriod = randi([2 3],1,3)
cDiff = exp(0.3*randn([mPeriod 3]));
cDiff = cDiff*mean(1./cDiff(:))
%{
\end{matlab}
Configure the patch scheme with some arbitrary choices of
cubic domain, patches, and micro-grid spacing~\(0.05\).
Use high order interpolation as few patches in each
direction. Configure for Dirichlet boundaries except for
Neumann on the right \(x\)-face.
\begin{matlab}
%}
nSubP = mPeriod+2;
nPatch = 5;
Dom.type = 'equispace';
Dom.bcOffset = zeros(2,3); Dom.bcOffset(2) = 0.5;
configPatches3(@microDiffBdry3, [-1 1], Dom ...
, nPatch, 0, 0.05, nSubP, 'EdgyInt',true ...
,'hetCoeffs',cDiff );
%{
\end{matlab}
Set forcing, and store in global patches for access by the
microcode
\begin{matlab}
%}
patches.fu = 10*exp(-patches.x.^2-patches.y.^2-patches.z.^2);
patches.fu = patches.fu.*(1+rand(size(patches.fu)));
%{
\end{matlab}
\paragraph{Solve for steady state}
Set initial guess of zero, with \verb|NaN| to indicate
patch-edge values. Index~\verb|i| are the indices of
patch-interior points, store in global patches for access by
\verb|theRes|, and the number of unknowns is then its
number of elements.
\begin{matlab}
%}
u0 = zeros([nSubP,1,1,nPatch,nPatch,nPatch]);
u0([1 end],:,:,:) = nan;
u0(:,[1 end],:,:) = nan;
u0(:,:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
Solve by iteration. Use \verb|fsolve| for simplicity and
robustness (optionally \verb|optimoptions| to omit trace
information), via the generic patch system wrapper
\verb|theRes| (\cref{sec:theRes}).
\begin{matlab}
%}
disp('Solving system, takes 10--40 secs'),tic
uSoln = fsolve(@theRes,u0(patches.i) ...
,optimoptions('fsolve','Display','off'));
solveTime = toc
normResidual = norm(theRes(uSoln))
normSoln = norm(uSoln)
%{
\end{matlab}
Store the solution into the patches, and give magnitudes.
\begin{matlab}
%}
u0(patches.i) = uSoln;
u0 = patchEdgeInt3(u0);
%{
\end{matlab}
\paragraph{Plot isosurfaces of the solution}
\begin{matlab}
%}
figure(1), clf
rgb=get(gca,'defaultAxesColorOrder');
%{
\end{matlab}
Reshape spatial coordinates of patches.
\begin{matlab}
%}
x = patches.x(:); y = patches.y(:); z = patches.z(:);
%{
\end{matlab}
Draw isosurfaces. Get the solution with interpolated
faces, form into a 6D array, and reshape and transpose~\(x\)
and~\(y\) to suit the isosurface function.
\begin{matlab}
%}
u = reshape( permute(squeeze(u0),[2 5 1 4 3 6]) ...
, [numel(y) numel(x) numel(z)]);
maxu=max(u(:)), minu=min(u(:))
%{
\end{matlab}
Optionally cut-out the front corner so we can see inside.
\begin{matlab}
%}
u( (x'>0) & (y<0) & (shiftdim(z,-2)>0) ) = nan;
%{
\end{matlab}
Draw some isosurfaces.
\begin{matlab}
%}
clf;
for iso=5:-1:1
isov=(iso-0.5)/5*(maxu-minu)+minu;
hsurf(iso) = patch(isosurface(x,y,z,u,isov));
isonormals(x,y,z,u,hsurf(iso))
set(hsurf(iso) ,'FaceColor',rgb(iso,:) ...
,'EdgeColor','none' ,'FaceAlpha',iso/5);
hold on
end
hold off
axis equal, axis([-1 1 -1 1 -1 1]), view(35,25)
xlabel('$x$'), ylabel('$y$'), zlabel('$z$')
camlight, lighting gouraud
ifOurCf2eps(mfilename) %optionally save plot
if exist('OurCf2eps') && OurCf2eps, print('-dpng',['Figs/' mfilename]), end
%{
\end{matlab}
\subsection{\texttt{microDiffBdry3()}: 3D forced
heterogeneous diffusion with boundaries}
\label{sec:microDiffBdry3}
This function codes the lattice forced heterogeneous
diffusion inside the 3D patches. For 8D input
array~\verb|u| (via edge-value interpolation of
\verb|patchEdgeInt3|, such as by \verb|patchSys3|,
\cref{sec:patchSys3}), computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|. The
three 3D array of diffusivities,~$c^x_{ijk}$, $c^y_{ijk}$
and~$c^z_{ijk}$, have previously been stored
in~\verb|patches.cs| (4D).
Supply patch information as a third argument (required by
parallel computation), or otherwise by a global variable.
\begin{matlab}
%}
function ut = microDiffBdry3(t,u,patches)
if nargin<3, global patches, end
%{
\end{matlab}
Microscale space-steps.
\begin{matlab}
%}
dx = diff(patches.x(2:3)); % x micro-scale step
dy = diff(patches.y(2:3)); % y micro-scale step
dz = diff(patches.z(2:3)); % z micro-scale step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
k = 2:size(u,3)-1; % y interior points in a patch
%{
\end{matlab}
Code microscale boundary conditions of say Neumann on right,
and Dirichlet on left, top, bottom, front, and back (viewed
along the \(z\)-axis).
\begin{matlab}
%}
u( 1 ,:,:,:,:, 1 ,:,:)=0; %left face of leftmost patch
u(end,:,:,:,:,end,:,:)=u(end-1,:,:,:,:,end,:,:); %right face of rightmost
u(:, 1 ,:,:,:,:, 1 ,:)=0; %bottom face of bottommost
u(:,end,:,:,:,:,end,:)=0; %top face of topmost
u(:,:, 1 ,:,:,:,:, 1 )=0; %front face of frontmost
u(:,:,end,:,:,:,:,end)=0; %back face of backmost
%{
\end{matlab}
Reserve storage and then assign interior patch values to the
heterogeneous diffusion time derivatives. Using \verb|nan+u|
appears quicker than \verb|nan(size(u),patches.codist)|
\begin{matlab}
%}
ut = nan+u; % reserve storage
ut(i,j,k,:) ...
= diff(patches.cs(:,j,k,1).*diff(u(:,j,k,:),1,1),1,1)/dx^2 ...
+diff(patches.cs(i,:,k,2).*diff(u(i,:,k,:),1,2),1,2)/dy^2 ...
+diff(patches.cs(i,j,:,3).*diff(u(i,j,:,:),1,3),1,3)/dz^2 ...
+patches.fu(i,j,k);
end% function
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/patchEdgeInt3.m
| 26,337 |
utf_8
|
658f0a10f8d51dd9022ca660c17ff77e
|
% patchEdgeInt3() provides the interpolation across 3D space
% for 3D patches of simulations of a smooth lattice system
% such as PDE discretisations. AJR, Aug 2020 -- 2 Feb 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt3()}: sets 3D patch
face values from 3D macroscale interpolation}
\label{sec:patchEdgeInt3}
Couples 3D patches across 3D space by computing their face
values via macroscale interpolation. Assumes patch face
values are determined by macroscale interpolation of the
patch centre-plane values \cite[]{Roberts2011a,
Bunder2019d}, or patch next-to-face values which appears
better \cite[]{Bunder2020a}. This function is primarily
used by \verb|patchSys3()| but is also useful for user
graphics. \footnote{Script \texttt{patchEdgeInt3test.m}
verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global
struct \verb|patches|.
\begin{matlab}
%}
function u = patchEdgeInt3(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP1| \cdot \verb|nSubP2| \cdot \verb|nSubP3|
\cdot \verb|nPatch1| \cdot \verb|nPatch2| \cdot
\verb|nPatch3|$ multiscale spatial grid on the
$\verb|nPatch1| \cdot \verb|nPatch2| \cdot \verb|nPatch3|$
array of patches.
\item \verb|patches| a struct set by \verb|configPatches3()|
which includes the following information.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP1| \times1 \times1 \times1
\times1 \times \verb|nPatch1| \times1 \times1 $ array of the
spatial locations~$x_{iI}$ of the microscale grid points in
every patch. Currently it \emph{must} be an equi-spaced
lattice on the microscale index~$i$, but may be variable
spaced in macroscale index~$I$.
\item \verb|.y| is similarly $1\times \verb|nSubP2| \times1
\times1 \times1 \times1 \times \verb|nPatch2| \times1$ array
of the spatial locations~$y_{jJ}$ of the microscale grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on the microscale index~$j$, but may be
variable spaced in macroscale index~$J$.
\item \verb|.z| is similarly $1 \times1 \times \verb|nSubP3|
\times1 \times1 \times1 \times1 \times \verb|nPatch3|$ array
of the spatial locations~$z_{kK}$ of the microscale grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on the microscale index~$k$, but may be
variable spaced in macroscale index~$K$.
\item \verb|.ordCC| is order of interpolation, currently
only $\{0,2,4,\ldots\}$
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left, right, top, bottom, front and back boundaries so
interpolation is via divided differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation. Currently must be zero.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation in each of the
$x,y,z$-directions---when invoking a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation: true, from opposite-edge
next-to-edge values (often preserves symmetry); false, from
centre cross-patch values (near original scheme).
\item \verb|.nEnsem| the number of realisations in the
ensemble.
\item \verb|.parallel| whether serial or parallel.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 8D array, $\verb|nSubP1| \cdot
\verb|nSubP2| \cdot \verb|nSubP3| \cdot \verb|nVars| \cdot
\verb|nEnsem| \cdot \verb|nPatch1| \cdot \verb|nPatch2|
\cdot \verb|nPatch3|$, of the fields with face values set by
interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[~,~,nz,~,~,~,~,Nz] = size(patches.z);
[~,ny,~,~,~,~,Ny,~] = size(patches.y);
[nx,~,~,~,~,Nx,~,~] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round( numel(u)/numel(patches.x) ...
/numel(patches.y)/numel(patches.z)/nEnsem );
assert(numel(u) == nx*ny*nz*Nx*Ny*Nz*nVars*nEnsem ...
,'patchEdgeInt3: input u has wrong size for parameters')
u = reshape(u,[nx ny nz nVars nEnsem Nx Ny Nz]);
%{
\end{matlab}
For the moment assume the physical domain is either
macroscale periodic or macroscale rectangle so that the
coupling formulas are simplest. These index vectors point
to patches and, if periodic, their six immediate neighbours.
\begin{matlab}
%}
I=1:Nx; Ip=mod(I,Nx)+1; Im=mod(I-2,Nx)+1;
J=1:Ny; Jp=mod(J,Ny)+1; Jm=mod(J-2,Ny)+1;
K=1:Nz; Kp=mod(K,Nz)+1; Km=mod(K-2,Nz)+1;
%{
\end{matlab}
The centre of each patch (as \verb|nx|, \verb|ny| and
\verb|nz| are odd for centre-patch interpolation) is at
indices
\begin{matlab}
%}
i0 = round((nx+1)/2);
j0 = round((ny+1)/2);
k0 = round((nz+1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches in each direction.
\begin{matlab}
%}
rx = patches.ratio(1);
ry = patches.ratio(2);
rz = patches.ratio(3);
%{
\end{matlab}
\subsubsection{Lagrange interpolation gives patch-face values}
Compute centred differences of the mid-patch values for the
macro-interpolation, of all fields. Here the domain is
macro-periodic.
\begin{matlab}
%}
ordCC = patches.ordCC;
if ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in face-edge and corner values. Start with
\(x\)-direction, and give most documentation for that case
as the others are essentially the same.
\paragraph{\(x\)-normal face values} The patch-edge values
are either interpolated from the next-to-edge-face values,
or from the centre-cross-plane values (not the patch-centre
value itself as that seems to have worse properties in
general). Have not yet implemented core averages.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u([2 nx-1],2:(ny-1),2:(nz-1),:,:,I,J,K);
else % interpolate centre-cross values
U = u(i0,2:(ny-1),2:(nz-1),:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Just in case the last array dimension(s) are one, we have to
force a padding of the sizes, then adjoin the extra
dimension for the subsequent array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in these arrays. When parallel, in order
to preserve the distributed array structure we use an index
at the end for the differences.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
% dmux(:,:,:,:,:,I,:,:,1) = (Ux(:,:,:,:,:,Ip,:,:) +Ux(:,:,:,:,:,Im,:,:))/2; % \mu
% dmux(:,:,:,:,:,I,:,:,2) = (Ux(:,:,:,:,:,Ip,:,:) -Ux(:,:,:,:,:,Im,:,:)); % \delta
% Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
% dmuy(:,:,:,:,:,:,J,:,1) = (Ux(:,:,:,:,:,:,Jp,:)+Ux(:,:,:,:,:,:,Jm,:))/2; % \mu
% dmuy(:,:,:,:,:,:,J,:,2) = (Ux(:,:,:,:,:,:,Jp,:)-Ux(:,:,:,:,:,:,Jm,:)); % \delta
% Jp = Jp(Jp); Jm = Jm(Jm); % increase shifts to \pm2
% dmuz(:,:,:,:,:,:,:,K,1) = (Ux(:,:,:,:,:,:,:,Kp)+Ux(:,:,:,:,:,:,:,Km))/2; % \mu
% dmuz(:,:,:,:,:,:,:,K,2) = (Ux(:,:,:,:,:,:,:,Kp)-Ux(:,:,:,:,:,:,:,Km)); % \delta
% Kp = Kp(Kp); Km = Km(Km); % increase shifts to \pm2
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,I,:,:,1) = (U(:,:,:,:,:,Ip,:,:) ...
-U(:,:,:,:,:,Im,:,:))/2; %\mu\delta
dmu(:,:,:,:,:,I,:,:,2) = (U(:,:,:,:,:,Ip,:,:) ...
-2*U(:,:,:,:,:,I,:,:) +U(:,:,:,:,:,Im,:,:)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,I,:,:,k) = dmu(:,:,:,:,:,Ip,:,:,k-2) ...
-2*dmu(:,:,:,:,:,I,:,:,k-2) +dmu(:,:,:,:,:,Im,:,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet face values for
each patch \cite[]{Roberts06d, Bunder2013b}, using the weights
pre-computed by \verb|configPatches3()|. Here interpolate to
specified order.
For the case where next-to-face values interpolate to the
opposite face-values: when we have an ensemble of
configurations, different configurations might be coupled to
each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to|, \verb|patches.bo|,
\verb|patches.fr| and \verb|patches.ba|.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(nx,2:(ny-1),2:(nz-1),:,patches.ri,I,:,:) ...
= U(1,:,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,1),-8).*dmu(1,:,:,:,:,:,:,:,:) ,9);
u(1 ,2:(ny-1),2:(nz-1),:,patches.le,I,:,:) ...
= U(k,:,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,1),-8).*dmu(k,:,:,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\paragraph{\(y\)-normal face values} Interpolate from either
the next-to-edge-face values, or the centre-cross-plane
values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,[2 ny-1],2:(nz-1),:,:,I,J,K);
else % interpolate centre-cross values
U = u(:,j0,2:(nz-1),:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,:,J,:,1) = (U(:,:,:,:,:,:,Jp,:) ...
-U(:,:,:,:,:,:,Jm,:))/2; %\mu\delta
dmu(:,:,:,:,:,:,J,:,2) = (U(:,:,:,:,:,:,Jp,:) ...
-2*U(:,:,:,:,:,:,J,:) +U(:,:,:,:,:,:,Jm,:)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,:,J,:,k) = dmu(:,:,:,:,:,:,Jp,:,k-2) ...
-2*dmu(:,:,:,:,:,:,J,:,k-2) +dmu(:,:,:,:,:,:,Jm,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches3()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(:,ny,2:(nz-1),:,patches.to,:,J,:) ...
= U(:,1,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,2),-8).*dmu(:,1,:,:,:,:,:,:,:) ,9);
u(:,1 ,2:(nz-1),:,patches.bo,:,J,:) ...
= U(:,k,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,2),-8).*dmu(:,k,:,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\paragraph{\(z\)-normal face values} Interpolate from either
the next-to-edge-face values, or the centre-cross-plane
values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,:,[2 nz-1],:,:,I,J,K);
else % interpolate centre-cross values
U = u(:,:,k0,:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,:,:,K,1) = (U(:,:,:,:,:,:,:,Kp) ...
-U(:,:,:,:,:,:,:,Km))/2; %\mu\delta
dmu(:,:,:,:,:,:,:,K,2) = (U(:,:,:,:,:,:,:,Kp) ...
-2*U(:,:,:,:,:,:,:,K) +U(:,:,:,:,:,:,:,Km)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,:,:,K,k) = dmu(:,:,:,:,:,:,:,Kp,k-2) ...
-2*dmu(:,:,:,:,:,:,:,K,k-2) +dmu(:,:,:,:,:,:,:,Km,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches3()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(:,:,nz,:,patches.fr,:,:,K) ...
= U(:,:,1,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,3),-8).*dmu(:,:,1,:,:,:,:,:,:) ,9);
u(:,:,1 ,:,patches.ba,:,:,K) ...
= U(:,:,k,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,3),-8).*dmu(:,:,k,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\subsubsection{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
We interpolate in terms of the patch index, $I$~say, not
directly in space. As the macroscale fields are $N$-periodic
in the patch index~$I$, the macroscale Fourier transform
writes the centre-patch values as $U_I=\sum_{k}C_ke^{ik2\pi
I/N}$. Then the face-patch values $U_{I\pm r}
=\sum_{k}C_ke^{ik2\pi/N(I\pm r)} =\sum_{k}C'_ke^{ik2\pi
I/N}$ where $C'_k =C_ke^{ikr2\pi/N}$. For $N$~patches we
resolve `wavenumbers' $|k|<N/2$, so set row vector
$\verb|ks| =k2\pi/N$ for `wavenumbers' $\mathcode`\,="213B
k=(0,1, \ldots, k_{\max}, -k_{\max}, \ldots, -1)$ for
odd~$N$, and $\mathcode`\,="213B k=(0,1, \ldots, k_{\max},
\pm(k_{\max}+1) -k_{\max}, \ldots, -1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches3|
tests there are an even number of patches). Then the
patch-ratio is effectively halved. The patch faces are near
the middle of the gaps and swapped.
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
error('staggered grid not yet implemented??')
v=nan(size(u)); % currently to restore the shape of u
u=cat(3,u(:,1:2:nPatch,:),u(:,2:2:nPatch,:));
stagShift=reshape(0.5*[ones(nVars,1);-ones(nVars,1)],1,1,[]);
iV=[nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r=r/2; % ratio effectively halved
nPatch=nPatch/2; % halve the number of patches
nVars=nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in face-edge and corner values. Start with
\(x\)-direction, and give most documentation for that case
as the others are essentially the same. Need these indices
of patch interior.
\begin{matlab}
%}
ix = 2:nx-1; iy = 2:ny-1; iz = 2:nz-1;
%{
\end{matlab}
\paragraph{\(x\)-normal face values} Now set wavenumbers
into a vector at the correct dimension. In the case of
even~$N$ these compute the $+$-case for the highest
wavenumber zig-zag mode, $\mathcode`\,="213B k=(0,1, \ldots,
k_{\max}, +(k_{\max}+1) -k_{\max}, \ldots, -1)$.
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
kr = shiftdim( rx*2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ,-4);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields. Unless doing patch-edgy
interpolation when FT the next-to-face values. If there are
an even number of points, then if complex, treat as positive
wavenumber, but if real, treat as cosine. When using an
ensemble of configurations, different configurations might
be coupled to each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to|, \verb|patches.bo|,
\verb|patches.fr| and \verb|patches.ba|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(i0,iy,iz,:,:,:,:,:) ,[],6);
Cp = Cm;
else
Cm = fft( u( 2,iy,iz ,:,patches.le,:,:,:) ,[],6);
Cp = fft( u(nx-1,iy,iz ,:,patches.ri,:,:,:) ,[],6);
end%if ~patches.EdgyInt
%{
\end{matlab}
Now invert the Fourier transforms to complete interpolation.
Enforce reality when appropriate.
\begin{matlab}
%}
u(nx,iy,iz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],6) );
u( 1,iy,iz,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],6) );
%{
\end{matlab}
\paragraph{\(y\)-normal face values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Ny-1)/2);
kr = shiftdim( ry*2*pi/Ny*(mod((0:Ny-1)+kMax,Ny)-kMax) ,-5);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,j0,iz,:,:,:,:,:) ,[],7);
Cp = Cm;
else
Cm = fft( u(:,2 ,iz ,:,patches.bo,:,:,:) ,[],7);
Cp = fft( u(:,ny-1,iz ,:,patches.to,:,:,:) ,[],7);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,ny,iz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],7) );
u(:, 1,iz,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],7) );
%{
\end{matlab}
\paragraph{\(z\)-normal face values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Nz-1)/2);
kr = shiftdim( rz*2*pi/Nz*(mod((0:Nz-1)+kMax,Nz)-kMax) ,-6);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,:,k0,:,:,:,:,:) ,[],8);
Cp = Cm;
else
Cm = fft( u(:,:,2 ,:,patches.ba,:,:,:) ,[],8);
Cp = fft( u(:,:,nz-1 ,:,patches.fr,:,:,:) ,[],8);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,:,nz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],8) );
u(:,:, 1,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],8) );
%{
\end{matlab}
\begin{matlab}
%}
end% if ordCC>0
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|px|, \verb|py|
and~\verb|pz| (potentially different in the different
directions!), and hence size of the (forward) divided
difference tables in~\verb|F|~(9D) for interpolating to
left/right, top/bottom, and front/back faces. Because of the
product-form of the patch grid, and because we are doing
\emph{only} either edgy interpolation or cross-patch
interpolation (\emph{not} just the centre patch value), the
interpolations are all 1D interpolations.
\begin{matlab}
%}
if patches.ordCC<1
px = Nx-1; py = Ny-1; pz = Nz-1;
else px = min(patches.ordCC,Nx-1);
py = min(patches.ordCC,Ny-1);
pz = min(patches.ordCC,Nz-1);
end
% interior indices of faces (ix n/a)
ix=2:nx-1; iy=2:ny-1; iz=2:nz-1;
%{
\end{matlab}
\subsubsection{\(x\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-face values are because their
values are to interpolate to the opposite face of each
patch. \todo{Have no plans to implement core averaging as yet.}
\begin{matlab}
%}
F = nan(patches.EdgyInt+1,ny-2,nz-2,nVars,nEnsem,Nx,Ny,Nz,px+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u([nx-1 2],iy,iz,:,:,:,:,:);
X = patches.x([nx-1 2],:,:,:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(i0,iy,iz,:,:,:,:,:);
X = patches.x(i0,:,:,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
\paragraph{Form tables of divided differences} Compute
tables of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable, and
across ensemble, and in both directions, and for all three
types of faces (left/right, top/bottom, and front/back).
Recursively find all divided differences in the respective
direction.
\begin{matlab}
%}
for q = 1:px
i = 1:Nx-q;
F(:,:,:,:,:,i,:,:,q+1) ...
= ( F(:,:,:,:,:,i+1,:,:,q)-F(:,:,:,:,:,i,:,:,q)) ...
./(X(:,:,:,:,:,i+q,:,:) -X(:,:,:,:,:,i,:,:));
end
%{
\end{matlab}
\paragraph{Interpolate with divided differences} Now
interpolate to find the face-values on left/right faces
at~\verb|Xface| for every interior~\verb|Y,Z|.
\begin{matlab}
%}
Xface = patches.x([1 nx],:,:,:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|i| are those of the left face of
each interpolation stencil, because the table is of forward
differences. This alternative: the case of order~\(p_x\),
\(p_y\) and~\(p_z\) interpolation across the domain,
asymmetric near the boundaries of the rectangular domain.
\begin{matlab}
%}
i = max(1,min(1:Nx,Nx-ceil(px/2))-floor(px/2));
Uface = F(:,:,:,:,:,i,:,:,px+1);
for q = px:-1:1
Uface = F(:,:,:,:,:,i,:,:,q) ...
+(Xface-X(:,:,:,:,:,i+q-1,:,:)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,iy,iz,:,patches.le,:,:,:) = Uface(1,:,:,:,:,:,:,:);
u(nx,iy,iz,:,patches.ri,:,:,:) = Uface(2,:,:,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(y\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,patches.EdgyInt+1,nz-2,nVars,nEnsem,Nx,Ny,Nz,py+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u(:,[ny-1 2],iz,:,:,:,:,:);
Y = patches.y(:,[ny-1 2],:,:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(:,j0,iz,:,:,:,:,:);
Y = patches.y(:,j0,:,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:py
j = 1:Ny-q;
F(:,:,:,:,:,:,j,:,q+1) ...
= ( F(:,:,:,:,:,:,j+1,:,q)-F(:,:,:,:,:,:,j,:,q)) ...
./(Y(:,:,:,:,:,:,j+q,:) -Y(:,:,:,:,:,:,j,:));
end
%{
\end{matlab}
Interpolate to find the top/bottom faces~\verb|Yface| for
every~\(x\) and interior~\(z\).
\begin{matlab}
%}
Yface = patches.y(:,[1 ny],:,:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|j| are those of the bottom face
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
j = max(1,min(1:Ny,Ny-ceil(py/2))-floor(py/2));
Uface = F(:,:,:,:,:,:,j,:,py+1);
for q = py:-1:1
Uface = F(:,:,:,:,:,:,j,:,q) ...
+(Yface-Y(:,:,:,:,:,:,j+q-1,:)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,1 ,iz,:,patches.bo,:,:,:) = Uface(:,1,:,:,:,:,:,:);
u(:,ny,iz,:,patches.to,:,:,:) = Uface(:,2,:,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(z\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,ny,patches.EdgyInt+1,nVars,nEnsem,Nx,Ny,Nz,pz+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u(:,:,[nz-1 2],:,:,:,:,:);
Z = patches.z(:,:,[nz-1 2],:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(:,:,k0,:,:,:,:,:);
Z = patches.z(:,:,k0,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:pz
k = 1:Nz-q;
F(:,:,:,:,:,:,:,k,q+1) ...
= ( F(:,:,:,:,:,:,:,k+1,q)-F(:,:,:,:,:,:,:,k,q)) ...
./(Z(:,:,:,:,:,:,:,k+q) -Z(:,:,:,:,:,:,:,k));
end
%{
\end{matlab}
Interpolate to find the face-values on front/back
faces~\verb|Zface| for every~\(x,y\).
\begin{matlab}
%}
Zface = patches.z(:,:,[1 nz],:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|k| are those of the bottom face
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
k = max(1,min(1:Nz,Nz-ceil(pz/2))-floor(pz/2));
Uface = F(:,:,:,:,:,:,:,k,pz+1);
for q = pz:-1:1
Uface = F(:,:,:,:,:,:,:,k,q) ...
+(Zface-Z(:,:,:,:,:,:,:,k+q-1)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,:,1 ,:,patches.fr,:,:,:) = Uface(:,:,1,:,:,:,:,:);
u(:,:,nz,:,patches.ba,:,:,:) = Uface(:,:,2,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{Optional NaNs for safety}
We want a user to set outer face values on the extreme
patches according to the microscale boundary conditions that
hold at the extremes of the domain. Consequently, override
their computed interpolation values with~\verb|NaN|.
\begin{matlab}
%}
u( 1,:,:,:,:, 1,:,:) = nan;
u(nx,:,:,:,:,Nx,:,:) = nan;
u(:, 1,:,:,:,:, 1,:) = nan;
u(:,ny,:,:,:,:,Ny,:) = nan;
u(:,:, 1,:,:,:,:, 1) = nan;
u(:,:,nz,:,:,:,:,Nz) = nan;
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic else
%{
\end{matlab}
Fin, returning the 8D array of field values with
interpolated faces.
\begin{matlab}
%}
end% function patchEdgeInt3
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
configPatches1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/configPatches1.m
| 23,698 |
utf_8
|
f00f13351f335beceda77bc01a5c7a7c
|
% configPatches1() creates a data struct of the design of
% 1D patches for later use by the patch functions such as
% patchSys1(). AJR, Nov 2017 -- 4 Jan 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{configPatches1()}: configures spatial
patches in 1D}
\label{sec:configPatches1}
\localtableofcontents
Makes the struct~\verb|patches| for use by the patch\slash
gap-tooth time derivative\slash step function
\verb|patchSys1()|. \cref{sec:configPatches1eg} lists an
example of its use.
\begin{matlab}
%}
function patches = configPatches1(fun,Xlim,Dom ...
,nPatch,ordCC,dx,nSubP,varargin)
%{
\end{matlab}
\paragraph{Input}
If invoked with no input arguments, then executes an example
of simulating Burgers' \pde---see \cref{sec:configPatches1eg}
for the example code.
\begin{itemize}
\item \verb|fun| is the name of the user function,
\verb|fun(t,u,patches)| or \verb|fun(t,u)|, that computes
time derivatives (or time-steps) of quantities on the 1D
micro-grid within all the 1D~patches.
\item \verb|Xlim| give the macro-space spatial domain of the
computation, namely the interval $[ \verb|Xlim(1)|,
\verb|Xlim(2)|]$.
\item \verb|Dom| sets the type of macroscale conditions for
the patches, and reflects the type of microscale boundary
conditions of the problem. If \verb|Dom| is \verb|NaN| or
\verb|[]|, then the field~\verb|u| is macro-periodic in the
1D spatial domain, and resolved on equi-spaced patches. If
\verb|Dom| is a character string, then that specifies the
\verb|.type| of the following structure, with
\verb|.bcOffset| set to the default zero. Otherwise
\verb|Dom| is a structure with the following components.
\begin{itemize}
\item \verb|.type|, string, of either \verb|'periodic'| (the
default), \verb|'equispace'|, \verb|'chebyshev'|,
\verb|'usergiven'|. For all cases except \verb|'periodic'|,
users \emph{must} code into \verb|fun| the micro-grid
boundary conditions that apply at the left(right) edge of
the leftmost(rightmost) patches.
\item \verb|.bcOffset|, optional one or two element array,
in the cases of \verb|'equispace'| or \verb|'chebyshev'|
the patches are placed so the left\slash right macroscale
boundaries are aligned to the left\slash right edges of the
corresponding extreme patches, but offset by \verb|bcOffset|
of the sub-patch micro-grid spacing. For example, use
\verb|bcOffset=0| when applying Dirichlet boundary values on
the extreme edge micro-grid points, whereas use
\verb|bcOffset=0.5| when applying Neumann boundary conditions
halfway between the extreme edge micro-grid points.
\item \verb|.X|, optional array, in the case~\verb|'usergiven'|
it specifies the locations of the centres of the
\verb|nPatch| patches---the user is responsible it makes
sense.
\end{itemize}
\item \verb|nPatch| is the number of equi-spaced spatial
patches.
\item \verb|ordCC|, must be~$\geq -1$, is the `order' of
interpolation across empty space of the macroscale patch
values to the edge of the patches for inter-patch coupling:
where \verb|ordCC| of~$0$ or~$-1$ gives spectral
interpolation; and \verb|ordCC| being odd specifies
staggered spatial grids.
\item \verb|dx| (real) is usually the sub-patch micro-grid
spacing in~\(x\).
However, if \verb|Dom| is~\verb|NaN| (as for pre-2023), then
\verb|dx| actually is \verb|ratio|, namely the ratio of
(depending upon \verb|EdgyInt|) either the half-width or
full-width of a patch to the equi-spacing of the patch
mid-points. So either $\verb|ratio|=\tfrac12$ means the
patches abut and $\verb|ratio|=1$ is overlapping patches as
in holistic discretisation, or $\verb|ratio|=1$ means the
patches abut. Small~\verb|ratio| should greatly reduce
computational time.
\item \verb|nSubP| is the number of equi-spaced microscale
lattice points in each patch. If not using \verb|EdgyInt|,
then must be odd so that there is a centre-patch lattice point.
\item \verb|nEdge| (not yet implemented), \emph{optional},
default=1, for each patch, the number of edge values set by
interpolation at the edge regions of each patch. The
default is one (suitable for microscale lattices with only
nearest neighbour interactions).
\item \verb|EdgyInt|, true/false, \emph{optional},
default=false. If true, then interpolate to left\slash
right edge-values from right\slash left next-to-edge values.
If false or omitted, then interpolate from centre-patch
values.
\item \verb|nEnsem|, \emph{optional-experimental},
default one, but if more, then an ensemble over this
number of realisations.
\item \verb|hetCoeffs|, \emph{optional}, default empty.
Supply a 1D or 2D array of microscale heterogeneous coefficients
to be used by the given microscale \verb|fun| in each patch.
Say the given array~\verb|cs| is of size $m_x\times n_c$,
where $n_c$~is the number of different sets of coefficients.
The coefficients are to be the same for each and every
patch; however, macroscale variations are catered for by the
$n_c$~coefficients being $n_c$~parameters in some macroscale
formula.
\begin{itemize}
\item If $\verb|nEnsem|=1$, then the array of coefficients
is just tiled across the patch size to fill up each patch,
starting from the first point in each patch.
\item If $\verb|nEnsem|>1$ (value immaterial), then reset
$\verb|nEnsem|:=m_x$ and construct an ensemble of all
$m_x$~phase-shifts of the coefficients. In this scenario,
the inter-patch coupling couples different members in the
ensemble. When \verb|EdgyInt| is true, and when the
coefficients are diffusivities\slash elasticities, then this
coupling cunningly preserves symmetry.
\end{itemize}
\item \verb|nCore|, \emph{optional-experimental}, default
one, but if more, and only for non-EdgyInt, then
interpolates from an average over the core of a patch, a
core of size ??. Then edge values are set according to
interpolation of the averages?? or so that average at edges
is the interpolant??
\item \verb|'parallel'|, true/false, \emph{optional},
default=false. If false, then all patch computations are on
the user's main \textsc{cpu}---although a user may well
separately invoke, say, a \textsc{gpu} to accelerate
sub-patch computations.
If true, and it requires that you have \Matlab's Parallel
Computing Toolbox, then it will distribute the patches over
multiple \textsc{cpu}s\slash cores. In \Matlab, only one
array dimension can be split in the distribution, so it
chooses the one space dimension~$x$. A user may
correspondingly distribute arrays with property
\verb|patches.codist|, or simply use formulas invoking the
preset distributed arrays \verb|patches.x|. If a user has
not yet established a parallel pool, then a `local' pool is
started.
\end{itemize}
\paragraph{Output} The struct \verb|patches| is created and
set with the following components. If no output variable is
provided for \verb|patches|, then make the struct available
as a global variable.\footnote{When using \texttt{spmd}
parallel computing, it is generally best to avoid global
variables, and so instead prefer using an explicit output
variable.}
\begin{matlab}
%}
if nargout==0, global patches, end
%{
\end{matlab}
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| or \verb|fun(t,u)|, that computes
the time derivatives (or steps) on the patchy lattice.
\item \verb|.ordCC| is the specified order of inter-patch
coupling.
\item \verb|.periodic|: either true, for interpolation on
the macro-periodic domain; or false, for general
interpolation by divided differences over non-periodic
domain or unevenly distributed patches.
\item \verb|.stag| is true for interpolation using only odd
neighbouring patches as for staggered grids, and false for
the usual case of all neighbour coupling.
\item \verb|.Cwtsr| and \verb|.Cwtsl|, only for
macro-periodic conditions, are the $\verb|ordCC|$-vector of
weights for the inter-patch interpolation onto the right and
left edges (respectively) with patch:macroscale ratio as
specified or as derived from~\verb|dx|.
\item \verb|.x| (4D) is $\verb|nSubP| \times1 \times1
\times \verb|nPatch|$ array of the regular spatial
locations~$x_{iI}$ of the $i$th~microscale grid point in
the $I$th~patch.
\item \verb|.ratio|, only for
macro-periodic conditions, is the size ratio of every patch.
\item \verb|.nEdge| is, for each patch, the number of edge
values set by interpolation at the edge regions of each
patch.
\item \verb|.le|, \verb|.ri|
determine inter-patch coupling of members in an ensemble.
Each a column vector of length~\verb|nEnsem|.
\item \verb|.cs| either
\begin{itemize}
\item \verb|[]| 0D, or
\item if $\verb|nEnsem|=1$, $(\verb|nSubP(1)|-1)\times
n_c$ 2D array of microscale heterogeneous coefficients, or
\item if $\verb|nEnsem|>1$, $(\verb|nSubP(1)|-1) \times
n_c\times m_x$ 3D array of $m_x$~ensemble of phase-shifts
of the microscale
heterogeneous coefficients.
\end{itemize}
\item \verb|.parallel|, logical: true if patches are
distributed over multiple \textsc{cpu}s\slash cores for the
Parallel Computing Toolbox, otherwise false (the default is
to activate the \emph{local} pool).
\item \verb|.codist|, \emph{optional}, describes the
particular parallel distribution of arrays over the active
parallel pool.
\end{itemize}
\subsection{If no arguments, then execute an example}
\label{sec:configPatches1eg}
\begin{matlab}
%}
if nargin==0
disp('With no arguments, simulate example of Burgers PDE')
%{
\end{matlab}
The code here shows one way to get started: a user's script
may have the following three steps (``\into'' denotes
function recursion).
\begin{enumerate}\def\itemsep{-1.5ex}
\item configPatches1
\item ode15s integrator \into patchSys1 \into user's PDE
\item process results
\end{enumerate}
Establish global patch data struct to point to and interface
with a function coding Burgers' \pde: to be solved on
$2\pi$-periodic domain, with eight patches, spectral
interpolation couples the patches, with micro-grid
spacing~$0.06$, and with seven microscale points forming
each patch.
\begin{matlab}
%}
global patches
patches = configPatches1(@BurgersPDE,[0 2*pi], [], 8, 0, 0.06, 7);
%{
\end{matlab}
Set some initial condition, with some microscale randomness.
\begin{matlab}
%}
u0=0.3*(1+sin(patches.x))+0.1*randn(size(patches.x));
%{
\end{matlab}
Simulate in time using a standard stiff integrator and the
interface function \verb|patchSys1()|
(\cref{sec:patchSys1}).
\begin{matlab}
%}
if ~exist('OCTAVE_VERSION','builtin')
[ts,us] = ode15s( @patchSys1,[0 0.5],u0(:));
else % octave version
[ts,us] = odeOcts(@patchSys1,[0 0.5],u0(:));
end
%{
\end{matlab}
Plot the simulation using only the microscale values
interior to the patches: either set $x$-edges to \verb|nan|
to leave the gaps; or use \verb|patchEdgyInt1| to
re-interpolate correct patch edge values and thereby join
the patches. \cref{fig:config1Burgers} illustrates an
example simulation in time generated by the patch scheme
applied to Burgers'~\pde.
\begin{matlab}
%}
figure(1),clf
if 1, patches.x([1 end],:,:,:)=nan; us=us.';
else us=reshape(patchEdgyInt1(us.'),[],length(ts));
end
surf(ts,patches.x(:),us)
view(60,40), colormap(0.8*hsv)
title('Burgers PDE: patches in space, continuous time')
xlabel('time t'), ylabel('space x'), zlabel('u(x,t)')
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:config1Burgers}field
$u(x,t)$ of the patch scheme applied to Burgers'~\pde.}
\includegraphics[scale=0.85]{configPatches1}
\end{figure}
Upon finishing execution of the example, optionally save
the graph to be shown in \cref{fig:config1Burgers}, then
exit this function.
\begin{matlab}
%}
ifOurCf2eps(mfilename)
return
end%if nargin==0
%{
\end{matlab}
\IfFileExists{../Patch/BurgersPDE.m}{\input{../Patch/BurgersPDE.m}}{}
\IfFileExists{../Patch/odeOcts.m}{\input{../Patch/odeOcts.m}}{}
\begin{devMan}
\subsection{Parse input arguments and defaults}
\begin{matlab}
%}
p = inputParser;
fnValidation = @(f) isa(f, 'function_handle'); %test for fn name
addRequired(p,'fun',fnValidation);
addRequired(p,'Xlim',@isnumeric);
%addRequired(p,'Dom'); % nothing yet decided
addRequired(p,'nPatch',@isnumeric);
addRequired(p,'ordCC',@isnumeric);
addRequired(p,'dx',@isnumeric);
addRequired(p,'nSubP',@isnumeric);
addParameter(p,'nEdge',1,@isnumeric);
addParameter(p,'EdgyInt',false,@islogical);
addParameter(p,'nEnsem',1,@isnumeric);
addParameter(p,'hetCoeffs',[],@isnumeric);
addParameter(p,'parallel',false,@islogical);
addParameter(p,'nCore',1,@isnumeric);
parse(p,fun,Xlim,nPatch,ordCC,dx,nSubP,varargin{:});
%{
\end{matlab}
Set the optional parameters.
\begin{matlab}
%}
patches.nEdge = p.Results.nEdge;
patches.EdgyInt = p.Results.EdgyInt;
patches.nEnsem = p.Results.nEnsem;
cs = p.Results.hetCoeffs;
patches.parallel = p.Results.parallel;
patches.nCore = p.Results.nCore;
%{
\end{matlab}
Check parameters.
\begin{matlab}
%}
assert(Xlim(1)<Xlim(2) ...
,'two entries of Xlim must be ordered increasing')
assert(patches.nEdge==1 ...
,'multi-edge-value interp not yet implemented')
assert(2*patches.nEdge+1<=nSubP ...
,'too many edge values requested')
if patches.nCore>1
warning('nCore>1 not yet tested in this version')
end
%{
\end{matlab}
For compatibility with pre-2023 functions, if parameter
\verb|Dom| is \verb|Nan|, then we set the \verb|ratio| to
be the value of the so-called \verb|dx| parameter.
\begin{matlab}
%}
if ~isstruct(Dom), pre2023=isnan(Dom);
else pre2023=false; end
if pre2023, ratio=dx; dx=nan; end
%{
\end{matlab}
Default macroscale conditions are periodic with evenly
spaced patches.
\begin{matlab}
%}
if isempty(Dom), Dom=struct('type','periodic'); end
if (~isstruct(Dom))&isnan(Dom), Dom=struct('type','periodic'); end
%{
\end{matlab}
If \verb|Dom| is a string, then just set type to that
string, and then get corresponding defaults for others
fields.
\begin{matlab}
%}
if ischar(Dom), Dom=struct('type',Dom); end
%{
\end{matlab}
Check what is and is not specified, and provide default of
Dirichlet boundaries if no \verb|bcOffset| specified when
needed.
\begin{matlab}
%}
patches.periodic=false;
switch Dom.type
case 'periodic'
patches.periodic=true;
if isfield(Dom,'bcOffset')
warning('bcOffset not available for Dom.type = periodic'), end
if isfield(Dom,'X')
warning('X not available for Dom.type = periodic'), end
case {'equispace','chebyshev'}
if ~isfield(Dom,'bcOffset'), Dom.bcOffset=[0;0]; end
if length(Dom.bcOffset)==1
Dom.bcOffset=repmat(Dom.bcOffset,2,1); end
if isfield(Dom,'X')
warning('X not available for Dom.type = equispace or chebyshev')
end
case 'usergiven'
if isfield(Dom,'bcOffset')
warning('bcOffset not available for usergiven Dom.type'), end
assert(isfield(Dom,'X'),'X required for Dom.type = usergiven')
otherwise
error([Dom.type ' is unknown Dom.type'])
end%switch Dom.type
%{
\end{matlab}
\subsection{The code to make patches and interpolation}
First, store the pointer to the time derivative function in
the struct.
\begin{matlab}
%}
patches.fun=fun;
%{
\end{matlab}
Second, store the order of interpolation that is to provide
the values for the inter-patch coupling conditions. Spectral
coupling is \verb|ordCC| of~$0$ and~$-1$.
\begin{matlab}
%}
assert((ordCC>=-1) & (floor(ordCC)==ordCC), ...
'ordCC out of allowed range integer>=-1')
%{
\end{matlab}
For odd~\verb|ordCC|, interpolate based upon odd
neighbouring patches as is useful for staggered grids.
\begin{matlab}
%}
patches.stag=mod(ordCC,2);
ordCC=ordCC+patches.stag;
patches.ordCC=ordCC;
%{
\end{matlab}
Check for staggered grid and periodic case.
\begin{matlab}
%}
if patches.stag, assert(mod(nPatch,2)==0, ...
'Require an even number of patches for staggered grid')
end
%{
\end{matlab}
Third, set the centre of the patches in the macroscale grid
of patches, depending upon \verb|Dom.type|.
\begin{matlab}
%}
switch Dom.type
%{
\end{matlab}
%: case periodic
The periodic case is evenly spaced within the spatial domain.
Store the size ratio in \verb|patches|.
\begin{matlab}
%}
case 'periodic'
X=linspace(Xlim(1),Xlim(2),nPatch+1);
DX=X(2)-X(1);
X=X(1:nPatch)+diff(X)/2;
pEI=patches.EdgyInt;% abbreviation
if pre2023, dx = ratio*DX/(nSubP-1-pEI)*(2-pEI);
else ratio = dx/DX*(nSubP-1-pEI)/(2-pEI); end
patches.ratio=ratio;
%{
\end{matlab}
In the case of macro-periodicity, precompute the weightings
to interpolate field values for coupling.
\todo{Might sometime extend to coupling via derivative values.}
\begin{matlab}
%}
if ordCC>0
[Cwtsr,Cwtsl] = patchCwts(ratio,ordCC,patches.stag);
patches.Cwtsr = Cwtsr; patches.Cwtsl = Cwtsl;
end
%{
\end{matlab}
%: case equispace
The equi-spaced case is also evenly spaced but with the
extreme edges aligned with the spatial domain boundaries,
modified by the offset.
\begin{matlab}
%}
case 'equispace'
X=linspace(Xlim(1)+((nSubP-1)/2-Dom.bcOffset(1))*dx ...
,Xlim(2)-((nSubP-1)/2-Dom.bcOffset(2))*dx ,nPatch);
DX=diff(X(1:2));
width=(1+patches.EdgyInt)/2*(nSubP-1-patches.EdgyInt)*dx;
if DX<width*0.999999
warning('too many equispace patches (double overlapping)')
end
%{
\end{matlab}
%: case chebyshev
The Chebyshev case is spaced according to the Chebyshev
distribution in order to reduce macro-interpolation errors,
\(X_i \propto -\cos(i\pi/N)\), but with the extreme edges
aligned with the spatial domain boundaries, modified by the
offset, and modified by possible `boundary
layers'.\footnote{ However, maybe overlapping patches near a
boundary should be viewed as some sort of spatial analogue
of the `christmas tree' of projective integration and its
projection to a slow manifold. Here maybe the overlapping
patches allow for a `christmas tree' approach to the
boundary layers. Needs to be explored??}
\begin{matlab}
%}
case 'chebyshev'
halfWidth=dx*(nSubP-1)/2;
X1 = Xlim(1)+halfWidth-Dom.bcOffset(1)*dx;
X2 = Xlim(2)-halfWidth+Dom.bcOffset(2)*dx;
% X = (X1+X2)/2-(X2-X1)/2*cos(linspace(0,pi,nPatch));
%{
\end{matlab}
Search for total width of `boundary layers' so that in the
interior the patches are non-overlapping Chebyshev. But
the width for assessing overlap of patches is the following
variable \verb|width|.
\begin{matlab}
%}
width=(1+patches.EdgyInt)/2*(nSubP-1-patches.EdgyInt)*dx;
for b=0:2:nPatch-2
DXmin=(X2-X1-b*width)/2*( 1-cos(pi/(nPatch-b-1)) );
if DXmin>width, break, end
end
if DXmin<width*0.999999
warning('too many Chebyshev patches (mid-domain overlap)')
end
%{
\end{matlab}
Assign the centre-patch coordinates.
\begin{matlab}
%}
X = [ X1+(0:b/2-1)*width ...
(X1+X2)/2-(X2-X1-b*width)/2*cos(linspace(0,pi,nPatch-b)) ...
X2+(1-b/2:0)*width ];
%{
\end{matlab}
%: case usergiven
The user-given case is entirely up to a user to specify, we just
force it to have the correct shape of a row.
\begin{matlab}
%}
case 'usergiven'
X = reshape(Dom.X,1,[]);
end%switch Dom.type
%{
\end{matlab}
Fourth, construct the microscale grid in each patch.
Reshape the grid to be 4D to suit dimensions
(micro,Vars,Ens,macro).
\begin{matlab}
%}
assert(patches.EdgyInt | mod(nSubP,2)==1, ...
'configPatches1: nSubP must be odd')
i0=(nSubP+1)/2;
patches.x = reshape( dx*(-i0+1:i0-1)'+X ,nSubP,1,1,nPatch);
%{
\end{matlab}
\subsection{Set ensemble inter-patch communication}
For \verb|EdgyInt| or centre interpolation respectively,
\begin{itemize}
\item the right-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to left-edge~\verb|le|,
and
\item the left-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to~\verb|re|.
\end{itemize}
\verb|re| and \verb|li| are `transposes' of each other as
\verb|re(li)=le(ri)| are both \verb|1:nEnsem|.
Alternatively, one may use the statement
\begin{verbatim}
c=hankel(c(1:nSubP-1),c([nSubP 1:nSubP-2]));
\end{verbatim}
to \emph{correspondingly} generates all phase shifted copies
of microscale heterogeneity (see \verb|homoDiffEdgy1| of
\cref{sec:homoDiffEdgy1}).
The default is nothing shifty. This setting reduces the
number of if-statements in function \verb|patchEdgeInt1()|.
\begin{matlab}
%}
nE = patches.nEnsem;
patches.le = 1:nE;
patches.ri = 1:nE;
%{
\end{matlab}
However, if heterogeneous coefficients are supplied via
\verb|hetCoeffs|, then do some non-trivial replications.
First, get microscale periods, patch size, and replicate
many times in order to subsequently sub-sample: \verb|nSubP|
times should be enough. If \verb|cs| is more then 2D, then
the higher-dimensions are reshaped into the 2nd dimension.
\begin{matlab}
%}
if ~isempty(cs)
[mx,nc] = size(cs);
nx = nSubP(1);
cs = repmat(cs,nSubP,1);
%{
\end{matlab}
If only one member of the ensemble is required, then
sub-sample to patch size, and store coefficients in
\verb|patches| as is.
\begin{matlab}
%}
if nE==1, patches.cs = cs(1:nx-1,:); else
%{
\end{matlab}
But for $\verb|nEnsem|>1$ an ensemble of
$m_x$~phase-shifts of the coefficients is constructed from
the over-supply. Here code phase-shifts over the
periods---the phase shifts are like Hankel-matrices.
\begin{matlab}
%}
patches.nEnsem = mx;
patches.cs = nan(nx-1,nc,mx);
for i = 1:mx
is = (i:i+nx-2);
patches.cs(:,:,i) = cs(is,:);
end
patches.cs = reshape(patches.cs,nx-1,nc,[]);
%{
\end{matlab}
Further, set a cunning left\slash right realisation of
inter-patch coupling. The aim is to preserve symmetry in
the system when also invoking \verb|EdgyInt|. What this
coupling does without \verb|EdgyInt| is unknown. Use
auto-replication.
\begin{matlab}
%}
patches.le = mod((0:mx-1)'+mod(nx-2,mx),mx)+1;
patches.ri = mod((0:mx-1)'-mod(nx-2,mx),mx)+1;
%{
\end{matlab}
Issue warning if the ensemble is likely to be affected by
lack of scale separation. Need to justify this and the
arbitrary threshold more carefully??
\begin{matlab}
%}
if ratio*patches.nEnsem>0.9, warning( ...
'Probably poor scale separation in ensemble of coupled phase-shifts')
scaleSeparationParameter = ratio*patches.nEnsem
end
%{
\end{matlab}
End the two if-statements.
\begin{matlab}
%}
end%if-else nEnsem>1
end%if not-empty(cs)
%{
\end{matlab}
\paragraph{If parallel code} then first assume this is not
within an \verb|spmd|-environment, and so we invoke
\verb|spmd...end| (which starts a parallel pool if not
already started). At this point, the global \verb|patches|
is copied for each worker processor and so it becomes
\emph{composite} when we distribute any one of the fields.
Hereafter, {\em all fields in the global variable
\verb|patches| must only be referenced within an
\verb|spmd|-environment.}%
\footnote{If subsequently outside spmd, then one must use
functions like \texttt{getfield(patches\{1\},'a')}.}
\begin{matlab}
%}
if patches.parallel
% theparpool=gcp()
spmd
%{
\end{matlab}
Second, choose to slice parallel workers in the spatial
direction.
\begin{matlab}
%}
pari = 1;
patches.codist=codistributor1d(3+pari);
%{
\end{matlab}
\verb|patches.codist.Dimension| is the index that is split
among workers. Then distribute the coordinate direction
among the workers: the function must be invoked inside an
\verb|spmd|-group in order for this to work---so we do not
need \verb|parallel| in argument list.
\begin{matlab}
%}
switch pari
case 1, patches.x=codistributed(patches.x,patches.codist);
otherwise
error('should never have bad index for parallel distribution')
end%switch
end%spmd
%{
\end{matlab}
If not parallel, then clean out \verb|patches.codist| if it
exists. May not need, but safer.
\begin{matlab}
%}
else% not parallel
if isfield(patches,'codist'), rmfield(patches,'codist'); end
end%if-parallel
%{
\end{matlab}
\paragraph{Fin}
\begin{matlab}
%}
end% function
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
Combescure2022.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/Combescure2022.m
| 20,001 |
utf_8
|
1e16325003790d6ce54ef341008ceea9
|
% For an example nonlinear elasticity in 1D, simulate and
% use MatCont to continue parametrised equilibria. An
% example of working via patches in space. Adapted from the
% example Figure 3(a) of Combescure(2022). AJR Nov 2022 --
% Jan 2023
%!TEX root = doc.tex
%{
\section{\texttt{Combescure2022}: simulation and
continuation of a 1D example nonlinear elasticity, via
patches}
\label{sec:Combescure2022}
Here we explore a nonlinear 1D elasticity problem with
complicated microstructure. Executes a simulation.
\emph{But the main aim is to show how one may use MatCont
continuation toolbox \cite[]{Govaerts2019} together with the
Patch Scheme toolbox} \cite[]{Maclean2020a} in order to
explore parameter space by continuing branches of
equilibria, etc.
\begin{figure}
\centering
\caption{\label{fig:toyElas}1D arrangement of non-linear
springs with connections to (a) next-to-neighbour node
\protect\cite[Fig.~3(a)]{Combescure2022}. The blue box is
one cell of one period, width~\(2b\), containing an odd and
an even~\(i\).}
\setlength{\unitlength}{0.01\linewidth}
\begin{picture}(100,31)
\put(0,0){\framebox(100,31){}}
\put(0,0){\includegraphics[width=\linewidth]{Figs/toyElas}}
\put(36,4){\color{blue}\framebox(27,23){cell}}
\end{picture}
\end{figure}
\cref{fig:toyElas} shows the microscale elasticity---adapted
from Fig.~3(a) by \cite{Combescure2022}. Let the spatial
microscale lattice be at rest at points~\(x_i\), with
constant spacing~\(b\). With displacement
variables~\(u_i(t)\), simulate the microscale lattice toy
elasticity system with 2-periodicity: for \(p=1,2\)
(respectively black and red in \cref{fig:toyElas}) and for
every~\(i\),
\begin{align}
&\epsilon^p_i:=\frac1{pb}(u_{i+p/2}-u_{i-p/2}),
&&\sigma^p_i:=w'_p(\epsilon^p_i),
\nonumber\\
&\DD t{u_{i}}= \sum_{p=1}^2\frac1{pb?}(\sigma^p_{i+p/2}-\sigma^p_{i-p/2}),
&&w'_p(\epsilon):=\epsilon-M_p\epsilon^3+\epsilon^5.
\label{eq:heteroNLE}
\end{align}
The system has a microscale heterogeneity via the two
different functions~\(w'_p(\epsilon)\)
\cite[\S4]{Combescure2022}:
\begin{itemize}
\item microscale `instability' (structure) arises with
\(M_1:=2\) and \(M_2:=1\)
(\cref{fig:Comb22diffuSvis2b,fig:Comb22cpl}(b)); and
\item large scale `instability' (structure) arises with
\(M_1:=-1\) and \(M_2:=3\)
(\cref{fig:Comb22diffuLvis1,fig:Comb22cpl}(a)).
\end{itemize}
\paragraph{Microscale case} Set \(M_1:=2\) and \(M_2:=1\)\,.
We fix the boundary conditions \(u(0)=0\) and parametrise
solutions by~\(u(L)\). There are equilibria \(u\approx
u(L)x/L\), but under large compression (large
negative~\(u(L)\)) interesting structures develop.
\cref{fig:Comb22diffuSvis2b} shows boundary layers with
microscale variations develop for \(u(L)<-13\). This figure
plots a strain~\(\epsilon\) as the strain is nearly constant
across the interior, so the boundary layers show up clearly.
As~\(u(L)\) decreases further, \cref{fig:Comb22diffuSvis2b}
shows the family of equilibria form complicated folds.
\cref{tblMicro} lists that MatCont also reports some branch
points and neutral saddle equilibria in this same regime
(see \cref{fig:Comb22cpl}(b)). I have not yet followed any
of the branches.
\begin{SCfigure}
\centering
\caption{\label{fig:Comb22diffuSvis2b}the case of microscale
`instability' appears as fluctuations close to both
boundaries. As the system is physically compressed, the
equilibrium curve has complicated folds, as shown here (and
\cref{fig:Comb22cpl}(b)).}
\includegraphics[scale=0.8]{Comb22diffuSvis2b}
\end{SCfigure}
\begin{SCtable}
\centering\caption{\label{tblMicro}Interesting equilibria
for the cases of small scale instability: \(M_1:=2\),
\(M_2:=1\) (\cref{fig:Comb22diffuSvis2b,fig:Comb22cpl}(b)).
The rightmost column gives the \(-u(L)\)~parameter values
for corresponding critical points in the three-patch code
(\cref{fig:Comb22diffuSvis2N3}).}
\begin{tabular}{@{}rp{12.1em}r@{}}
\hline
$-u(L)$&MatCont description &\text{Patch}\\\hline
14.684 & Branch point &14.599\\
14.702 & Limit point &14.610\\
14.612 & Neutral Saddle Equilibrium &-\\
14.063 & Neutral Saddle Equilibrium &-\\
13.972 & Limit point &13.817\\
13.988 & Branch point &13.828\\
17.184 & Branch point &17.197\\
- & Limit point &17.227\\
17.183 & Neutral Saddle Equilibrium &17.211\\
%15.034 & Neutral Saddle Equilibrium \\
%15.024 & Limit point \\
%15.032 & Branch point \\
%17.987 & Branch point \\
%17.993 & Limit point \\
%17.987 & Neutral Saddle Equilibrium \\
\hline
\end{tabular}
\end{SCtable}
The previous paragraph's discussion is for a full domain
simulation, albeit done through an imposed computational
framework of physically abutting patches.
\cref{fig:Comb22diffuSvis2N3} shows the corresponding
MatCont continuation for the patch scheme with \(N=3\)
patches in the domain. Just three patches may well be
reasonable as the structures in this problem are the two
boundary layers, and a constant interior.
\cref{fig:Comb22diffuSvis2N3} shows the patch scheme
reasonably resolves these. \cref{tblMicro} also lists the
special points, as reported by MatCont, in the equilibria of
the patch scheme. The locations of these special points
reasonably match those found by the full domain simulation.
Importantly, MatCont is about \emph{ten times quicker to
execute on the patches} than on the full domain code. This
speed-up indicates that on larger scale problems the patch
scheme could be very useful in continuation explorations.
\begin{SCfigure}
\centering
\caption{\label{fig:Comb22diffuSvis2N3}using just three
patches, the case of microscale instability appears as
fluctuations close to both boundaries. As the system is
physically compressed, the equilibrium curve has complicated
folds, as shown, and that approximately match
\cref{fig:Comb22diffuSvis2b}. But it is computed ten times
quicker.}
\includegraphics[scale=0.8]{Comb22diffuSvis2N3}
\end{SCfigure}
\paragraph{Large scale case} Set \(M_1:=-1\) and
\(M_2:=3\)\,. We fix the boundary conditions \(u(0)=0\) and
parametrise solutions by~\(u(L)\). There are equilibria
\(u\approx u(L)x/L\), but under large compression (large
negative~\(u(L)\)) interesting structures develop.
\cref{fig:Comb22diffuLvis1} shows an interior region of
higher magnitude strain develops. Again, this figure plots a
strain~\(\epsilon\) as the strain is nearly constant across
the domain, so the interior structure shows up clearly.
As~\(u(L)\) decreases further, \cref{fig:Comb22diffuLvis1}
shows the family of equilibria form complicated folds.
\cref{tblLarge} lists that MatCont also reports some branch
points and neutral saddle equilibria in this regime (see
\cref{fig:Comb22cpl}(a)). I have not yet followed any of the
branches.
\begin{SCfigure}
\centering
\caption{\label{fig:Comb22diffuLvis1}the case of large scale
`instability'. Spatial structure appears in the middle of
the domain. As the system is physically compressed, the
equilibrium curve has complicated folds, as shown here and
in \cref{fig:Comb22cpl}(a).}
\includegraphics[scale=0.8]{Comb22diffuLvis1}
\end{SCfigure}
\begin{SCtable}
\centering\caption{\label{tblLarge}Interesting equilibria
for the cases of large scale instability: \(M_1:=-1\),
\(M_2:=3\) (\cref{fig:Comb22diffuLvis1,fig:Comb22cpl}(a)).}
\begin{tabular}{@{}rp{12.1em}r@{}}
\hline
$-u(L)$&MatCont description \\\hline
21.295 & Limit point \\
18.783 & Branch point \\
18.762 & Neutral Saddle Equilibrium \\
18.761 & Neutral Saddle Equilibrium \\
18.761 & Limit point \\
18.934 & Branch point \\
19.393 & Branch point \\
19.928 & Branch point \\
20.490 & Branch point \\
21.055 & Branch point \\
21.627 & Branch point \\
\hline
\end{tabular}
% these are from N=3 patches
%21.469 & Branch point \\
%23.342 & Neutral Saddle Equilibrium \\
%23.462 & Branch point \\
%29.95 & Hopf \\
\end{SCtable}
The patch scheme with \(N=3\) patches does not make
reasonable predictions here. I suspect this failure is
because the nontrivial interior structure here occupies too
much of the domain to fit into one `small' patch. Here the
patch scheme may be useful if the physical domain is larger.
\subsection{Configure heterogeneous toy elasticity systems}
\label{sec:chtes}
Set some physical parameters. Each cell is of
width~\(dx:=2b\) as I choose to store~\(u_i\) for odd~\(i\)
in \verb|u((i+1)/2,1,:)| and for even~\(i\) in
\verb|u(i/2,2,:)|, that is, the the physical displacements
form the array
\begin{equation*}
\verb|u|=\begin{bmatrix} u_1&u_2\\ u_3&u_4\\ u_5&u_6\\ \vdots&\vdots \end{bmatrix}.
\end{equation*}
Then corresponding velocities are adjoined as 3rd and 4th column.
\begin{matlab}
%}
clear all
global b M vis
b = 1 % separation of lattice points
N = 42 % # lattice steps in L
L = b*N % length of domain
%{
\end{matlab}
The nonlinear coefficients of stress-strain are in
array~\verb|M|, chosen by~\verb|theCase|.
\begin{matlab}
%}
theCase = 2
switch theCase
case 1, M = [0 0 0 0] % linear spring coefficients
case 2, M = [ 2 1 1 1] % micro scale instability??
case 3, M = [-1 3 1 1] % large scale instability??
end% switch
vis = 0.1 % does not appear to affect the equilibria
tEnd = 25
%{
\end{matlab}
Patch parameters: here \verb|nSubP| is the number of cells.
\begin{matlab}
%}
edgyInt = true
nSubP = 6, nPatch = 5 % gives full-domain on N=42, dx=2
%nSubP = 6, nPatch = 3 % patches for some crude comparison
%{
\end{matlab}
Establish the global data struct~\verb|patches| for the
microscale heterogeneous lattice elasticity
system~\cref{eq:heteroNLE}. Solved with \verb|nPatch|
patches, and interpolation (as high-order as possible) to
provide the edge-values of the inter-patch coupling
conditions.
\begin{matlab}
%}
global patches
configPatches1(@heteroNLE,[0 L],'equispace',nPatch ...
,0,2*b,nSubP,'EdgyInt',edgyInt);
xx = patches.x+[-1 1]*b/2; % staggered sub-cell positions
%{
\end{matlab}
\subsection{Simulate in time}
Set the initial displacement and velocity of a simulation.
Integrate some time using standard integrator.
\begin{matlab}
%}
u0 = [ sin(pi/L*xx) -0*0.14*cos(pi/L*xx) ];
tic
[ts,ust] = ode23(@patchSys1, tEnd*linspace(0,1,41), u0(:) ...
,[],patches,0);
cpuIntegrateTime = toc
%{
\end{matlab}
\paragraph{Plot space-time surface of the simulation} To see
the edge values of the patches, interpolate and then adjoin
a row of \verb|nan|s between patches. Because of the
odd/even storage we need to do a lot of permuting and
reshaping. First, array of sub-cell coordinates in a
column for each patch, separating patches also by an extra
row of nans.
\begin{matlab}
%}
xs = reshape( permute( xx ,[2 1 3 4]), 2*nSubP,nPatch);
xs(end+1,:) = nan;
%{
\end{matlab}
Interpolate patch edge values, at all times simultaneously
by including time data into the 2nd dimension, and 2nd
reshaping it into the 3rd dimension.
\begin{matlab}
%}
uvs = reshape( permute( reshape(ust ...
,length(ts),nSubP,4,1,nPatch) ,[2 3 1 4 5]) ,nSubP,[],1,nPatch);
uvs = reshape( patchEdgeInt1(uvs) ,nSubP,4,[],nPatch);
%{
\end{matlab}
Extract displacement field, merge the 1st two columns,
permute the time variations to the 3rd, separate patches by
NaNs, and merge spatial data into the 1st column.
\begin{matlab}
%}
us = reshape( permute( uvs(:,1:2,:,:) ...
,[2 1 4 3]) ,2*nSubP,nPatch,[]);
us(end+1,:,:) = nan;
us = reshape(us,[],length(ts));
%{
\end{matlab}
Plot space-time surface of displacements over the macroscale
duration of the simulation.
\begin{matlab}
%}
figure(1), clf()
mesh(ts,xs(:),us)
view(60,40), colormap(0.8*jet), axis tight
xlabel('time t'), ylabel('space x'), zlabel('u(x,t)')
%{
\end{matlab}
Ditto for the velocity.
\begin{matlab}
%}
vs = reshape( permute( uvs(:,3:4,:,:) ...
,[2 1 4 3]) ,2*nSubP,nPatch,[]);
vs(end+1,:,:) = nan;
vs = reshape(vs,[],length(ts));
figure(2), clf()
mesh(ts,xs(:),vs)
view(60,40), colormap(0.8*jet), axis tight
xlabel('time t'), ylabel('space x'), zlabel('v(x,t)')
drawnow
%{
\end{matlab}
\subsection{MatCont continuation}
First, use \verb|fsolve| to find an equilibrium at some
starting compressive displacement---a compression that
differs depending upon the case of nonlinearity.
\begin{matlab}
%}
muL0 = 12+6*(theCase==3)
u0 = [ -muL0*xx/L 0*xx ];
u0([1 end],:,:,:)=nan;
patches.i = find(~isnan(u0));
nVars=length(patches.i)
ueq=fsolve(@(v) dudtSys(0,v,muL0),u0(patches.i));
%{
\end{matlab}
Start search for equilibria at other compression parameters.
Starting from zero, need 1000+ to find both the large-scale
and small-scale instability cases. But need less points
when starting from parameter~\(12\) or so.
\begin{matlab}
%}
disp('Searching for equilibria, may take 1000+ secs')
[uv0,vec0]=init_EP_EP(@matContSys,ueq,muL0,[1]);
opt=contset; % initialise MatCont options
opt=contset(opt,'Singularities',true); %to report branch points, p.24
opt=contset(opt,'MaxNumPoints',400); % restricts how far matcont goes
opt=contset(opt,'Backward',true); % strangely, needs to go backwards??
[uv,vec,s,h,f]=cont(@equilibrium, uv0, [], opt); %MatCont continuation
%{
\end{matlab}
\paragraph{Post-process the report}
\begin{matlab}
%}
disp('List of interesting critical points')
muLs=uv(nVars+1,:);
for j=1:numel(s)
disp([num2str(muLs(s(j).index),5) ' & ' s(j).msg ' \\'])
end
%{
\end{matlab}
Find a range of parameter and corresponding indices where
all the critical points occur.
\begin{matlab}
%}
p1=muLs(end); pe=muLs(1);
if numel(s)>3, for j=2:numel(s)-1
p1=min(p1,muLs(s(j).index));
pe=max(pe,muLs(s(j).index));
end, end
pMid=(p1+pe)/2, pWid=abs(pe-p1)
iPars=find(abs(muLs(:)-pMid)<pWid);%include some either side
%{
\end{matlab}
Choose an `evenly spaced' subset of the range so we only
plot up to sixty of the parameter values reported in the
range.
\begin{matlab}
%}
nPars=numel(iPars)
dP=ceil((nPars-1)/60)
iP=1:dP:nPars;
muLP=muLs(iPars(iP));
%{
\end{matlab}
Interpolate patch edge values, at all parameters
simultaneously by including parameter-wise data into the 2nd
dimension, and 2nd reshaping it into the 3rd dimension.
\begin{matlab}
%}
uvs=nan(numel(iP),numel(u0));
uvs(:,patches.i)=uv(1:nVars,iPars(iP))';
uvs = reshape( permute( reshape(uvs ...
,length(muLP),nSubP,4,1,nPatch) ,[2 3 1 4 5]) ,nSubP,[],1,nPatch);
uvs = reshape( patchEdgeInt1(uvs) ,nSubP,4,[],nPatch);
%{
\end{matlab}
Extract displacement field, merge the 1st two columns,
permute the parameter variations to the 3rd, separate
patches by NaNs, and merge spatial data into the 1st column.
\begin{matlab}
%}
us = reshape( permute( uvs(:,1:2,:,:) ...
,[2 1 4 3]) ,2*nSubP,nPatch,[]);
us(end+1,:,:) = nan;
us = reshape(us,[],length(muLP));
%{
\end{matlab}
Plot space-time surface of displacements over the macroscale
duration of the simulation.
\begin{matlab}
%}
figure(4), clf()
mesh(muLP,xs(:),us)
view(60,40), colormap(0.8*jet), axis tight
xlabel('-u(L)'), ylabel('space x'), zlabel('u(x)')
%{
\end{matlab}
Plot space-time surface of strain, differences in
displacements, over the parameter variation.
\begin{matlab}
%}
figure(5), clf()
mesh(muLP,xs(1:end-1),diff(us))
view(45,20), colormap(0.8*jet), axis tight
xlabel('-u(L)'), ylabel('space x'), zlabel('strain \delta u(x)')
set(gcf,'PaperPosition',[0 0 12 9])
print('-depsc',['Figs/Comb22diffu' num2str(theCase) '.eps'])
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:Comb22cpl}cross-sections through
\cref{fig:Comb22diffuLvis1,fig:Comb22diffuSvis2b}: (a)~large
scale case, at the mid-point in space of
\cref{fig:Comb22diffuLvis1}; (b)~microscale case, in a
boundary layer of \cref{fig:Comb22diffuSvis2b}. These
cross-sections are labelled with the various critical
points.}
\begin{tabular}{@{}cc@{}}
(a) large scale case & (b) microscale case\\
\includegraphics[scale=0.75]{Figs/Comb22cpl3}&
\includegraphics[scale=0.75]{Figs/Comb22cpl2}
\end{tabular}
\end{figure}
\paragraph{Labelled parameter plot} Get the labelled 2D
plots of \cref{fig:Comb22cpl} via MatCont's \verb|cpl|
function. In high-D problems it is unlikely that any one
variable is a good thing to plot, so I show how to plot
something else, here a strain. I use all the computed points
so reform~\verb|uvs| (possibly better to have merged the
critical points into the list of plotted parameters??).
\begin{matlab}
%}
uvs = nan(numel(muLs),numel(u0));
uvs(:,patches.i) = uv(1:nVars,:)';
uvs = reshape( uvs ,[],nSubP,4,nPatch);
%{
\end{matlab}
As a function of the parameter, plot the strain in the
middle of the domain (the middle of the middle patch),
unless it is the microscale case when we plot a strain near
the middle of the left boundary layer.
\begin{matlab}
%}
if theCase==2, thePatch=1;
else thePatch=(nPatch+1)/2;
end%if
figure(7),clf
du = diff( uvs(:,nSubP/2,1:2,thePatch) ,1,3);
cpl([muLs;du'],[],s);
xlabel('-u(L)')
if thePatch==1, ylabel('boundary layer strain')
else ylabel('mid-domain strain')
end
set(gcf,'PaperPosition',[0 0 9 7])
print('-depsc',['Figs/Comb22cpl' num2str(theCase) '.eps'])
%{
\end{matlab}
\subsection{\texttt{matContSys}: basic function for MatCont analysis}
This is the simple `odefile' of the patch scheme wrapped
around the microcode.
\begin{matlab}
%}
function out = matContSys%(t,coordinates,flag,y,z)
out{1} = [];%@init;
out{2} = @dudtSys;
out{3} = [];%@jacobian;
out{4} = [];%@jacobianp;
out{5} = [];%@hessians;
out{6} = [];%@hessiansp;
out{7} = [];
out{8} = [];
out{9} = [];
end% function matContSys
%{
\end{matlab}
\subsection{\texttt{dudtSys()}: wraps around the patch wrapper}
This function adjoins \verb|patches| to the argument list,
places the variables within the patch structure, and then
extracts their time derivatives to return. Used by both
MatCont and \verb|fsolve|.
\begin{matlab}
%}
function ut = dudtSys(t,u,p)
global patches
U=repmat(nan+patches.x,1,4,1,1);
U(patches.i)=u(:);
Ut=patchSys1(t,U,patches,p);
ut=Ut(patches.i);
end
%{
\end{matlab}
\subsection{\texttt{heteroNLE()}: forced heterogeneous elasticity}
\label{sec:heteroNLE}
This function codes the lattice heterogeneous example
elasticity inside the patches. Computes the time derivative
at each point in the interior of a patch, output
in~\verb|uvt|.
\begin{matlab}
%}
function uvt = heteroNLE(t,uv,patches,muL)
if nargin<4, muL=0; end% default end displacement is zero
global b M vis
%{
\end{matlab}
Separate state vector into displacement and velocity fields:
\(u_{ijI}\)~is the displacement at the \(j\)th~point in the
\(i\)th 2-cell in the \(I\)th~patch; similarly for
velocity~\(v_{ijI}\). That is, physically neighbouring
points have different~\(j\), whereas physical
next-to-neighbours have \(i\)~different by one.
\begin{matlab}
%}
u=uv(:,1:2,:,:); v=uv(:,3:4,:,:); % separate u and v=du/dt
%{
\end{matlab}
Provide boundary conditions, here fixed displacement and
velocity in the left/right sub-cells of the
leftmost/rightmost patches.
\begin{matlab}
%}
u(1,:,:,1)=0;
v(1,:,:,1)=0;
u(end,:,:,end)=-muL;
v(end,:,:,end)=0;
%{
\end{matlab}
Compute the two different strain fields, and also a first
derivative for some optional viscosity.
\begin{matlab}
%}
eps2 = diff(u)/(2*b);
eps1 = [u(:,2,:,:)-u(:,1,:,:) u([2:end 1],1,:,:)-u(:,2,:,:)]/b;
eps1(end,2,:,:)=nan; % as this value is fake
vx1 = [v(:,2,:,:)-v(:,1,:,:) v([2:end 1],1,:,:)-v(:,2,:,:)]/b;
vx1(end,2,:,:)=nan; % as this value is fake
%{
\end{matlab}
Set corresponding nonlinear stresses
\begin{matlab}
%}
sig2 = eps2-M(2)*eps2.^3+M(4)*eps2.^5;
sig1 = eps1-M(1)*eps1.^3+M(3)*eps1.^5;
%{
\end{matlab}
Preallocate output array, and fill in time derivatives of
displacement and velocity, from velocity and gradient of
stresses, respectively.
\begin{matlab}
%}
uvt = nan+uv; % preallocate output array
i=2:size(uv,1)-1;
% rate of change of position
uvt(i,1:2,:,:) = v(i,:,:,:);
% rate of change of velocity +some artificial viscosity??
uvt(i,3:4,:,:) = diff(sig2) ...
+[ sig1(i,1,:,:)-sig1(i-1,2,:,:) diff(sig1(i,:,:,:),1,2)] ...
+vis*[ vx1(i,1,:,:)-vx1(i-1,2,:,:) diff(vx1(i,:,:,:),1,2) ];
%{
\end{matlab}
\begin{matlab}
%}
end% function heteroNLE
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
elastic2Dstaggered.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/elastic2Dstaggered.m
| 10,276 |
utf_8
|
d292f24139a8d4f68f460dc05e1e062a
|
% The aim is to simulate a heterogeneous 2D beam using an
% Equation-free Patch Scheme. Here we code patches to use a
% microscale staggered grid of the microscale heterogeneous
% elasticity PDEs. This function computes the time
% derivatives given that interpolation has provided the
% patch-edge values, except we code boundary conditions on
% extreme patches. AJR, 20 Aug 2022 -- 4 Feb 2023
%!TEX root = doc.tex
%{
\subsection{\texttt{elastic2Dstaggered()}: \(\D t{}\) of 2D
heterogeneous elastic patch on staggered grid}
\label{secelastic2Dstaggered}
Let's try a staggered microgrid for patches of heterogeneous
2D elasticity forming a 2D beam. \cref{figpatchgridv} draw
the microgrid in a patches: the microgrid is akin to that by
\cite{Virieux86}.
\begin{matlab}
%}
function [Ut]=elastic2Dstaggered(t,U,patches)
%{
\end{matlab}
\paragraph{Input} \begin{itemize}
\item \verb|t| is time (real scalar).
\item \verb|U| is vector of \((u,v,\dot u,\dot v)\) values
in each and every patch.
\item \verb|patches| data structure from \verb|configPatches|,
with extra physical parameters.
\end{itemize}
\paragraph{Output} \begin{itemize}
\item \verb|Ut| is corresponding vector of time derivatives
of~\verb|U|
\end{itemize}
\paragraph{Unpack the data vector} Form data vector into a
4D array: \verb|nx|~is the number of points along a patch;
\verb|Nx|~is the number of patches.
\begin{matlab}
%}
[nx,~,~,Nx] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round(numel(U)/numel(patches.x)/nEnsem);
U = reshape(U,nx,nVars,nEnsem,Nx);
%{
\end{matlab}
\input{Figs/figpatchgridv}
Set microgrid parameters of patches like
\cref{figpatchgridv}.
\begin{matlab}
%}
ny=(nVars+2)/4;
nny=2*ny-1;
dx=diff(patches.x(2:3));
dy=dx; % now set by new sim script
i =2:nx-1; % indices for interior x
ix=1:nx-1;
ju=1:ny-1; % indices y structures of u, u_t
jv=1:ny; % indices y structures of v, v_t
jse=1:2:nny; jnw=2:2:nny; % indices of elasticity y structure
%{
\end{matlab}
Then split input field into the four physical fields.
\begin{matlab}
%}
u = U(:,ju ,:,:);
v = U(:,jv+ju(end),:,:);
ut= U(:,ju+nny,:,:);
vt= U(:,jv+nny+ju(end),:,:);
%{
\end{matlab}
Unpack the physical, microscale heterogeneous, elastic
parameters.
\begin{matlab}
%}
mu =patches.cs(:,1:nny);
lamb=patches.cs(:,2*ny:end);
visc=patches.viscosity;
%{
\end{matlab}
Temporary trace print.
\begin{matlab}
%}
if t<0
usz=size(u),us=squeeze(u);
vsz=size(v),vs=squeeze(v);
utsz=size(ut),uts=squeeze(ut);
vtsz=size(vt),vts=squeeze(vt);
musz=size(mu),mus=squeeze(mu);
lambsz=size(lamb),lambs=squeeze(lamb);
end
%{
\end{matlab}
\paragraph{Mathematical expression of elasticity} Strain
tensor \(\varepsilon_{ij} := \tfrac12 (u_{i,j} +u_{j,i})\)
is symmetric. Remember stress~\(\sigma_{ij}\) is the force
in the \(j\)th~direction across a surface whose normal is
the \(i\)th~direction. So across a surface whose normal
is~\nv, the stress is~\(\nv^T\sigma\),
equivalently~\(n_i\sigma_{ij}\).
Denote the 2D displacement vector by \(\uv=(u,v)\).
\footnote{Adapted from Wikipedia: linear elasticity:
Derivation of Navier--Cauchy equations} First, consider the
\(x\)-direction. Substitute the strain-displacement
equations into the equilibrium equation in the
\(x\)-direction to get
\begin{align*}&
\sigma_{xx} =2\mu \varepsilon_{xx} +\lambda
(\varepsilon_{xx} +\varepsilon_{yy}) =(2\mu+\lambda) {\D xu}
+\lambda {\D yv}
\\&
\sigma_{xy} = 2\mu \varepsilon_{xy} =\mu \left({\D yu} +{\D
xv}\right)
\end{align*}
\paragraph{Discretise in space} Form equi-spaced microscale
grid of spacing~\(dx,dy\) and indices~\(i,j\) in the
\(x,y\)-directions respectively (\cref{figpatchgridv}).
Field values are at various `quarter points' within the
microgrid elements (\ne, \nw, \sw, \se).
\begin{itemize}
\item locate \(u\) at \ne-points
\item locate \(v\) at \sw-points
\item evaluate diagonal strains \(\varepsilon_{xx},
\varepsilon_{yy}\) at \nw-points, also~\(\lambda,\mu\)
\item evaluate off-diagonal strains \(\varepsilon_{xy}
=\varepsilon_{yx}\) at \se-points, also~\(\mu\).
\item evaluate \pde{}s at the appropriate \sw,\ne~points, via
gradients of stresses from the \nw,\se~points.
\end{itemize}
All the above derivatives in space then involve simple
first differences from grid points half-spacing away. They do
\emph{not} involve any averaging. Such staggered spatial
discretisation is the best chance of best behaviour.
For interpolation between patches in the \(x\)-direction,
that edge values of~\(u,v\) are in zig-zag
positions makes absolutely no difference to the patch
interpolation schemes, since all coded schemes are invariant
to translations in the \(x\)-direction just so long as the
translation is the same across all patches for each of the
edge variables.
\paragraph{Physical boundary conditions on extreme patches}
Fixed boundaries are to simply code zero displacements and
zero time derivatives (velocities) at the boundaries. First
at the left edge of the leftmost patch:
\begin{matlab}
%}
tweak=1;% choose simple zero, or accurate one??
u(1,:,:,1) = +u(2,:,:,1)/5*tweak;
v(1,:,:,1) = -v(2,:,:,1)/3*tweak;
ut(1,:,:,1)= +ut(2,:,:,1)/5*tweak;
vt(1,:,:,1)= -vt(2,:,:,1)/3*tweak;
%{
\end{matlab}
Second, at the right edge of the rightmost patch: first
alternative is fixed boundary.
\begin{matlab}
%}
if ~patches.stressFreeRightBC
u(nx,:,:,Nx) = -u(nx-1,:,:,Nx)/3*tweak;
v(nx,:,:,Nx) = +v(nx-1,:,:,Nx)/5*tweak;
ut(nx,:,:,Nx)= -ut(nx-1,:,:,Nx)/3*tweak;
vt(nx,:,:,Nx)= +vt(nx-1,:,:,Nx)/5*tweak;
%{
\end{matlab}
otherwise code a stress free boundary at the location of the
\(x\)-direction displacements and velocities (as for the
top-bottom boundaries).
\begin{matlab}
%}
else% patches.stressFreeRightBC
%{
\end{matlab}
Need \verb|sxy| (below) to be computed zero at the
bdry---assume \(u\) fattened by zero difference in~\(y\) at
top/bottom. Later set \verb|sxx| to zero.
\begin{matlab}
%}
uDy = diff(u(nx-1,:,:,Nx),1,2);
v(nx,:,:,Nx) = v(nx-1,:,:,Nx)-dx/dy*[0 uDy 0];
%{
\end{matlab}
For phenomenological viscosity purposes assume \(\D x{\dot
u}=\D x{\dot v}=0\) at the free boundary.
\begin{matlab}
%}
vt(nx,:,:,Nx) = vt(nx-1,:,:,Nx);
ut(nx,:,:,Nx) = ut(nx-2,:,:,Nx);
end%if ~patches.stressFreeRightBC
%{
\end{matlab}
\paragraph{Patch-interior elasticity} For the case of
\cref{figpatchgridv}, fatten~\verb|u| using zero stress on
top-bottom, although not really needed it does mean
that~\(\sigma_{xy}\) computed next is zero on the
top-bottom.
\begin{matlab}
%}
u= [nan(nx,1,nEnsem,Nx) u nan(nx,1,nEnsem,Nx) ];
u(ix,1 ,:,:)=u(ix,2 ,:,:)+dy/dx*diff(v(:,1 ,:,:));
u(ix,ny+1,:,:)=u(ix,ny,:,:)-dy/dx*diff(v(:,ny,:,:));
%{
\end{matlab}
\begin{itemize}
\item Compute stresses \(\sigma_{xy}\) at \se-points.
\begin{matlab}
%}
sxy = mu(ix,jse).*( diff(u(ix,:,:,:),1,2)/dy+diff(v)/dx );
%{
\end{matlab}
\item Compute stresses \(\sigma_{yy}\) at \nw-points
(omitting leftmost~\(\sigma_{yy}\)), fattening the array to
cater for ghost nodes. Little tricky with indices of
\nw-elasticity parameters as they cross over the `grid
lines'.
\begin{matlab}
%}
syy = nan(nx,ny+1,nEnsem,Nx);
syy(ix+1,ju+1,:,:) = ...
(2*mu(:,jnw)+lamb(:,jnw)).*diff(v(ix+1,:,:,:),1,2)/dy ...
+lamb(:,jnw).*diff(u(:,2:ny,:,:))/dx;
%{
\end{matlab}
\item Compute~\(\sigma_{xx}\) at \nw-points (omitting
leftmost \(i=1\)).
\begin{matlab}
%}
sxx = lamb(:,jnw).*diff(v(ix+1,:,:,:),1,2)/dy ...
+(2*mu(:,jnw)+lamb(:,jnw)).*diff(u(:,ju+1,:,:))/dx;
%{
\end{matlab}
\end{itemize}
\paragraph{Top-bottom boundary conditions} At the top-bottom
of the beam we need \(\sigma_{xy}=\sigma_{yy}=0\). Given the
micro-grid of \cref{figpatchgridv}, the first is already
catered for. Here use \(\sigma_{yy}=0\) at \sw~points on the
top-bottom to set ghost values.
\begin{matlab}
%}
syy(:, 1,:,:) = -syy(:,2 ,:,:);
syy(:,ny+1,:,:) = -syy(:,ny,:,:);
%{
\end{matlab}
Similarly for any stress-free right boundary condition
(remembering \verb|sxx| currently omits leftmost \(i=1\)).
\begin{matlab}
%}
if patches.stressFreeRightBC
sxx(nx-1,:,:,Nx) = -sxx(nx-2,:,:,Nx);
end
%{
\end{matlab}
Temporary trace print.
\begin{matlab}
%}
if t<0
sxysz=size(sxy),sxys=squeeze(sxy);
syysz=size(syy),syys=squeeze(syy);
sxxsz=size(sxx),sxxs=squeeze(sxx);
end
%{
\end{matlab}
\paragraph{Second derivatives for viscosity} This code is
for constant viscosity---if spatially varying, then modify
each to be two first-derivatives in each direction. The
\(x\)-derivatives are well-defined second differences.
\begin{matlab}
%}
utxx = visc*diff(ut,2,1)/dx^2;
vtxx = visc*diff(vt,2,1)/dx^2;
%{
\end{matlab}
On \cref{figpatchgridv}, and for the purpose of viscosity,
assume \(\D y{\dot u}=\D y{\dot v}=0\) on the top-bottom (we
just need `viscosity' to be some phenomenological
dissipation).
\begin{matlab}
%}
utyy = visc*diff(ut(i,[1 ju ny-1],:,:),2,2)/dy^2;
vtyy = visc*diff(vt(i,[2 jv ny-1],:,:),2,2)/dy^2;
%{
\end{matlab}
Temporary trace print.
\begin{matlab}
%}
if t<0
utxxsz=size(utxx),utxxs=squeeze(utxx);
vtxxsz=size(vtxx),vtxxs=squeeze(vtxx);
utyysz=size(utyy),utyys=squeeze(utyy);
vtyysz=size(vtyy),vtyys=squeeze(vtyy);
end
%{
\end{matlab}
\paragraph{Time derivatives} The rate of change of
displacement is the provided velocities: \(\D tu=\dot u\)
and \(\D tv=\dot v\). Time derivative array should really be
initialised to~\verb|nan|, but \verb|ode15s| chokes on any
\verb|nan|s at the patch edges.
\begin{matlab}
%}
Ut=zeros(nx,nVars,nEnsem,Nx);
Ut(i,ju ,:,:) = ut(i,:,:,:); % dudt = ut
Ut(i,jv+ju(end),:,:) = vt(i,:,:,:); % dvdt = vt
%{
\end{matlab}
Substitute the stresses into the dynamical \pde{}s in the
\(x\)-direction to get
\begin{align*}&
\rho \D t{\dot u}
= {\D {x}{\sigma_{xx}}} +{\D {y}{\sigma_{yx}}}
+\kappa(\dot u_{xx}+\dot u_{yy})
+F_{x} \,,
\end{align*}
and correspondingly for the \(y\)-direction. Here, we
include some viscous dissipation of strength
\(\kappa=\verb|visc|\), but \emph{do not} justify it as
visco-elasticity. First code above \(x\)-direction, then
the corresponding \(y\)-direction.
\begin{matlab}
%}
Ut(i,ju+nny,:,:) ...
= diff(sxx)/dx +diff(sxy(i,:,:,:),1,2)/dy +(utxx+utyy);
Ut(i,jv+nny+ju(end),:,:) ...
= diff(syy(i,:,:,:),1,2)/dy +diff(sxy)/dx +(vtxx+vtyy);
%{
\end{matlab}
End of function.
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
elastic2DstagHeteroSim.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/elastic2DstagHeteroSim.m
| 8,178 |
utf_8
|
db57f7bfe05dea4bcf7cf1ad70c2c16e
|
% Execute patch scheme on the heterogeneous miscroscale grid
% coded in function elastic2Dstaggered() with specified
% microscale boundary conditions on the beam ends. AJR, 27
% Sep 2022 -- 4 Feb 2023
%!TEX root = doc.tex
%{
\section{\texttt{elastic2DstagHeteroSim}: simulate 2D
heterogeneous elastic patches on staggered grid}
\label{elastic2DstagHeteroSim}
Execute patch scheme on the miscroscale grid of
heterogeneous elasticity in a 2D beam as coded in the
function \verb|elastic2Dstaggered()| of
\cref{secelastic2Dstaggered}. Here a beam of length~\(\pi\)
with either fixed or stress-free boundary conditions. This
patch scheme provides an effective computational
homogenisation of the microscale heterogeneous beam.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plot
%{
\end{matlab}
\paragraph{Set some patch and physical parameters}
\begin{matlab}
%}
nPatch = 5
nSubP = 7
ny = 4
xLim = [0 pi]
yLim= [-1 1]*0.06
nVars = 4*ny-2;
iOrd = 0
edgyInt = true
heteroStrength = 1 % -2--2 ??
stressFreeRightBC = true
viscosity = 2e-3; % 1e-3 sometimes has unstable micro-modes!!!
tEnd = 30
basename = mfilename;
%{
\end{matlab}
Viscosity of 1e-3 sometimes has unstable modes: only one
pair for homogeneous beam, but three pairs for heterogeneous
beam??
Set the cross-beam microscale \(y\)-coordinates and indices
in row vectors: one for \(u,\sigma_{xx},\sigma_{yy}\)-level;
and one for \(v,\sigma_{xy}\)-level. Then show the
micro-grid spacing.
\begin{matlab}
%}
yv=linspace(yLim(1),yLim(2),ny);
yu=(yv(1:ny-1)+yv(2:ny))/2;
ju=1:ny-1; jv=1:ny;
dy=diff(yu(1:2))
%{
\end{matlab}
\paragraph{Physical elastic parameters---random} Initially
express in terms of Young's modulus and Poisson's ratio to
be passed to the micro-code via \verb|patches|. For
heterogeneous elasticity, in the microgrid, we need
\(\lambda\)~at just \nw-points, and \(\mu\)~at both
\nw,\se~points. Might as well provide at all quarter points
as they both come from~\(E,\nu\), so we need these two
parameters at each of \(2n_y-1\) points across the beam.
Edgy interpolation requires patches to be two microgrid
points longer than any multiple of the microgrid
periodicity, whereas non-edgy requires one more than an even
multiple. Have to be careful with heterogeneities as
\nw,\se-points are alternately either side of the notional
microgrid lines.
\begin{matlab}
%}
xHeteroPeriod = (nSubP-1-edgyInt)/(2-edgyInt)
E = 1*exp(heteroStrength*0.5*randn(xHeteroPeriod,2*ny-1) );
nu = 0.3 +heteroStrength*0.1*(2*rand(xHeteroPeriod,2*ny-1)-1);
Equantiles = quantile( E(:),[0:0.25:1])
nuQuantiles = quantile(nu(:),[0:0.25:1])
%{
\end{matlab}
Compute corresponding \(\lambda,\mu\)-fields, and store so
\verb|configPatches1| \(x\)-expands micro-heterogeneity to
fill patch as necessary.
\begin{matlab}
%}
lambda=nu.*E./(1+nu)./(1-2*nu);
mu = E./(1+nu)./2;
cElas = [mu lambda];
%{
\end{matlab}
\paragraph{Configure patches} Using \verb|hetCoeffs| to
manage form heterogeneity in the patch, and adjoin viscosity
coefficient.
\begin{matlab}
%}
Dom.type='equispace';
Dom.bcOffset = [ 0 0.75*stressFreeRightBC ];
configPatches1(@elastic2Dstaggered,xLim,'equispace',nPatch ...
,iOrd,dy,nSubP,'EdgyInt',edgyInt,'hetCoeffs',cElas);
patches.viscosity = viscosity;
patches.stressFreeRightBC = stressFreeRightBC;
dx=diff(patches.x(1:2))
%{
\end{matlab}
\paragraph{Set initial condition} Say choose initial
velocities zero, and displacements varying somehow.
\begin{matlab}
%}
U0 = zeros(nSubP,nVars,1,nPatch);
U0(:,ju,:,:) = 0.1*sin(patches.x/(1+stressFreeRightBC))+0.*yu;
if stressFreeRightBC
U0(:,jv+ju(end),:,:) = 0.02*patches.x.^2.*(2.5-patches.x)+0.*yv;
else U0(:,jv+ju(end),:,:) = 0.2*sin(patches.x)+0.*yv;
end
%{
\end{matlab}
Optionally test the function
\begin{matlab}
%}
if 1 % test the new function
Ut=elastic2Dstaggered(-1,U0,patches);
Ut=reshape(Ut,nSubP,nVars,nPatch);
dudt=squeeze(Ut(:,ju,:))
dvdt=squeeze(Ut(:,jv+ju(end),:))
dutdt=squeeze(Ut(:,ju+2*ny-1,:))
dvtdt=squeeze(Ut(:,jv+2*ny-1+ju(end),:))
return
end
%{
\end{matlab}
\paragraph{Integrate in time}
\begin{matlab}
%}
[ts,Us] = ode15s(@patchSys1, [0 tEnd], U0(:));
%{
\end{matlab}
\paragraph{Plot summary of simulation} First, subsample the
time-steps to roughly 150~steps.
\begin{matlab}
%}
nt=numel(ts)
jt=1:ceil(nt/150):nt;
ts=ts(jt);
Us=reshape(Us(jt,:),[],nSubP,nVars,1,nPatch);
%{
\end{matlab}
Extract displacement fields.
\begin{matlab}
%}
us=Us(:,:,ju,:,:);
vs=Us(:,:,jv+ju(end),:,:);
%{
\end{matlab}
Form arrays of averages and variation across \(y\),
reshaped into 2D arrays.
\begin{matlab}
%}
uMean=reshape(mean(us,3),[],nSubP*nPatch);
uStd=reshape(std(us,0,3),[],nSubP*nPatch);
vMean=reshape(mean(vs,3),[],nSubP*nPatch);
vStd=reshape(std(vs,0,3),[],nSubP*nPatch);
%{
\end{matlab}
Plot \(xt\)-meshes coloured by the variation across~\(y\),
first the \(u\)-field of compression waves, see
\cref{figelastic2DstagHeteroSimu}. The small space-shift in
\(x\)-location is due to the staggered micro-grid for the
patches as coded.
%\begin{figure}
%\centering
%\caption{\label{figelastic2DstagHeteroSimu}%
%mean field~\(u\) in space-time showing compression waves. etc.}
%\input{Figs/elastic2DstagHeteroSimu}
%\end{figure}
\begin{matlab}
%}
xs = patches.x; xs([1 end],:) = nan;
figure(1),clf
mesh(xs(:)+dx/4,ts,uMean,uStd);
ylabel('time $t$'),xlabel('space $x$'),zlabel('mean $u$')
xlim([0 pi]),view(40,55),colorbar
ifOurCf2eps([basename 'us'])%optionally save
%{
\end{matlab}
Draw the \(v\)-field showing the beam bending, see
\cref{figelastic2DstagHeteroSimv}. The small space-shift in
\(x\)-location is due to the staggered micro-grid for the
patches as coded.
%\begin{figure}
%\centering
%\caption{\label{figelastic2DstagHeteroSimv}%
%mean field~\(v\) in space-time showing beam bending. etc.}
%\input{Figs/elastic2DstagHeteroSimv}
%\end{figure}
\begin{matlab}
%}
figure(2),clf
mesh(xs(:)-dx/4,ts,vMean,vStd);
ylabel('time $t$'),xlabel('space $x$'),zlabel('mean $v$')
xlim([0 pi]),view(40,55),colorbar
drawnow
ifOurCf2eps([basename 'vs'])%optionally save
%{
\end{matlab}
\paragraph{Compute Jacobian and its spectrum} The aim here
is four-fold: \begin{itemize}
\item to show the patch scheme is stable for all elastic waves;
\item to have a clear separation between fast and slow waves;
\item for compression macro-waves to match theory of
frequency \(\omega=\sqrt E k\) for integer wavenumber~\(k\);
and
\item for beam macro-waves to match beam theory of
\(mv_{tt}=EIv_{xxxx}\) for mass-density \(m:=2h\) and moment
\(I:=\int_{-h}^h y^2\,dy=\tfrac23h^3\) giving frequencies
\(\omega=\sqrt{E/3}hk\) where \(h\)~is the half-width of the
beam.
\end{itemize}
Form the Jacobian matrix, the linear operator, by numerical
construction about a zero field. Use~\verb|i| to store the
indices of the micro-grid points that are interior to the
patches and hence are the system variables.
\begin{matlab}
%}
u0 = zeros(nSubP,nVars,1,nPatch);
u0([1 end],:,:,:)=nan; u0=u0(:);
i=find(~isnan(u0));
nVariables=length(i)
Jac=nan(nVariables);
for j=1:nVariables
u0(i)=((1:nVariables)==j);
dudt=patchSys1(0,u0);
Jac(:,j)=dudt(i);
end
nJacEffZero = sum(abs(Jac(:))<1e-12)
Jac(abs(Jac)<1e-12) = 0;
%{
\end{matlab}
Find the eigenvalues of the Jacobian, and list the
slowest for inspection.
\begin{matlab}
%}
[evecs,evals]=eig(Jac);
cabs=@(z) -real(z)*1e5+abs(imag(z));
[~,j]=sort(cabs(diag(evals)));
evals=diag(evals(j,j)); evecs=evecs(:,j);
nZeroEvals=sum(abs(evals)<1e-5)
j=find(abs(evals)>1e-5);
leadingNonzeroEvals=evals(j(1:4*nPatch))
%{
\end{matlab}
Plot quasi-log view of the spectrum,
see \cref{figelastic2DstagHeteroSimEig}.
%\begin{figure}
%\centering
%\caption{\label{figelastic2DstagHeteroSimEig}%
%spectrum of the patch scheme showing slow macroscale waves,
%and fast sub-patch microscale modes. etc.}
%\input{Figs/elastic2DstagHeteroSimEig}
%\end{figure}
\begin{matlab}
%}
figure(3),clf
handle = plot(real(evals),imag(evals),'.');
xlabel('real-part'), ylabel('imag-part')
quasiLogAxes(handle,0.01,0.1);
ifOurCf2eps([basename 'Eig'])%optionally save
%{
\end{matlab}
\input{elastic2Dstaggered.m}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
heteroBurstF.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/heteroBurstF.m
| 715 |
utf_8
|
611b10c66c13bed0fd051798cd7e543d
|
% Simulates a burst of the system linked to by the
% configuration of patches. Used by ??.m
% AJR, 4 Apr 2019 -- 21 Oct 2022
%!TEX root = doc.tex
%{
\subsection{\texttt{heteroBurstF()}: a burst of
heterogeneous diffusion}
\label{sec:heteroBurstF}
This code integrates in time the derivatives computed by
\verb|heteroDiff| from within the patch coupling of
\verb|patchSys1|. Try~\verb|ode23|, although \verb|ode45|
may give smoother results. Sample every period of the
microscale time fluctuations (or, at least, close to the
period).
\begin{matlab}
%}
function [ts, ucts] = heteroBurstF(ti, ui, bT)
global microTimePeriod
[ts,ucts] = ode45( @patchSys1,ti+(0:microTimePeriod:bT),ui(:));
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
configPatches2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/configPatches2.m
| 30,136 |
utf_8
|
60d970c3501f89f25665af35ee248993
|
% configPatches2() creates a data struct of the design of 2D
% patches for later use by the patch functions such as
% patchSys2(). AJR, Nov 2018 -- Jan 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{configPatches2()}: configures spatial
patches in 2D}
\label{sec:configPatches2}
\localtableofcontents
Makes the struct~\verb|patches| for use by the patch\slash
gap-tooth time derivative\slash step function
\verb|patchSys2()|. \cref{sec:configPatches2eg} lists an
example of its use.
\begin{matlab}
%}
function patches = configPatches2(fun,Xlim,Dom ...
,nPatch,ordCC,dx,nSubP,varargin)
%{
\end{matlab}
\paragraph{Input}
If invoked with no input arguments, then executes an example
of simulating a nonlinear diffusion \pde\ relevant to the
lubrication flow of a thin layer of fluid---see
\cref{sec:configPatches2eg} for an example code.
\begin{itemize}
\item \verb|fun| is the name of the user function,
\verb|fun(t,u,patches)| or \verb|fun(t,u)|, that computes
time-derivatives (or time-steps) of quantities on the 2D
micro-grid within all the 2D~patches.
\item \verb|Xlim| array/vector giving the rectangular
macro-space domain of the computation, namely
$[\verb|Xlim(1)|, \verb|Xlim(2)|] \times [\verb|Xlim(3)|,
\verb|Xlim(4)|]$. If \verb|Xlim| has two elements, then the
domain is the square domain of the same interval in both
directions.
\item \verb|Dom| sets the type of macroscale conditions for
the patches, and reflects the type of microscale boundary
conditions of the problem. If \verb|Dom| is \verb|NaN| or
\verb|[]|, then the field~\verb|u| is doubly macro-periodic
in the 2D spatial domain, and resolved on equi-spaced
patches. If \verb|Dom| is a character string, then that
specifies the \verb|.type| of the following structure, with
\verb|.bcOffset| set to the default zero. Otherwise
\verb|Dom| is a structure with the following components.
\begin{itemize}
\item \verb|.type|, string, of either \verb|'periodic'| (the
default), \verb|'equispace'|, \verb|'chebyshev'|,
\verb|'usergiven'|. For all cases except \verb|'periodic'|,
users \emph{must} code into \verb|fun| the micro-grid
boundary conditions that apply at the left\slash right\slash
bottom\slash top edges of the leftmost\slash rightmost\slash
bottommost\slash topmost patches, respectively.
\item \verb|.bcOffset|, optional one, two or four element
vector/array, in the cases of \verb|'equispace'| or
\verb|'chebyshev'| the patches are placed so the left\slash
right\slash top\slash bottom macroscale boundaries are
aligned to the left\slash right\slash top\slash bottom edges
of the corresponding extreme patches, but offset by
\verb|.bcOffset| of the sub-patch micro-grid spacing. For
example, use \verb|bcOffset=0| when the micro-code applies
Dirichlet boundary values on the extreme edge micro-grid
points, whereas use \verb|bcOffset=0.5| when the microcode
applies Neumann boundary conditions halfway between the
extreme edge micro-grid points. Similarly for the top and
bottom edges.
If \verb|.bcOffset| is a scalar, then apply the same offset
to all boundaries. If two elements, then apply the first
offset to both \(x\)-boundaries, and the second offset to
both \(y\)-boundaries. If four elements, then apply the
first two offsets to the respective \(x\)-boundaries, and
the last two offsets to the respective \(y\)-boundaries.
\item \verb|.X|, optional vector/array with \verb|nPatch(1)|
elements, in the case \verb|'usergiven'| it specifies the
\(x\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\item \verb|.Y|, optional vector/array with \verb|nPatch(2)|
elements, in the case \verb|'usergiven'| it specifies the
\(y\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\end{itemize}
\item \verb|nPatch| sets the number of equi-spaced spatial
patches: if scalar, then use the same number of patches in
both directions, otherwise \verb|nPatch(1:2)| gives the
number of patches~($\geq1$) in each direction.
\item \verb|ordCC| is the `order' of interpolation for
inter-patch coupling across empty space of the macroscale
patch values to the edge-values of the patches: currently
must be~$0,2,4,\ldots$; where $0$~gives spectral
interpolation.
\item \verb|dx| (real---scalar or two element) is usually
the sub-patch micro-grid spacing in~\(x\) and~\(y\). If
scalar, then use the same \verb|dx| in both directions,
otherwise \verb|dx(1:2)| gives the spacing in each of the
two directions.
However, if \verb|Dom| is~\verb|NaN| (as for pre-2023), then
\verb|dx| actually is \verb|ratio| (scalar or two element),
namely the ratio of (depending upon \verb|EdgyInt|) either
the half-width or full-width of a patch to the equi-spacing
of the patch mid-points. So either $\verb|ratio|=\tfrac12$
means the patches abut and $\verb|ratio|=1$ is overlapping
patches as in holistic discretisation, or $\verb|ratio|=1$
means the patches abut. Small~\verb|ratio| should greatly
reduce computational time.
\item \verb|nSubP| is the number of equi-spaced microscale
lattice points in each patch: if scalar, then use the same
number in both directions, otherwise \verb|nSubP(1:2)| gives
the number in each direction. If not using \verb|EdgyInt|,
then must be odd so that there is/are centre-patch
micro-grid point\slash lines in each patch.
\item \verb|nEdge| (not yet implemented), \emph{optional},
default=1, for each patch, the number of edge values set by
interpolation at the edge regions of each patch. The
default is one (suitable for microscale lattices with only
nearest neighbour interactions).
\item \verb|EdgyInt|, true/false, \emph{optional},
default=false. If true, then interpolate to left\slash
right\slash top\slash bottom edge-values from right\slash
left\slash bottom\slash top next-to-edge values. If false
or omitted, then interpolate from centre cross-patch lines.
\item \verb|nEnsem|, \emph{optional-experimental},
default one, but if more, then an ensemble over this
number of realisations.
\item \verb|hetCoeffs|, \emph{optional}, default empty.
Supply a 2D or 3D array of microscale heterogeneous
coefficients to be used by the given microscale \verb|fun|
in each patch. Say the given array~\verb|cs| is of size
$m_x\times m_y\times n_c$, where $n_c$~is the number of
different sets of coefficients. For example, in
heterogeneous diffusion, $n_c=2$ for the diffusivities in
the \emph{two} different spatial directions (or $n_c=3$ for
the diffusivity tensor). The coefficients are to be the same
for each and every patch; however, macroscale variations are
catered for by the $n_c$~coefficients being $n_c$~parameters
in some macroscale formula.
\begin{itemize}
\item If $\verb|nEnsem|=1$, then the array of coefficients
is just tiled across the patch size to fill up each patch,
starting from the $(1,1)$-point in each patch.
\item If $\verb|nEnsem|>1$ (value immaterial), then reset
$\verb|nEnsem|:=m_x\cdot m_y$ and construct an ensemble of
all $m_x\cdot m_y$ phase-shifts of the coefficients. In
this scenario, the inter-patch coupling couples different
members in the ensemble. When \verb|EdgyInt| is true, and
when the coefficients are diffusivities\slash elasticities
in~$x$ and~$y$ directions, respectively, then this
coupling cunningly preserves symmetry.
\end{itemize}
\item \verb|'parallel'|, true/false, \emph{optional},
default=false. If false, then all patch computations are on
the user's main \textsc{cpu}---although a user may well
separately invoke, say, a \textsc{gpu} to accelerate
sub-patch computations.
If true, and it requires that you have \Matlab's Parallel
Computing Toolbox, then it will distribute the patches over
multiple \textsc{cpu}s\slash cores. In \Matlab, only one
array dimension can be split in the distribution, so it
chooses the one space dimension~$x,y$ corresponding to the
highest~\verb|\nPatch| (if a tie, then chooses the rightmost
of~$x,y$). A user may correspondingly distribute arrays
with property \verb|patches.codist|, or simply use formulas
invoking the preset distributed arrays \verb|patches.x|, and
\verb|patches.y|. If a user has not yet established a
parallel pool, then a `local' pool is started.
\end{itemize}
\paragraph{Output} The struct \verb|patches| is created and
set with the following components. If no output variable is
provided for \verb|patches|, then make the struct available
as a global variable.\footnote{When using \texttt{spmd}
parallel computing, it is generally best to avoid global
variables, and so instead prefer using an explicit output
variable.}
\begin{matlab}
%}
if nargout==0, global patches, end
%{
\end{matlab}
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| or \verb|fun(t,u)|, that computes
the time derivatives (or steps) on the patchy lattice.
\item \verb|.ordCC| is the specified order of inter-patch
coupling.
\item \verb|.periodic|: either true, for interpolation on
the macro-periodic domain; or false, for general
interpolation by divided differences over non-periodic
domain or unevenly distributed patches.
\item \verb|.stag| is true for interpolation using only odd
neighbouring patches as for staggered grids, and false for
the usual case of all neighbour coupling---not yet
implemented.
\item \verb|.Cwtsr| and \verb|.Cwtsl|, only for
macro-periodic conditions, are the
$\verb|ordCC|\times 2$-array of weights for the inter-patch
interpolation onto the right\slash top and left\slash bottom
edges (respectively) with patch:macroscale ratio as
specified or as derived from~\verb|dx|.
\item \verb|.x| (6D) is $\verb|nSubP(1)| \times1 \times1
\times1 \times \verb|nPatch(1)| \times1$ array of the
regular spatial locations~$x_{iI}$ of the microscale grid
points in every patch.
\item \verb|.y| (6D) is $1 \times \verb|nSubP(2)| \times1
\times1 \times1 \times \verb|nPatch(2)|$ array of the
regular spatial locations~$y_{jJ}$ of the microscale grid
points in every patch.
\item \verb|.ratio| $1\times 2$, only for
macro-periodic conditions, are the size ratios of
every patch.
\item \verb|.nEdge| is, for each patch, the number of edge
values set by interpolation at the edge regions of each
patch.
\item \verb|.le|, \verb|.ri|, \verb|.bo|, \verb|.to|
determine inter-patch coupling of members in an ensemble.
Each a column vector of length~\verb|nEnsem|.
\item \verb|.cs| either
\begin{itemize}
\item \verb|[]| 0D, or
\item if $\verb|nEnsem|=1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times n_c$ 3D array of microscale
heterogeneous coefficients, or
\item if $\verb|nEnsem|>1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times n_c\times m_xm_y$ 4D array of
$m_xm_y$~ensemble of phase-shifts of the microscale
heterogeneous coefficients.
\end{itemize}
\item \verb|.parallel|, logical: true if patches are
distributed over multiple \textsc{cpu}s\slash cores for the
Parallel Computing Toolbox, otherwise false (the default is
to activate the \emph{local} pool).
\item \verb|.codist|, \emph{optional}, describes the
particular parallel distribution of arrays over the active
parallel pool.
\end{itemize}
\subsection{If no arguments, then execute an example}
\label{sec:configPatches2eg}
\begin{matlab}
%}
if nargin==0
disp('With no arguments, simulate example of nonlinear diffusion')
%{
\end{matlab}
The code here shows one way to get started: a user's script
may have the following three steps (``\into'' denotes
function recursion).
\begin{enumerate}\def\itemsep{-1.5ex}
\item configPatches2
\item ode23 integrator \into patchSys2 \into user's PDE
\item process results
\end{enumerate}
Establish global patch data struct to interface with a
function coding a nonlinear `diffusion' \pde: to be solved
on $6\times4$-periodic domain, with $9\times7$ patches,
spectral interpolation~($0$) couples the patches, with
$5\times5$ points forming the micro-grid in each patch, and
a sub-patch micro-grid spacing of~\(0.12\) (relatively large
for visualisation). \cite{Roberts2011a} established that
this scheme is consistent with the \pde\ (as the patch
spacing decreases).
\begin{matlab}
%}
global patches
patches = configPatches2(@nonDiffPDE,[-3 3 -2 2], [] ...
, [9 7], 0, 0.12, 5 ,'EdgyInt',false);
%{
\end{matlab}
Set an initial condition of a perturbed-Gaussian using
auto-replication of the spatial grid.
\begin{matlab}
%}
u0 = exp(-patches.x.^2-patches.y.^2);
u0 = u0.*(0.9+0.1*rand(size(u0)));
%{
\end{matlab}
Initiate a plot of the simulation using only the microscale
values interior to the patches: optionally set $x$~and
$y$-edges to \verb|nan| to leave the gaps between patches.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*hsv)
x = squeeze(patches.x); y = squeeze(patches.y);
if 1, x([1 end],:) = nan; y([1 end],:) = nan; end
%{
\end{matlab}
Start by showing the initial conditions of
\cref{fig:configPatches2ic} while the simulation computes.
\begin{matlab}
%}
u = reshape(permute(squeeze(u0) ...
,[1 3 2 4]), [numel(x) numel(y)]);
hsurf = surf(x(:),y(:),u');
axis([-3 3 -3 3 -0.03 1]), view(60,40)
legend('time = 0.00','Location','north')
xlabel('space x'), ylabel('space y'), zlabel('u(x,y)')
colormap(hsv)
ifOurCf2eps([mfilename 'ic'])
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:configPatches2ic}initial
field~$u(x,y,t)$ at time $t=0$ of the patch scheme applied
to a nonlinear `diffusion'~\pde: \cref{fig:configPatches2t3}
plots the computed field at time $t=3$.}
\includegraphics[scale=0.9]{configPatches2ic}
\end{figure}
Integrate in time to $t=4$ using standard functions. In
\Matlab\ \verb|ode15s| would be natural as the patch scheme
is naturally stiff, but \verb|ode23| is quicker \cite
[Fig.~4] {Maclean2020a}. Ask for output at non-uniform
times because the diffusion slows.
\begin{matlab}
%}
disp('Wait to simulate nonlinear diffusion h_t=(h^3)_xx+(h^3)_yy')
drawnow
if ~exist('OCTAVE_VERSION','builtin')
[ts,us] = ode23(@patchSys2,linspace(0,2).^2,u0(:));
else % octave version is quite slow for me
lsode_options('absolute tolerance',1e-4);
lsode_options('relative tolerance',1e-4);
[ts,us] = odeOcts(@patchSys2,[0 1],u0(:));
end
%{
\end{matlab}
Animate the computed simulation to end with
\cref{fig:configPatches2t3}. Use \verb|patchEdgeInt2| to
interpolate patch-edge values.
\begin{matlab}
%}
for i = 1:length(ts)
u = patchEdgeInt2(us(i,:));
u = reshape(permute(squeeze(u) ...
,[1 3 2 4]), [numel(x) numel(y)]);
set(hsurf,'ZData', u');
legend(['time = ' num2str(ts(i),'%4.2f')])
pause(0.1)
end
ifOurCf2eps([mfilename 't3'])
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:configPatches2t3}field~$u(x,y,t)$ at
time $t=3$ of the patch scheme applied to a nonlinear
`diffusion'~\pde\ with initial condition in
\cref{fig:configPatches2ic}.}
\includegraphics[scale=0.9]{configPatches2t3}
\end{figure}
Upon finishing execution of the example, exit this function.
\begin{matlab}
%}
return
end%if no arguments
%{
\end{matlab}
\IfFileExists{../Patch/nonDiffPDE.m}{\input{../Patch/nonDiffPDE.m}}{}
\begin{devMan}
\subsection{Parse input arguments and defaults}
\begin{matlab}
%}
p = inputParser;
fnValidation = @(f) isa(f, 'function_handle');%test for fn name
addRequired(p,'fun',fnValidation);
addRequired(p,'Xlim',@isnumeric);
%addRequired(p,'Dom'); % nothing yet decided
addRequired(p,'nPatch',@isnumeric);
addRequired(p,'ordCC',@isnumeric);
addRequired(p,'dx',@isnumeric);
addRequired(p,'nSubP',@isnumeric);
addParameter(p,'nEdge',1,@isnumeric);
addParameter(p,'EdgyInt',false,@islogical);
addParameter(p,'nEnsem',1,@isnumeric);
addParameter(p,'hetCoeffs',[],@isnumeric);
addParameter(p,'parallel',false,@islogical);
%addParameter(p,'nCore',1,@isnumeric); % not yet implemented
parse(p,fun,Xlim,nPatch,ordCC,dx,nSubP,varargin{:});
%{
\end{matlab}
Set the optional parameters.
\begin{matlab}
%}
patches.nEdge = p.Results.nEdge;
patches.EdgyInt = p.Results.EdgyInt;
patches.nEnsem = p.Results.nEnsem;
cs = p.Results.hetCoeffs;
patches.parallel = p.Results.parallel;
%patches.nCore = p.Results.nCore;
%{
\end{matlab}
Initially duplicate parameters for both space dimensions as
needed.
\begin{matlab}
%}
if numel(Xlim)==2, Xlim = repmat(Xlim,1,2); end
if numel(nPatch)==1, nPatch = repmat(nPatch,1,2); end
if numel(dx)==1, dx = repmat(dx,1,2); end
if numel(nSubP)==1, nSubP = repmat(nSubP,1,2); end
%{
\end{matlab}
Check parameters.
\begin{matlab}
%}
assert(Xlim(1)<Xlim(2) ...
,'first pair of Xlim must be ordered increasing')
assert(Xlim(3)<Xlim(4) ...
,'second pair of Xlim must be ordered increasing')
assert(patches.nEdge==1 ...
,'multi-edge-value interp not yet implemented')
assert(all(2*patches.nEdge<nSubP) ...
,'too many edge values requested')
%if patches.nCore>1
% warning('nCore>1 not yet tested in this version')
% end
%{
\end{matlab}
For compatibility with pre-2023 functions, if parameter
\verb|Dom| is \verb|Nan|, then we set the \verb|ratio| to
be the value of the so-called \verb|dx| vector.
\begin{matlab}
%}
if ~isstruct(Dom), pre2023=isnan(Dom);
else pre2023=false; end
if pre2023, ratio=dx; dx=nan; end
%{
\end{matlab}
Default macroscale conditions are periodic with evenly
spaced patches.
\begin{matlab}
%}
if isempty(Dom), Dom=struct('type','periodic'); end
if (~isstruct(Dom))&isnan(Dom), Dom=struct('type','periodic'); end
%{
\end{matlab}
If \verb|Dom| is a string, then just set type to that
string, and subsequently set corresponding defaults for
others fields.
\begin{matlab}
%}
if ischar(Dom), Dom=struct('type',Dom); end
%{
\end{matlab}
We allow different macroscale domain conditions in the
different directions. But for the moment do not allow
periodic to be mixed with the others (as the interpolation
mechanism is different code)---hence why we choose
\verb|periodic| be seven characters, whereas the others are
eight characters. The different conditions are coded in
different rows of \verb|Dom.type|, so we duplicate the
string if only one row specified.
\begin{matlab}
%}
if size(Dom.type,1)==1, Dom.type=repmat(Dom.type,2,1); end
%{
\end{matlab}
Check what is and is not specified, and provide default of
zero
(Dirichlet boundaries) if no \verb|bcOffset| specified when
needed. Do so for both directions independently.
\begin{matlab}
%}
patches.periodic=false;
for p=1:2
switch Dom.type(p,:)
case 'periodic'
patches.periodic=true;
if isfield(Dom,'bcOffset')
warning('bcOffset not available for Dom.type = periodic'), end
msg=' not available for Dom.type = periodic';
if isfield(Dom,'X'), warning(['X' msg]), end
if isfield(Dom,'Y'), warning(['Y' msg]), end
case {'equispace','chebyshev'}
if ~isfield(Dom,'bcOffset'), Dom.bcOffset=zeros(2,2); end
% for mixed with usergiven, following should still work
if numel(Dom.bcOffset)==1
Dom.bcOffset=repmat(Dom.bcOffset,2,2); end
if numel(Dom.bcOffset)==2
Dom.bcOffset=repmat(Dom.bcOffset(:)',2,1); end
msg=' not available for Dom.type = equispace or chebyshev';
if (p==1)& isfield(Dom,'X'), warning(['X' msg]), end
if (p==2)& isfield(Dom,'Y'), warning(['Y' msg]), end
case 'usergiven'
% if isfield(Dom,'bcOffset')
% warning('bcOffset not available for usergiven Dom.type'), end
msg=' required for Dom.type = usergiven';
if p==1, assert(isfield(Dom,'X'),['X' msg]), end
if p==2, assert(isfield(Dom,'Y'),['Y' msg]), end
otherwise
error([Dom.type 'is unknown Dom.type'])
end%switch Dom.type
end%for p
%{
\end{matlab}
\subsection{The code to make patches}
First, store the pointer to the time derivative function in
the struct.
\begin{matlab}
%}
patches.fun = fun;
%{
\end{matlab}
Second, store the order of interpolation that is to provide
the values for the inter-patch coupling conditions. Spectral
coupling is \verb|ordCC| of~$0$ or (not yet??)~$-1$.
\todo{Perhaps implement staggered spectral coupling.}
\begin{matlab}
%}
assert((ordCC>=-1) & (floor(ordCC)==ordCC), ...
'ordCC out of allowed range integer>=-1')
%{
\end{matlab}
For odd~\verb|ordCC| do interpolation based upon odd
neighbouring patches as is useful for staggered grids.
\begin{matlab}
%}
patches.stag = mod(ordCC,2);
assert(patches.stag==0,'staggered not yet implemented??')
ordCC = ordCC+patches.stag;
patches.ordCC = ordCC;
%{
\end{matlab}
Check for staggered grid and periodic case.
\begin{matlab}
%}
if patches.stag, assert(all(mod(nPatch,2)==0), ...
'Require an even number of patches for staggered grid')
end
%{
\end{matlab}
\paragraph{Set the macro-distribution of patches}
Third, set the centre of the patches in the macroscale grid
of patches. Loop over the coordinate directions, setting
the distribution into~\verb|Q| and finally assigning to
array of corresponding direction.
\begin{matlab}
%}
for q=1:2
qq=2*q-1;
%{
\end{matlab}
Distribution depends upon \verb|Dom.type|:
\begin{matlab}
%}
switch Dom.type(q,:)
%{
\end{matlab}
%: case periodic
The periodic case is evenly spaced within the spatial domain.
Store the size ratio in \verb|patches|.
\begin{matlab}
%}
case 'periodic'
Q=linspace(Xlim(qq),Xlim(qq+1),nPatch(q)+1);
DQ=Q(2)-Q(1);
Q=Q(1:nPatch(q))+diff(Q)/2;
pEI=patches.EdgyInt;% abbreviation
if pre2023, dx(q) = ratio(q)*DQ/(nSubP(q)-1-pEI)*(2-pEI);
else ratio(q) = dx(q)/DQ*(nSubP(q)-1-pEI)/(2-pEI);
end
patches.ratio=ratio;
%{
\end{matlab}
%: case equispace
The equi-spaced case is also evenly spaced but with the
extreme edges aligned with the spatial domain boundaries,
modified by the offset.
\begin{matlab}
%}
case 'equispace'
Q=linspace(Xlim(qq)+((nSubP(q)-1)/2-Dom.bcOffset(qq))*dx(q) ...
,Xlim(qq+1)-((nSubP(q)-1)/2-Dom.bcOffset(qq+1))*dx(q) ...
,nPatch(q));
DQ=diff(Q(1:2));
width=(1+patches.EdgyInt)/2*(nSubP(q)-1-patches.EdgyInt)*dx;
if DQ<width*0.999999
warning('too many equispace patches (double overlapping)')
end
%{
\end{matlab}
%: case chebyshev
The Chebyshev case is spaced according to the Chebyshev
distribution in order to reduce macro-interpolation errors,
\(Q_i \propto -\cos(i\pi/N)\), but with the extreme edges
aligned with the spatial domain boundaries, modified by the
offset, and modified by possible `boundary layers'.
\footnote{ However, maybe overlapping patches near a
boundary should be viewed as some sort of spatially analogue
of the `christmas tree' of projective integration and its
integration to a slow manifold. Here maybe the overlapping
patches allow for a `christmas tree' approach to the
boundary layers. Needs to be explored??}
\begin{matlab}
%}
case 'chebyshev'
halfWidth=dx(q)*(nSubP(q)-1)/2;
Q1 = Xlim(1)+halfWidth-Dom.bcOffset(qq)*dx(q);
Q2 = Xlim(2)-halfWidth+Dom.bcOffset(qq+1)*dx(q);
% Q = (Q1+Q2)/2-(Q2-Q1)/2*cos(linspace(0,pi,nPatch));
%{
\end{matlab}
Search for total width of `boundary layers' so that in the
interior the patches are non-overlapping Chebyshev. But
the width for assessing overlap of patches is the following
variable \verb|width|.
\begin{matlab}
%}
width=(1+patches.EdgyInt)/2*(nSubP(q)-1-patches.EdgyInt)*dx(q);
for b=0:2:nPatch(q)-2
DQmin=(Q2-Q1-b*width)/2*( 1-cos(pi/(nPatch(q)-b-1)) );
if DQmin>width, break, end
end
if DQmin<width*0.999999
warning('too many Chebyshev patches (mid-domain overlap)')
end
%{
\end{matlab}
Assign the centre-patch coordinates.
\begin{matlab}
%}
Q =[ Q1+(0:b/2-1)*width ...
(Q1+Q2)/2-(Q2-Q1-b*width)/2*cos(linspace(0,pi,nPatch(q)-b)) ...
Q2+(1-b/2:0)*width ];
%{
\end{matlab}
%: case usergiven
The user-given case is entirely up to a user to specify, we just
ensure it has the correct shape of a row??.
\begin{matlab}
%}
case 'usergiven'
if q==1, Q = reshape(Dom.X,1,[]);
else Q = reshape(Dom.Y,1,[]);
end%if
end%switch Dom.type
%{
\end{matlab}
Assign \(Q\)-coordinates to the correct spatial direction.
At this stage they are all rows.
\begin{matlab}
%}
if q==1, X=Q; end
if q==2, Y=Q; end
end%for q
%{
\end{matlab}
\paragraph{Construct the micro-grids}
Fourth, construct the microscale grid in each patch. Reshape
the grid to be 6D to suit dimensions (micro,Vars,Ens,macro).
\begin{matlab}
%}
nSubP = reshape(nSubP,1,2); % force to be row vector
assert(patches.EdgyInt | all(mod(nSubP,2)==1), ...
'configPatches2: nSubP must be odd')
i0 = (nSubP(1)+1)/2;
patches.x = reshape( dx(1)*(-i0+1:i0-1)'+X ...
,nSubP(1),1,1,1,nPatch(1),1);
%{
\end{matlab}
Next the \(y\)-direction.
\begin{matlab}
%}
i0 = (nSubP(2)+1)/2;
patches.y = reshape( dx(2)*(-i0+1:i0-1)'+Y ...
,1,nSubP(2),1,1,1,nPatch(2));
%{
\end{matlab}
\paragraph{Pre-compute weights for macro-periodic}
In the case of macro-periodicity, precompute the weightings
to interpolate field values for coupling. \todo{Might sometime
extend to coupling via derivative values.}
\begin{matlab}
%}
if patches.periodic
ratio = reshape(ratio,1,2); % force to be row vector
patches.ratio=ratio;
if ordCC>0
[Cwtsr,Cwtsl] = patchCwts(ratio,ordCC,patches.stag);
patches.Cwtsr = Cwtsr; patches.Cwtsl = Cwtsl;
end%if
end%if patches.periodic
%{
\end{matlab}
\subsection{Set ensemble inter-patch communication}
For \verb|EdgyInt| or centre interpolation respectively,
\begin{itemize}
\item the right-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to left-edge~\verb|le|,
and
\item the left-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to~\verb|re|.
\end{itemize}
\verb|re| and \verb|li| are `transposes' of each other as
\verb|re(li)=le(ri)| are both \verb|1:nEnsem|. Similarly for
bottom-edge\slash centre interpolation to top-edge
via~\verb|to|, and top-edge\slash centre interpolation to
bottom-edge via~\verb|bo|.
The default is nothing shifty. This setting reduces the
number of if-statements in function \verb|patchEdgeInt2()|.
\begin{matlab}
%}
nE = patches.nEnsem;
patches.le = 1:nE; patches.ri = 1:nE;
patches.bo = 1:nE; patches.to = 1:nE;
%{
\end{matlab}
However, if heterogeneous coefficients are supplied via
\verb|hetCoeffs|, then do some non-trivial replications.
First, get microscale periods, patch size, and replicate
many times in order to subsequently sub-sample: \verb|nSubP|
times should be enough. If \verb|cs| is more then 3D, then
the higher-dimensions are reshaped into the 3rd dimension.
\begin{matlab}
%}
if ~isempty(cs)
[mx,my,nc] = size(cs);
nx = nSubP(1); ny = nSubP(2);
cs = repmat(cs,nSubP);
%{
\end{matlab}
If only one member of the ensemble is required, then
sub-sample to patch size, and store coefficients in
\verb|patches| as is.
\begin{matlab}
%}
if nE==1, patches.cs = cs(1:nx-1,1:ny-1,:); else
%{
\end{matlab}
But for $\verb|nEnsem|>1$ an ensemble of
$m_xm_y$~phase-shifts of the coefficients is constructed
from the over-supply. Here code phase-shifts over the
periods---the phase shifts are like Hankel-matrices.
\begin{matlab}
%}
patches.nEnsem = mx*my;
patches.cs = nan(nx-1,ny-1,nc,mx,my);
for j = 1:my
js = (j:j+ny-2);
for i = 1:mx
is = (i:i+nx-2);
patches.cs(:,:,:,i,j) = cs(is,js,:);
end
end
patches.cs = reshape(patches.cs,nx-1,ny-1,nc,[]);
%{
\end{matlab}
Further, set a cunning left\slash right\slash bottom\slash
top realisation of inter-patch coupling. The aim is to
preserve symmetry in the system when also invoking
\verb|EdgyInt|. What this coupling does without
\verb|EdgyInt| is unknown. Use auto-replication.
\begin{matlab}
%}
le = mod((0:mx-1)+mod(nx-2,mx),mx)+1;
patches.le = reshape( le'+mx*(0:my-1) ,[],1);
ri = mod((0:mx-1)-mod(nx-2,mx),mx)+1;
patches.ri = reshape( ri'+mx*(0:my-1) ,[],1);
bo = mod((0:my-1)+mod(ny-2,my),my)+1;
patches.bo = reshape( (1:mx)'+mx*(bo-1) ,[],1);
to = mod((0:my-1)-mod(ny-2,my),my)+1;
patches.to = reshape( (1:mx)'+mx*(to-1) ,[],1);
%{
\end{matlab}
Issue warning if the ensemble is likely to be affected by
lack of scale separation. \todo{Maybe need to justify this
and the arbitrary threshold more carefully??}
\begin{matlab}
%}
if prod(ratio)*patches.nEnsem>0.9, warning( ...
'Probably poor scale separation in ensemble of coupled phase-shifts')
scaleSeparationParameter = ratio*patches.nEnsem
end
%{
\end{matlab}
End the two if-statements.
\begin{matlab}
%}
end%if-else nEnsem>1
end%if not-empty(cs)
%{
\end{matlab}
\paragraph{If parallel code} then first assume this is not
within an \verb|spmd|-environment, and so we invoke
\verb|spmd...end| (which starts a parallel pool if not
already started). At this point, the global \verb|patches|
is copied for each worker processor and so it becomes
\emph{composite} when we distribute any one of the fields.
Hereafter, {\em all fields in the global variable
\verb|patches| must only be referenced within an
\verb|spmd|-environment.}%
\footnote{If subsequently outside spmd, then one must use
functions like \texttt{getfield(patches\{1\},'a')}.}
\begin{matlab}
%}
if patches.parallel
% theparpool=gcp()
spmd
%{
\end{matlab}
Second, decide which dimension is to be sliced among
parallel workers (for the moment, do not consider slicing
the ensemble). Choose the direction of most patches, biased
towards the last.
\begin{matlab}
%}
[~,pari]=max(nPatch+0.01*(1:2));
patches.codist=codistributor1d(4+pari);
%{
\end{matlab}
\verb|patches.codist.Dimension| is the index that is split
among workers. Then distribute the appropriate coordinate
direction among the workers: the function must be invoked
inside an \verb|spmd|-group in order for this to work---so
we do not need \verb|parallel| in argument list.
\begin{matlab}
%}
switch pari
case 1, patches.x=codistributed(patches.x,patches.codist);
case 2, patches.y=codistributed(patches.y,patches.codist);
otherwise
error('should never have bad index for parallel distribution')
end%switch
end%spmd
%{
\end{matlab}
If not parallel, then clean out \verb|patches.codist| if it exists.
May not need, but safer.
\begin{matlab}
%}
else% not parallel
if isfield(patches,'codist'), rmfield(patches,'codist'); end
end%if-parallel
%{
\end{matlab}
\paragraph{Fin}
\begin{matlab}
%}
end% function
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/patchEdgeInt2.m
| 20,179 |
utf_8
|
7cac816a06110db2af6ca47960709934
|
% patchEdgeInt2() provides the interpolation across 2D space
% for 2D patches of simulations of a lattice system such as
% a PDE discretisation. AJR, Nov 2018 -- 2 Feb 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt2()}: sets 2D patch
edge values from 2D macroscale interpolation}
\label{sec:patchEdgeInt2}
Couples 2D patches across 2D space by computing their edge
values via macroscale interpolation. Research
\cite[]{Roberts2011a, Bunder2019d} indicates the patch
centre-values are sensible macroscale variables, and
macroscale interpolation of these determine patch-edge
values. However, for computational homogenisation in
multi-D, interpolating patch next-to-edge values appears
better \cite[]{Bunder2020a}. This function is primarily
used by \verb|patchSys2()| but is also useful for user
graphics. \footnote{Script \texttt{patchEdgeInt2test.m}
verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global struct
\verb|patches|.
\begin{matlab}
%}
function u = patchEdgeInt2(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP1| \cdot \verb|nSubP2| \cdot \verb|nPatch1|
\cdot \verb|nPatch2|$ multiscale spatial grid on the
$\verb|nPatch1| \cdot \verb|nPatch2|$ array of patches.
\item \verb|patches| a struct set by \verb|configPatches2()|
which includes the following information.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP1| \times1 \times1 \times1
\times \verb|nPatch1| \times1 $ array of the spatial
locations~$x_{iI}$ of the microscale grid points in every
patch. Currently it \emph{must} be an equi-spaced lattice on
the microscale index~$i$, but may be variable spaced in
macroscale index~$I$.
\item \verb|.y| is similarly $1 \times \verb|nSubP2| \times1
\times1 \times1 \times \verb|nPatch2|$ array of the spatial
locations~$y_{jJ}$ of the microscale grid points in every
patch. Currently it \emph{must} be an equi-spaced lattice on
the microscale index~$j$, but may be variable spaced in
macroscale index~$J$.
\item \verb|.ordCC| is order of interpolation, currently
only $\{0,2,4,\ldots\}$
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left, right, top and bottom boundaries so interpolation is
via divided differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation. Currently must be zero.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation in both the
$x,y$-directions---when invoking a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation: true, from opposite-edge
next-to-edge values (often preserves symmetry); false, from
centre cross-patch values (near original scheme).
\item \verb|.nEnsem| the number of realisations in the
ensemble.
\item \verb|.parallel| whether serial or parallel.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 6D array, $\verb|nSubP1| \cdot
\verb|nSubP2| \cdot \verb|nVars| \cdot \verb|nEnsem| \cdot
\verb|nPatch1| \cdot \verb|nPatch2|$, of the fields with
edge values set by interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[~,ny,~,~,~,Ny] = size(patches.y);
[nx,~,~,~,Nx,~] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round(numel(u)/numel(patches.x)/numel(patches.y)/nEnsem);
assert(numel(u) == nx*ny*Nx*Ny*nVars*nEnsem ...
,'patchEdgeInt2: input u has wrong size for parameters')
u = reshape(u,[nx ny nVars nEnsem Nx Ny ]);
%{
\end{matlab}
For the moment assume the physical domain is either
macroscale periodic or macroscale rectangle so that the
coupling formulas are simplest. These index vectors point
to patches and, if periodic, their four immediate neighbours.
\begin{matlab}
%}
I=1:Nx; Ip=mod(I,Nx)+1; Im=mod(I-2,Nx)+1;
J=1:Ny; Jp=mod(J,Ny)+1; Jm=mod(J-2,Ny)+1;
%{
\end{matlab}
The centre of each patch (as \verb|nx| and~\verb|ny| are
odd for centre-patch interpolation) is at indices
\begin{matlab}
%}
i0 = round((nx+1)/2);
j0 = round((ny+1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches.
\begin{matlab}
%}
rx = patches.ratio(1);
ry = patches.ratio(2);
%{
\end{matlab}
\subsubsection{Lagrange interpolation gives patch-edge values}
Compute centred differences of the mid-patch values for the
macro-interpolation, of all fields. Here the domain is
macro-periodic.
\begin{matlab}
%}
ordCC = patches.ordCC;
if ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in corner values. Start with
\(x\)-direction, and give most documentation for that case
as the \(y\)-direction is essentially the same.
\paragraph{\(x\)-normal edge values} The patch-edge values
are either interpolated from the next-to-edge values, or
from the centre-cross values (not the patch-centre value
itself as that seems to have worse properties in general).
Have not yet implemented core averages.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u([2 nx-1],2:(ny-1),:,:,I,J);
else % interpolate centre-cross values
U = u(i0,2:(ny-1),:,:,I,J);
end;%if patches.EdgyInt
%{
\end{matlab}
Just in case the last array dimension(s) are one, we have to
force a padding of the sizes, then adjoin the extra
dimension for the subsequent array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,6-length(szUO)) ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in these arrays. When parallel, in order
to preserve the distributed array structure we use an index
at the end for the differences.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 7D
else dmu = zeros(szUO,patches.codist); % 7D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
% dmux(:,:,:,:,I,:,1) = (Ux(:,:,:,:,Ip,:)+Ux(:,:,:,:,Im,:))/2; % \mu
% dmux(:,:,:,:,I,:,2) = (Ux(:,:,:,:,Ip,:)-Ux(:,:,:,:,Im,:)); % \delta
% Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
% dmuy(:,:,:,:,:,J,1) = (Ux(:,:,:,:,:,Jp)+Ux(:,:,:,:,:,Jm))/2; % \mu
% dmuy(:,:,:,:,:,J,2) = (Ux(:,:,:,:,:,Jp)-Ux(:,:,:,:,:,Jm)); % \delta
% Jp = Jp(Jp); Jm = Jm(Jm); % increase shifts to \pm2
else %disp('starting standard interpolation')
dmu(:,:,:,:,I,:,1) = (U(:,:,:,:,Ip,:) ...
-U(:,:,:,:,Im,:))/2; %\mu\delta
dmu(:,:,:,:,I,:,2) = (U(:,:,:,:,Ip,:) ...
-2*U(:,:,:,:,I,:) +U(:,:,:,:,Im,:)); %\delta^2
end% if patches.stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,I,:,k) = dmu(:,:,:,:,Ip,:,k-2) ...
-2*dmu(:,:,:,:,I,:,k-2) +dmu(:,:,:,:,Im,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet edge values for
each patch \cite[]{Roberts06d, Bunder2013b}, using weights
computed in \verb|configPatches2()|. Here interpolate to
specified order.
For the case where next-to-edge values interpolate to the
opposite edge-values: when we have an ensemble of
configurations, different configurations might be coupled to
each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to| and \verb|patches.bo|.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two edges
u(nx,2:(ny-1),:,patches.ri,I,:) ...
= U(1,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,1),-6).*dmu(1,:,:,:,:,:,:) ,7);
u(1 ,2:(ny-1),:,patches.le,I,:,:) ...
= U(k,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,1),-6).*dmu(k,:,:,:,:,:,:) ,7);
%{
\end{matlab}
\paragraph{\(y\)-normal edge values} Interpolate from either
the next-to-edge values, or the centre-cross-line values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,[2 ny-1],:,:,I,J);
else % interpolate centre-cross values
U = u(:,j0,:,:,I,J);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,6-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 7D
else dmu = zeros(szUO,patches.codist); % 7D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,J,1) = (U(:,:,:,:,:,Jp) ...
-U(:,:,:,:,:,Jm))/2; %\mu\delta
dmu(:,:,:,:,:,J,2) = (U(:,:,:,:,:,Jp) ...
-2*U(:,:,:,:,:,J) +U(:,:,:,:,:,Jm)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,J,k) = dmu(:,:,:,:,:,Jp,k-2) ...
-2*dmu(:,:,:,:,:,J,k-2) +dmu(:,:,:,:,:,Jm,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches2()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k = 1+patches.EdgyInt; % use centre or two edges
u(:,ny,:,patches.to,:,J) ...
= U(:,1,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,2),-6).*dmu(:,1,:,:,:,:,:) ,7);
u(:,1 ,:,patches.bo,:,J) ...
= U(:,k,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,2),-6).*dmu(:,k,:,:,:,:,:) ,7);
%{
\end{matlab}
\subsubsection{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
We interpolate in terms of the patch index, $j$~say, not
directly in space. As the macroscale fields are $N$-periodic
in the patch index~$I$, the macroscale Fourier transform
writes the centre-patch values as $U_I=\sum_{k}C_ke^{ik2\pi
I/N}$. Then the edge-patch values $U_{I\pm r}
=\sum_{k}C_ke^{ik2\pi/N(I\pm r)} =\sum_{k}C'_ke^{ik2\pi
I/N}$ where $C'_k=C_ke^{ikr2\pi/N}$. For $N$~patches we
resolve `wavenumbers' $|k|<N/2$, so set row vector
$\verb|ks|=k2\pi/N$ for `wavenumbers' $\mathcode`\,="213B
k=(0,1, \ldots, k_{\max}, -k_{\max}, \ldots, -1)$ for
odd~$N$, and $\mathcode`\,="213B k=(0,1, \ldots, k_{\max},
\pm(k_{\max}+1) -k_{\max}, \ldots, -1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches2|
tests there are an even number of patches). Then the
patch-ratio is effectively halved. The patch edges are near
the middle of the gaps and swapped.
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
error('staggered grid not yet implemented??')
v=nan(size(u)); % currently to restore the shape of u
u=cat(3,u(:,1:2:nPatch,:),u(:,2:2:nPatch,:));
stagShift=reshape(0.5*[ones(nVars,1);-ones(nVars,1)],1,1,[]);
iV=[nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r=r/2; % ratio effectively halved
nPatch=nPatch/2; % halve the number of patches
nVars=nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Interpolate the two directions in succession, in this way we
naturally fill-in edge-corner values. Start with
\(x\)-direction, and give most documentation for that case
as the other is essentially the same. Need these indices of
patch interior.
\begin{matlab}
%}
ix = 2:nx-1; iy = 2:ny-1;
%{
\end{matlab}
\paragraph{\(x\)-normal edge values} Now set wavenumbers
into a vector at the correct dimension. In the case of
even~$N$ these compute the $+$-case for the highest
wavenumber zig-zag mode, $\mathcode`\,="213B k=(0,1, \ldots,
k_{\max}, +(k_{\max}+1) -k_{\max}, \ldots, -1)$.
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
kr = shiftdim( rx*2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ,-3);
%{
\end{matlab}
Compute the Fourier transform of the centre-cross values.
Unless doing patch-edgy interpolation when FT the
next-to-edge values. If there are an even number of points,
then if complex, treat as positive wavenumber, but if real,
treat as cosine. When using an ensemble of configurations,
different configurations might be coupled to each other, as
specified by \verb|patches.le|, \verb|patches.ri|,
\verb|patches.to| and \verb|patches.bo|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(i0,iy,:,:,:,:) ,[],5);
Cp = Cm;
else
Cm = fft( u( 2,iy ,:,patches.le,:,:) ,[],5);
Cp = fft( u(nx-1,iy ,:,patches.ri,:,:) ,[],5);
end%if ~patches.EdgyInt
%{
\end{matlab}
Now invert the Fourier transforms to complete interpolation.
Enforce reality when appropriate.
\begin{matlab}
%}
u(nx,iy,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],5) );
u( 1,iy,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],5) );
%{
\end{matlab}
\paragraph{\(y\)-normal edge values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Ny-1)/2);
kr = shiftdim( ry*2*pi/Ny*(mod((0:Ny-1)+kMax,Ny)-kMax) ,-4);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-lines for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,j0,:,:,:,:) ,[],6);
Cp = Cm;
else
Cm = fft( u(:,2 ,:,patches.bo,:,:) ,[],6);
Cp = fft( u(:,ny-1 ,:,patches.to,:,:) ,[],6);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,ny,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],6) );
u(:, 1,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],6) );
%{
\end{matlab}
\begin{matlab}
%}
end% if ordCC>0 else, so spectral
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|px| and~\verb|py|
(potentially different in the different directions!), and
hence size of the (forward) divided difference tables
in~\verb|F|~(7D) for interpolating to left/right, and
top/bottom edges. Because of the product-form of the patch
grid, and because we are doing \emph{only} either edgy
interpolation or cross-patch interpolation (\emph{not} just
the centre patch value), the interpolations are all 1D
interpolations.
\begin{matlab}
%}
if patches.ordCC<1
px = Nx-1; py = Ny-1;
else px = min(patches.ordCC,Nx-1);
py = min(patches.ordCC,Ny-1);
end
ix=2:nx-1; iy=2:ny-1; % indices of edge 'interior' (ix n/a)
%{
\end{matlab}
\subsubsection{\(x\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-edge values are because their
values are to interpolate to the opposite edge of each
patch. \todo{Have no plans to implement core averaging as
yet.}
\begin{matlab}
%}
F = nan(patches.EdgyInt+1,ny-2,nVars,nEnsem,Nx,Ny,px+1);
if patches.EdgyInt % interpolate next-to-edge values
F(:,:,:,:,:,:,1) = u([nx-1 2],iy,:,:,:,:);
X = patches.x([nx-1 2],:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,1) = u(i0,iy,:,:,:,:);
X = patches.x(i0,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
\paragraph{Form tables of divided differences} Compute
tables of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable, and
across ensemble, and for left/right edges. Recursively find
all divided differences.
\begin{matlab}
%}
for q = 1:px
i = 1:Nx-q;
F(:,:,:,:,i,:,q+1) ...
= (F(:,:,:,:,i+1 ,:,q)-F(:,:,:,:,i,:,q)) ...
./(X(:,:,:,:,i+q,:) -X(:,:,:,:,i,:));
end
%{
\end{matlab}
\paragraph{Interpolate with divided differences} Now
interpolate to find the edge-values on left/right edges
at~\verb|Xedge| for every interior~\verb|Y|.
\begin{matlab}
%}
Xedge = patches.x([1 nx],:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|i| are those of the left edge of
each interpolation stencil, because the table is of forward
differences. This alternative: the case of order~\(p_x\)
and~\(p_y\) interpolation across the domain, asymmetric near
the boundaries of the rectangular domain.
\begin{matlab}
%}
i = max(1,min(1:Nx,Nx-ceil(px/2))-floor(px/2));
Uedge = F(:,:,:,:,i,:,px+1);
for q = px:-1:1
Uedge = F(:,:,:,:,i,:,q)+(Xedge-X(:,:,:,:,i+q-1,:)).*Uedge;
end
%{
\end{matlab}
Finally, insert edge values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,iy,:,patches.le,:,:) = Uedge(1,:,:,:,:,:);
u(nx,iy,:,patches.ri,:,:) = Uedge(2,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(y\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,patches.EdgyInt+1,nVars,nEnsem,Nx,Ny,py+1);
if patches.EdgyInt % interpolate next-to-edge values
F(:,:,:,:,:,:,1) = u(:,[ny-1 2],:,:,:,:);
Y = patches.y(:,[ny-1 2],:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,1) = u(:,j0,:,:,:,:);
Y = patches.y(:,j0,:,:,:,:);
end;
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:py
j = 1:Ny-q;
F(:,:,:,:,:,j,q+1) ...
= (F(:,:,:,:,:,j+1 ,q)-F(:,:,:,:,:,j,q)) ...
./(Y(:,:,:,:,:,j+q) -Y(:,:,:,:,:,j));
end
%{
\end{matlab}
Interpolate to find the edge-values on top/bottom
edges~\verb|Yedge| for every~\(x\).
\begin{matlab}
%}
Yedge = patches.y(:,[1 ny],:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|j| are those of the bottom edge
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
j = max(1,min(1:Ny,Ny-ceil(py/2))-floor(py/2));
Uedge = F(:,:,:,:,:,j,py+1);
for q = py:-1:1
Uedge = F(:,:,:,:,:,j,q)+(Yedge-Y(:,:,:,:,:,j+q-1)).*Uedge;
end
%{
\end{matlab}
Finally, insert edge values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,1 ,:,patches.bo,:,:) = Uedge(:,1,:,:,:,:);
u(:,ny,:,patches.to,:,:) = Uedge(:,2,:,:,:,:);
%{
\end{matlab}
\subsubsection{Optional NaNs for safety}
We want a user to set outer edge values on the extreme
patches according to the microscale boundary conditions that
hold at the extremes of the domain. Consequently, override
their computed interpolation values with~\verb|NaN|.
\begin{matlab}
%}
u( 1,:,:,:, 1,:) = nan;
u(nx,:,:,:,Nx,:) = nan;
u(:, 1,:,:,:, 1) = nan;
u(:,ny,:,:,:,Ny) = nan;
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic else
%{
\end{matlab}
Fin, returning the 6D array of field values with
interpolated edges.
\begin{matlab}
%}
end% function patchEdgeInt2
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchSys2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/patchSys2.m
| 3,798 |
utf_8
|
951820e31f71da29cc283e05c0913575
|
% patchSys2() Provides an interface to time integrators
% for the dynamics on patches in 2D coupled across space.
% The system must be a smooth lattice system such as PDE
% discretisations. AJR, Nov 2018 -- Nov 2020
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchSys2()}: interface 2D space to time integrators}
\label{sec:patchSys2}
To simulate in time with 2D spatial patches we often need to
interface a users time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function provides an interface. It assumes that the
sub-patch structure is \emph{smooth enough} so that the
patch centre-values are sensible macroscale variables, and
patch edge-values are determined by macroscale interpolation
of the patch-centre or edge values. Nonetheless, microscale
heterogeneous systems may be accurately simulated with this
function via appropriate interpolation. Communicate
patch-design variables (\cref{sec:configPatches2}) either
via the global struct~\verb|patches| or via an optional
third argument (except that this last is required for
parallel computing of \verb|spmd|).
\begin{matlab}
%}
function dudt = patchSys2(t,u,patches)
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP(1)| \times \verb|nSubP(2)| \times
\verb|nPatch(1)| \times \verb|nPatch(2)|$ grid.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches2()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| that computes the time derivatives
on the patchy lattice. The array~\verb|u| has size
$\verb|nSubP(1)| \times \verb|nSubP(2)| \times \verb|nVars|
\times \verb|nEsem| \times \verb|nPatch(1)| \times
\verb|nPatch(2)|$. Time derivatives must be computed into
the same sized array, although herein the patch edge-values
are overwritten by zeros.
\item \verb|.x| is $\verb|nSubP(1)| \times1 \times1 \times1
\verb|nPatch(1)| \times1$ array of the spatial
locations~$x_{i}$ of the microscale $(i,j)$-grid points
in every patch. Currently it \emph{must} be an equi-spaced
lattice on both macro- and micro-scales.
\item \verb|.y| is similarly $1 \times \verb|nSubP(2)|
\times1 \times1 \times1 \times \verb|nPatch(2)|$ array of
the spatial locations~$y_{j}$ of the microscale
$(i,j)$-grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on both macro- and
micro-scales.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector\slash array of of time
derivatives, but with patch edge-values set to zero. It is
of total length $\verb|prod(nSubP)| \cdot \verb|nVars|
\cdot \verb|nEnsem| \cdot \verb|prod(nPatch)|$ and the same
dimensions as~\verb|u|.
\end{itemize}
\begin{devMan}
Reshape the fields~\verb|u| as a 6D-array, and sets the edge
values from macroscale interpolation of centre-patch values.
\cref{sec:patchEdgeInt2} describes \verb|patchEdgeInt2()|.
\begin{matlab}
%}
sizeu = size(u);
u = patchEdgeInt2(u,patches);
%{
\end{matlab}
Ask the user function for the time derivatives computed in
the array, overwrite its edge values with the dummy value of
zero (as \verb|ode15s| chokes on NaNs), then return to the
user\slash integrator as same sized array as input.
\begin{matlab}
%}
dudt = patches.fun(t,u,patches);
dudt([1 end],:,:,:,:,:) = 0;
dudt(:,[1 end],:,:,:,:) = 0;
dudt = reshape(dudt,sizeu);
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
twoscaleDiffEquil2Errs.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/twoscaleDiffEquil2Errs.m
| 12,199 |
utf_8
|
2d63db620941b674ef8a74a65ebb2bdd
|
% Explore errors in the steady state of twoscale
% heterogeneous diffusion in 2D on patches as an example,
% inspired by section 5.3.1 of Freese et al., 2211.13731.
% AJR, 31 Jan 2023
%!TEX root = doc.tex
%{
\section{\texttt{twoscaleDiffEquil2Errs}: errors in
equilibria of a 2D twoscale heterogeneous diffusion via
small patches}
\label{sec:twoscaleDiffEquil2Errs}
\begin{figure}
\centering\caption{\label{fig:twoscaleDiffEquil2Errsus} For
various numbers of patches as indicated on the colorbar,
plot the equilibrium of the multiscale diffusion problem of
Freese with Dirichlet zero-value boundary conditions
(\cref{sec:twoscaleDiffEquil2Errs}). We only compare
solutions only in these 25~common patches.}
\includegraphics[scale=0.8]{Figs/twoscaleDiffEquil2Errsus}
\end{figure}%
Here we find the steady state~\(u(x,y)\) to the
heterogeneous \pde\ (inspired by Freese et al.\footnote{
\protect \url{http://arxiv.org/abs/2211.13731}} \S5.3.1)
\begin{equation*}
u_t=A(x,y)\grad\grad u+f,
\end{equation*}
on domain \([-1,1]^2\) with Dirichlet BCs, for coefficient
`diffusion' matrix, varying with some microscale
period~\(\epsilon\) (here \(\epsilon\approx 0.24, 0.12,
0.06, 0.03\)), of
\begin{equation*}
A:=\begin{bmatrix} 2& a\\a & 2 \end{bmatrix}
\quad \text{with } a:=\sin(\pi x/\epsilon)\sin(\pi y/\epsilon),
\end{equation*}
and for forcing \(f:=10(x+y+\cos\pi x)\) (for which the
solution has magnitude up to one).\footnote{Freese et al.\
had forcing \(f:=(x+\cos3\pi x)y^3\), but here we want
smoother forcing so we get meaningful results in a minute or
two computation.\footnote{Except in the `usergiven' case,
for $N=65$, that is $152\,100$ unknowns, it takes an hour to
compute the Jacobian, then chokes.} For the same reason we
do not invoke their smaller \(\epsilon\approx 0.01\).}
\begin{figure}
\centering\caption{\label{fig:twoscaleDiffEquil2Errs} For
various numbers of patches as indicated on the colorbar,
plot the equilibrium of the multiscale diffusion problem of
Freese with Dirichlet zero-value boundary conditions
(\cref{sec:twoscaleDiffEquil2Errs}). We only compare
solutions only in these 25~common patches.}
\includegraphics[scale=0.8]{Figs/twoscaleDiffEquil2Errs}
\end{figure}%
Here we explore the errors for increasing number~\(N\) of
patches (in both directions). Find mean-abs errors to be the
following (for different orders of interpolation and patch
distribution):
\begin{equation*}
\begin{array}{rcccc}
N&5&9&17&33%&65
\\\hline
\text{equispace, 2nd-order} &6\E2 &3\E2 &1\E2 &3\E3
\\
\text{equispace, 4th-order} &3\E2 &8\E3 &7\E4 &7\E5
\\
\text{chebyshev, 4th-order} &1\E2 &2\E2 &6\E3 &2\E3
\\
\text{usergiven, 4th-order} &1\E2 &2\E2 &4\E3 &\text{n/a}
\\
\text{equispace, 6th-order} &3\E2 &1\E3 &1\E4 &2\E5
\\\hline
\end{array}
\end{equation*}
\paragraph{Script start} Clear, and initiate global patches.
Choose the type of patch distribution to be either
`equispace', `chebyshev', or `usergiven'. Also set order of
interpolation (fourth-order is good start).
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plot
switch 1
case 1, Dom.type = 'equispace'
case 2, Dom.type = 'chebyshev'
case 3, Dom.type = 'usergiven'
end% switch
ordInt = 4
%{
\end{matlab}
\paragraph{First configure the patch system} Establish the
microscale heterogeneity has micro-period \verb|mPeriod| on
the spatial lattice. Then \verb|configPatches2| replicates
the heterogeneity as needed to fill each patch.
\begin{matlab}
%}
mPeriod = 6
z = (0.5:mPeriod)'/mPeriod;
A = sin(2*pi*z).*sin(2*pi*z');
%{
\end{matlab}
To use a hierarchy of patches with \verb|nPatch| of~5, 9,
17, \ldots, we need up to \(N\)~patches plus one~\verb|dx|
to fit into the domain interval. Cater for up to some
full-domain simulation---can compute \(\verb|log2Nmax|=5\)
(\(\epsilon=0.06\)) within minutes:
\begin{matlab}
%}
log2Nmax = 4 % >2 up to 6 OKish
nPatchMax=2^log2Nmax+1
%{
\end{matlab}
Set the periodicity~\(\epsilon\), and other microscale
parameters.
\begin{matlab}
%}
nPeriodsPatch = 1 % any integer
nSubP = nPeriodsPatch*mPeriod+2 % for edgy int
epsilon = 2/(nPatchMax*nPeriodsPatch+1/mPeriod)
dx = epsilon/mPeriod
%{
\end{matlab}
\paragraph{For various numbers of patches} Choose five
patches to be the coarsest number of patches. Define
variables to store common results for the solutions from
differing patches. Assign \verb|Ps| to be the indices of
the common patches: for equispace set to the five common
patches, but for `chebyshev' the only common ones are the
three centre and boundary-adjacent patches.
\begin{matlab}
%}
us=[]; xs=[]; ys=[]; nPs=[];
for log2N=log2Nmax:-1:2
if log2N==log2Nmax
Ps=linspace(1,nPatchMax ...
,5-2*all(Dom.type=='chebyshev'))
else Ps=(Ps+1)/2
end
%{
\end{matlab}
Set the number of patches in \((-1,1)\):
\begin{matlab}
%}
nPatch = 2^log2N+1
%{
\end{matlab}
In the case of `usergiven', we set the standard Chebyshev
distribution of the patch-centres, which involves
overlapping of patches near the boundaries! (instead of the
coded chebyshev which has boundary layers of abutting
patches, and non-overlapping Chebyshev between the boundary
layers).
\begin{matlab}
%}
if all(Dom.type=='usergiven')
halfWidth = dx*(nSubP-1)/2;
X1 = -1+halfWidth; X2 = 1-halfWidth;
Dom.X = (X1+X2)/2-(X2-X1)/2*cos(linspace(0,pi,nPatch));
Dom.Y = Dom.X;
end
%{
\end{matlab}
Configure the patches:
\begin{matlab}
%}
configPatches2(@twoscaleDiffForce2,[-1 1],Dom,nPatch ...
,ordInt ,dx ,nSubP ,'EdgyInt',true ,'hetCoeffs',A );
%{
\end{matlab}
Compute the time-constant forcing, and store in struct
\verb|patches| for access by the microcode of
\cref{sec:twoscaleDiffForce2}.
\begin{matlab}
%}
if 1
patches.fu = 10*(patches.x+cos(pi*patches.x)+patches.y);
else patches.fu = 8+0*patches.x+0*patches.y;
end
%{
\end{matlab}
\paragraph{Solve for steady state} Set initial guess of
either zero or a subsample of the previous, next-finer,
solution. \verb|NaN| indicates patch-edge values.
Index~\verb|i| are the indices of patch-interior points, and
the number of unknowns is then its length.
\begin{matlab}
%}
if log2N==log2Nmax
u0 = zeros(nSubP,nSubP,1,1,nPatch,nPatch);
else u0 = u0(:,:,:,:,1:2:end,1:2:end);
end
u0([1 end],:,:) = nan; u0(:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
First try to solve via iterative solver \verb|bicgstab|, via
the generic patch system wrapper \verb|theRes|
(\cref{sec:theRes}).
\begin{matlab}
%}
tic;
maxIt = ceil(nVariables/10);
rhsb = theRes( zeros(size(patches.i)) );
[uSoln,flag] = bicgstab(@(u) rhsb-theRes(u),rhsb ...
,1e-9,maxIt,[],[],u0(patches.i));
bicgTime = toc
%{
\end{matlab}
However, the above often fails (and \verb|fsolve| sometimes
takes too long here), so then try a preconditioned version
of \verb|bicgstab|. The preconditioner is derived from the
Jacobian which is expensive to find (four minutes for
\(N=33\), one hour for $N=65$), but we do so as follows.
\begin{matlab}
%}
if flag>0, disp('**** bicg failed, trying ILU preconditioner')
disp(['Computing Jacobian: wait roughly ' ...
num2str(nPatch^4/4500,2) ' secs'])
tic
Jac=sparse(nVariables,nVariables);
for j=1:nVariables
Jac(:,j)=sparse( rhsb-theRes((1:nVariables)'==j) );
end
formJacTime=toc
%{
\end{matlab}
Compute an incomplete \(LU\)-factorization, and use it as
preconditioner to \verb|bicgstab|.
\begin{matlab}
%}
tic
[L,U] = ilu(Jac,struct('type','ilutp','droptol',1e-4));
LUfillFactor = (nnz(L)+nnz(U))/nnz(Jac)
[uSoln,flag] = bicgstab(@(u) rhsb-theRes(u),rhsb ...
,1e-9,maxIt,L,U,u0(patches.i));
precondSolveTime=toc
assert(flag==0,'preconditioner fails bicgstab. Lower droptol?')
end%if flag
%{
\end{matlab}
Store the solution into the patches, and give
magnitudes---Inf norm is max(abs()).
\begin{matlab}
%}
normResidual = norm(theRes(uSoln),Inf)
normSoln = norm(uSoln,Inf)
u0(patches.i) = uSoln;
u0 = patchEdgeInt2(u0);
u0( 1 ,:,:,:, 1 ,:)=0; % left edge of left patches
u0(end,:,:,:,end,:)=0; % right edge of right patches
u0(:, 1 ,:,:,:, 1 )=0; % bottom edge of bottom patches
u0(:,end,:,:,:,end)=0; % top edge of top patches
assert(normResidual<1e-5,'poor--bad solution found')
%{
\end{matlab}
Concatenate the solution on common patches into stores.
\begin{matlab}
%}
us=cat(5,us,squeeze(u0(:,:,:,:,Ps,Ps)));
xs=cat(3,xs,squeeze(patches.x(:,:,:,:,Ps,:)));
ys=cat(3,ys,squeeze(patches.y(:,:,:,:,:,Ps)));
nPs = [nPs;nPatch];
%{
\end{matlab}
End loop. Check micro-grids are aligned, then compute
errors compared to the full-domain solution (or the highest
resolution solution for the case of `usergiven').
\begin{matlab}
%}
end%for log2N
assert(max(abs(reshape(diff(xs,1,3),[],1)))<1e-12,'x-coord failure')
assert(max(abs(reshape(diff(ys,1,3),[],1)))<1e-12,'y-coord failure')
errs = us-us(:,:,:,:,1);
meanAbsErrs = mean(abs(reshape(errs,[],size(us,5))))
ratioErrs = meanAbsErrs(2:end)./meanAbsErrs(1:end-1)
%{
\end{matlab}
\paragraph{Plot solution in common patches} First reshape
arrays to suit 2D space surface plots, inserting nans to
separate patches.
\begin{matlab}
%}
x = xs(:,:,1); y = ys(:,:,1); u=us;
x(end+1,:)=nan; y(end+1,:)=nan;
u(end+1,:,:)=nan; u(:,end+1,:)=nan;
u = reshape(permute(u,[1 3 2 4 5]),numel(x),numel(y),[]);
%{
\end{matlab}
Plot the patch solution surfaces, with colour offset between
surfaces (best if \(u\)-field has a range of one): blues are
the full-domain solution, reds the coarsest patches.
\begin{matlab}
%}
figure(1), clf, colormap(jet)
for p=1:size(u,3)
mesh(x(:),y(:),u(:,:,p)',p+u(:,:,p)');
hold on;
end, hold off
view(60,55)
colorbar('Ticks',1:size(u,3) ...
,'TickLabels',[num2str(nPs) ['x';'x';'x'] num2str(nPs)]);
xlabel('space x'), ylabel('space y'), zlabel('u(x,y)')
ifOurCf2eps([mfilename 'us'])%optionally save
%{
\end{matlab}
\paragraph{Plot error surfaces} Plot the error surfaces,
with colour offset between surfaces (best if \(u\)-field has
a range of one): dark blue is the full-domain zero error,
reds the coarsest patches.
\begin{matlab}
%}
err=u(:,:,1)-u;
maxAbsErr=max(abs(err(:)));
figure(2), clf, colormap(jet)
for p=1:size(u,3)
mesh(x(:),y(:),err(:,:,p)',p+err(:,:,p)'/maxAbsErr);
hold on;
end, hold off
view(60,55)
colorbar('Ticks',1:size(u,3) ...
,'TickLabels',[num2str(nPs) ['x';'x';'x'] num2str(nPs)]);
xlabel('space x'), ylabel('space y')
zlabel('errors in u(x,y)')
ifOurCf2eps(mfilename)%optionally save
%{
\end{matlab}
\subsection{\texttt{twoscaleDiffForce2()}: microscale
discretisation inside patches of forced diffusion PDE}
\label{sec:twoscaleDiffForce2}
This function codes the lattice heterogeneous diffusion of
the \pde\ inside the patches. For 6D input arrays~\verb|u|,
\verb|x|, and~\verb|y|, computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|.
\begin{matlab}
%}
function ut = twoscaleDiffForce2(t,u,patches)
dx = diff(patches.x(2:3)); % x space step
dy = diff(patches.y(2:3)); % y space step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
ut = nan+u; % preallocate output array
%{
\end{matlab}
Set Dirichlet boundary value of zero around the square
domain.
\begin{matlab}
%}
u( 1 ,:,:,:, 1 ,:)=0; % left edge of left patches
u(end,:,:,:,end,:)=0; % right edge of right patches
u(:, 1 ,:,:,:, 1 )=0; % bottom edge of bottom patches
u(:,end,:,:,:,end)=0; % top edge of top patches
%{
\end{matlab}
Compute the time derivatives via stored forcing and
coefficients. Easier to code by conflating the last four
dimensions into the one~\verb|,:|.
\begin{matlab}
%}
ut(i,j,:) ...
= 2*diff(u(:,j,:),2,1)/dx^2 +2*diff(u(i,:,:),2,2)/dy^2 ...
+2*patches.cs(i,j).*( u(i+1,j+1,:) -u(i-1,j+1,:) ...
-u(i+1,j-1,:) +u(i-1,j-1,:) )/(4*dx*dy) ...
+patches.fu(i,j,:);
end%function twoscaleDiffForce2
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/patchEdgeInt1.m
| 15,387 |
utf_8
|
bb791ea67bf7f51783c12add715bca8b
|
% patchEdgeInt1() provides the interpolation across 1D space
% for 1D patches of simulations of a lattice system such as
% PDE discretisations. AJR & JB, Sep 2018 -- Jan 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt1()}: sets patch-edge values
from interpolation over the 1D macroscale}
\label{sec:patchEdgeInt1}
Couples 1D patches across 1D space by computing their edge
values from macroscale interpolation of either the mid-patch
value \cite[]{Roberts00a, Roberts06d}, or the patch-core
average \cite[]{Bunder2013b}, or the opposite next-to-edge
values \cite[]{Bunder2020a}---this last alternative often
maintains symmetry. This function is primarily used by
\verb|patchSys1()| but is also useful for user graphics.
When using core averages (not fully implemented), assumes
the averages are sensible macroscale variables: then patch
edge values are determined by macroscale interpolation of
the core averages \citep{Bunder2013b}. \footnote{Script
\texttt{patchEdgeInt1test.m} verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global
struct~\verb|patches|.
\begin{matlab}
%}
function u=patchEdgeInt1(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|nSubP| \cdot \verb|nVars|\cdot \verb|nEnsem|\cdot
\verb|nPatch|$ where there are $\verb|nVars|\cdot
\verb|nEnsem|$ field values at each of the points in the
$\verb|nSubP| \times \verb|nPatch|$ multiscale spatial grid.
\item \verb|patches| a struct largely set by
\verb|configPatches1()|, and which includes the following.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP| \times1 \times1 \times
\verb|nPatch|$ array of the spatial locations~$x_{iI}$ of
the microscale grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on the
microscale index~$i$, but may be variable spaced in
macroscale index~$I$.
\item \verb|.ordCC| is order of interpolation, integer~$\geq
-1$.
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left and right boundaries so interpolation is via divided
differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation, and zero for ordinary grid.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation---when invoking
a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation:
true, from opposite-edge next-to-edge values (often
preserves symmetry);
false, from centre-patch values (original scheme).
\item \verb|.nEnsem| the number of realisations in the ensemble.
\item \verb|.parallel| whether serial or parallel.
\item \verb|.nCore| \todo{introduced sometime but not fully
implemented yet, because prefer ensemble}
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 4D array, $\verb|nSubP| \times
\verb|nVars| \times \verb|nEnsem| \times \verb|nPatch|$, of
the fields with edge values set by interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[nx,~,~,Nx] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round(numel(u)/numel(patches.x)/nEnsem);
assert(numel(u) == nx*nVars*nEnsem*Nx ...
,'patchEdgeInt1: input u has wrong size for parameters')
u = reshape(u,nx,nVars,nEnsem,Nx);
%{
\end{matlab}
If the user has not defined the patch core, then we assume
it to be a single point in the middle of the patch, unless
we are interpolating from next-to-edge values.
These index vectors point to patches and their two
immediate neighbours, for periodic domain.
\begin{matlab}
%}
I = 1:Nx; Ip = mod(I,Nx)+1; Im = mod(I-2,Nx)+1;
%{
\end{matlab}
Calculate centre of each patch and the surrounding core
(\verb|nx| and \verb|nCore| are both odd).
\begin{matlab}
%}
i0 = round((nx+1)/2);
c = round((patches.nCore-1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches, then use finite width
stencils or spectral.
\begin{matlab}
%}
r = patches.ratio(1);
if patches.ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
\paragraph{Lagrange interpolation gives patch-edge values}
Consequently, compute centred differences of the patch
core/edge averages/values for the macro-interpolation of all
fields. Here the domain is macro-periodic.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-edge values
Ux = u([2 nx-1],:,:,I);
else % interpolate mid-patch values/sums
Ux = sum( u((i0-c):(i0+c),:,:,I) ,1);
end;
%{
\end{matlab}
Just in case any last array dimension(s) are one, we have to
force a padding of the sizes, then adjoin the extra
dimension for the subsequent array of differences.
\begin{matlab}
%}
szUxO=size(Ux);
szUxO=[szUxO ones(1,4-length(szUxO)) patches.ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences in these arrays. When parallel, in
order to preserve the distributed array structure we use an
index at the end for the differences.
\begin{matlab}
%}
if patches.parallel
dmu = zeros(szUxO,patches.codist); % 5D
else
dmu = zeros(szUxO); % 5D
end
%{
\end{matlab}
First compute differences, either $\mu$ and $\delta$, or
$\mu\delta$ and $\delta^2$ in space.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
dmu(:,:,:,I,1) = (Ux(:,:,:,Ip)+Ux(:,:,:,Im))/2; % \mu
dmu(:,:,:,I,2) = (Ux(:,:,:,Ip)-Ux(:,:,:,Im)); % \delta
Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
else % standard
dmu(:,:,:,I,1) = (Ux(:,:,:,Ip)-Ux(:,:,:,Im))/2; % \mu\delta
dmu(:,:,:,I,2) = (Ux(:,:,:,Ip)-2*Ux(:,:,:,I) ...
+Ux(:,:,:,Im)); % \delta^2
end%if patches.stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:patches.ordCC
dmu(:,:,:,:,k) = dmu(:,:,:,Ip,k-2) ...
-2*dmu(:,:,:,I,k-2) +dmu(:,:,:,Im,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet edge values for
each patch \cite[]{Roberts06d, Bunder2013b}, using weights
computed in \verb|configPatches1()|. Here interpolate to
specified order.
For the case where single-point values interpolate to
patch-edge values: when we have an ensemble of
configurations, different realisations are coupled to each
other as specified by \verb|patches.le| and
\verb|patches.ri|.
\begin{matlab}
%}
if patches.nCore==1
k=1+patches.EdgyInt; % use centre/core or two edges
u(nx,:,patches.ri,I) = Ux(1,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr,-4).*dmu(1,:,:,:,:) ,5);
u(1 ,:,patches.le,I) = Ux(k,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl,-4).*dmu(k,:,:,:,:) ,5);
%{
\end{matlab}
For a non-trivial core then more needs doing: the core (one
or more) of each patch interpolates to the edge action
regions. When more than one in the core, the edge is set
depending upon near edge values so the average near the edge
is correct.
\begin{matlab}
%}
else% patches.nCore>1
error('not yet considered, july--dec 2020 ??')
u(nx,:,:,I) = Ux(:,:,I)*(1-patches.stag) ...
+ reshape(-sum(u((nx-patches.nCore+1):(nx-1),:,:,I),1) ...
+ sum( patches.Cwtsr.*dmu ),Nx,nVars);
u(1,:,:,I) = Ux(:,:,I)*(1-patches.stag) ...
+ reshape(-sum(u(2:patches.nCore,:,:,I),1) ...
+ sum( patches.Cwtsl.*dmu ),Nx,nVars);
end%if patches.nCore
%{
\end{matlab}
\paragraph{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
As the macroscale fields are $N$-periodic, the macroscale
Fourier transform writes the centre-patch values as $U_j =
\sum_{k}C_ke^{ik2\pi j/N}$. Then the edge-patch values
$U_{j\pm r} =\sum_{k}C_ke^{ik2\pi/N(j\pm r)}
=\sum_{k}C'_ke^{ik2\pi j/N}$ where $C'_k =
C_ke^{ikr2\pi/N}$. For \verb|Nx|~patches we resolve
`wavenumbers' $|k|<\verb|Nx|/2$, so set row vector
$\verb|ks| = k2\pi/N$ for `wavenumbers'
$\mathcode`\,="213B k = (0,1, \ldots, k_{\max}, -k_{\max},
\ldots, -1)$ for odd~$N$, and $\mathcode`\,="213B k =
(0,1, \ldots, k_{\max}, (k_{\max}+1), -k_{\max}, \ldots,
-1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches1()|
tests that there are an even number of patches). Then the
patch-ratio is effectively halved. The patch edges are near
the middle of the gaps and swapped. \todo{Have not yet tested
whether works for Edgy Interpolation.}
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
v = nan(size(u)); % currently to restore the shape of u
u = [u(:,:,:,1:2:Nx) u(:,:,:,2:2:Nx)];
stagShift = 0.5*[ones(1,nVars) -ones(1,nVars)];
iV = [nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r = r/2; % ratio effectively halved
Nx = Nx/2; % halve the number of patches
nVars = nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Now set wavenumbers (when \verb|Nx| is even then highest
wavenumber is~$\pi$).
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
ks = shiftdim( ...
2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ...
,-2);
%{
\end{matlab}
Compute the Fourier transform across patches of the patch
centre or next-to-edge values for all the fields. If there
are an even number of points, then if complex, treat as
positive wavenumber, but if real, treat as cosine. When
using an ensemble of configurations, different
configurations might be coupled to each other, as specified
by \verb|patches.le| and \verb|patches.ri|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cleft = fft(u(i0 ,:,:,:),[],4);
Cright = Cleft;
else
Cleft = fft(u(2 ,:,:,:),[],4);
Cright= fft(u(nx-1,:,:,:),[],4);
end
%{
\end{matlab}
The inverse Fourier transform gives the edge values via a
shift a fraction~$r$ to the next macroscale grid point.
\begin{matlab}
%}
u(nx,iV,patches.ri,:) = uclean( ifft( ...
Cleft.*exp(1i*ks.*(stagShift+r)) ,[],4));
u(1 ,iV,patches.le,:) = uclean( ifft( ...
Cright.*exp(1i*ks.*(stagShift-r)) ,[],4));
%{
\end{matlab}
Restore staggered grid when appropriate. This dimensional
shifting appears to work.
Is there a better way to do this?
\begin{matlab}
%}
if patches.stag
nVars = nVars/2;
u=reshape(u,nx,nVars,2,nEnsem,Nx);
Nx = 2*Nx;
v(:,:,:,1:2:Nx) = u(:,:,1,:,:);
v(:,:,:,2:2:Nx) = u(:,:,2,:,:);
u = v;
end%if patches.stag
end%if patches.ordCC
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|p|, and hence
size of the (forward) divided difference table in~\verb|F|.
\begin{matlab}
%}
if patches.ordCC<1, patches.ordCC = Nx-1; end
p = min(patches.ordCC,Nx-1);
F = nan(patches.EdgyInt+1,nVars,nEnsem,Nx,p+1);
%{
\end{matlab}
Set function values in first `column' of the table for every
variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-edge values are because their
values are to interpolate to the opposite edge of each
patch.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-edge values
F(:,:,:,:,1) = u([nx-1 2],:,:,I);
X(:,:,:,:) = patches.x([nx-1 2],:,:,I);
else % interpolate mid-patch values/sums
F(:,:,:,:,1) = sum( u((i0-c):(i0+c),:,:,I) ,1);
X(:,:,:,:) = patches.x(i0,:,:,I);
end;
%{
\end{matlab}
Compute table of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable and
across ensemble.
\begin{matlab}
%}
for q = 1:p
i = 1:Nx-q;
F(:,:,:,i,q+1) = (F(:,:,:,i+1,q)-F(:,:,:,i,q)) ...
./(X(:,:,:,i+q) -X(:,:,:,i));
end
%{
\end{matlab}
Now interpolate to the edge-values at locations~\verb|Xedge|.
\begin{matlab}
%}
Xedge = patches.x([1 nx],:,:,:);
%{
\end{matlab}
Code Horner's evaluation of the interpolation polynomials.
Indices~\verb|i| are those of the left end of each
interpolation stencil because the table is of forward
differences.\footnote{For EdgyInt, perhaps interpret odd
order interpolation in such a way that first-order
interpolations reduces to appropriate linear interpolation
so that as patches abut the scheme is `full-domain'. May
mean left-edge and right-edge have different indices.
Explore sometime??} First alternative: the case of
order~\(p\) interpolation across the domain, asymmetric near
the boundary. Use this first alternative for now.
\begin{matlab}
%}
if true
i = max(1,min(1:Nx,Nx-ceil(p/2))-floor(p/2));
Uedge = F(:,:,:,i,p+1);
for q = p:-1:1
Uedge = F(:,:,:,i,q)+(Xedge-X(:,:,:,i+q-1)).*Uedge;
end
%{
\end{matlab}
Second alternative: lower the degree of interpolation near
the boundary to maintain the band-width of the
interpolation. Such symmetry might be essential for multi-D.
\footnote{The aim is to preserve symmetry?? Does it?? As of
Jan 2023 it only partially does---fails near boundaries, and
maybe fails with uneven spacing.}
\begin{matlab}
%}
else%if false
i = max(1,I-floor(p/2));
%{
\end{matlab}
For the tapering order of interpolation, form the interior
mask~\verb|Q| (logical) that signifies which interpolations
are to be done at order~\verb|q|. This logical mask spreads
by two as each order~\verb|q| decreases.
\begin{matlab}
%}
Q = (I-1>=floor(p/2)) & (Nx-I>=p/2);
Imid = floor(Nx/2);
%{
\end{matlab}
Initialise to highest divide difference, surrounded by zeros.
\begin{matlab}
%}
Uedge = zeros(patches.EdgyInt+1,nVars,nEnsem,Nx);
Uedge(:,:,:,Q) = F(:,:,:,i(Q),p+1);
%{
\end{matlab}
Complete Horner evaluation of the relevant polynomials.
\begin{matlab}
%}
for q = p:-1:1
Q = [Q(2:Imid) true(1,2) Q(Imid+1:end-1)]; % spread mask
Uedge(:,:,:,Q) = F(:,:,:,i(Q),q) ...
+(Xedge(:,:,:,Q)-X(:,:,:,i(Q)+q-1)).*Uedge(:,:,:,Q);
end%for q
end%if
%{
\end{matlab}
Finally, insert edge values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,:,patches.le,I) = Uedge(1,:,:,I);
u(nx,:,patches.ri,I) = Uedge(2,:,:,I);
%{
\end{matlab}
We want a user to set the extreme patch edge values
according to the microscale boundary conditions that hold at
the extremes of the domain. Consequently, may override
their computed interpolation values with~\verb|NaN|.
\begin{matlab}
%}
u( 1,:,:, 1) = nan;
u(nx,:,:,Nx) = nan;
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic
%{
\end{matlab}
Fin, returning the 4D array of field values.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
abdulleDiffEquil2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/abdulleDiffEquil2.m
| 6,045 |
utf_8
|
39a09e5e4134b72d1f242ad011a85436
|
% Solve for steady state of multiscale heterogeneous diffusion
% in 2D on patches as an example application, varied from
% example of section 5.1 of Abdulle et al., (2020b). AJR,
% 31 Jan 2023
%!TEX root = doc.tex
%{
\section{\texttt{abdulleDiffEquil2}: equilibrium of a 2D
multiscale heterogeneous diffusion via small patches}
\label{sec:abdulleDiffEquil2}
Here we find the steady state~\(u(x,y)\) to the
heterogeneous \pde\ \cite[inspired by][\S5.1]{Abdulle2020b}
\begin{equation*}
u_t=\divv[a(x,y)\grad u]+10,
\end{equation*}
on square domain \([0,1]^2\) with zero-Dirichlet BCs, for
coefficient `diffusion' matrix, varying with
period~\(\epsilon\) of (their~(45))
\begin{equation*}
a:=\frac{2+1.8\sin2\pi x/\epsilon}{2+1.8\cos2\pi y/\epsilon}
+\frac{2+\sin2\pi y/\epsilon}{2+1.8\cos2\pi x/\epsilon}.
\end{equation*}
\cref{fig:abdulleDiffEquil2} shows solutions have some
nice microscale wiggles reflecting the heterogeneity.
\begin{figure}
\centering\caption{\label{fig:abdulleDiffEquil2}%
Equilibrium of the macroscale diffusion problem of Abdulle
with boundary conditions of Dirichlet zero-value except for
\(x=0\) which is Neumann (\cref{sec:abdulleDiffEquil2}).
Here the patches have a Chebyshev-like spatial distribution.
The patch size is chosen large enough to see within.}
\includegraphics[scale=0.8]{Figs/abdulleDiffEquil2}
\end{figure}
Clear, and initiate globals.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plot
%{
\end{matlab}
First establish the microscale heterogeneity has
micro-period~\verb|mPeriod| on the spatial micro-grid
lattice. Then \verb|configPatches2| replicates the
heterogeneity to fill each patch. (These diffusion
coefficients should really recognise the half-grid-point
shifts, but let's not bother.)
\begin{matlab}
%}
mPeriod = 6
x = (0.5:mPeriod)'/mPeriod; y=x';
a = (2+1.8*sin(2*pi*x))./(2+1.8*sin(2*pi*y)) ...
+(2+ sin(2*pi*y))./(2+1.8*sin(2*pi*x));
diffusivityRange = [min(a(:)) max(a(:))]
%{
\end{matlab}
Set the periodicity~\(\epsilon\), here big enough so we can
see the patches, and other microscale parameters.
\begin{matlab}
%}
epsilon = 0.04
dx = epsilon/mPeriod
nPeriodsPatch = 1 % any integer
nSubP = nPeriodsPatch*mPeriod+2 % when edgy int
%{
\end{matlab}
\paragraph{Patch configuration} Choose either Dirichlet
(default) or Neumann on the left boundary in coordination
with micro-code in \cref{sec:abdulleDiffForce2}
\begin{matlab}
%}
Dom.bcOffset = zeros(2);
if 1, Dom.bcOffset(1)=0.5; end% left Neumann
%{
\end{matlab}
Say use \(7\times7\) patches in \((0,1)^2\), fourth order
interpolation, and either `equispace' or `chebyshev':
\begin{matlab}
%}
nPatch = 7
Dom.type='chebyshev';
configPatches2(@abdulleDiffForce2,[0 1],Dom ...
,nPatch ,4 ,dx ,nSubP ,'EdgyInt',true ,'hetCoeffs',a );
%{
\end{matlab}
\paragraph{Solve for steady state} Set initial guess of
zero, with \verb|NaN| to indicate patch-edge values.
Index~\verb|i| are the indices of patch-interior points, and
the number of unknowns is then its length.
\begin{matlab}
%}
u0 = zeros(nSubP,nSubP,1,1,nPatch,nPatch);
u0([1 end],:,:) = nan; u0(:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
Solve by iteration. Use \verb|fsolve| for simplicity and
robustness (and using \verb|optimoptions| to omit trace
information), via the generic patch system wrapper
\verb|theRes| (\cref{sec:theRes}), and give magnitudes.
\begin{matlab}
%}
tic;
uSoln = fsolve(@theRes,u0(patches.i) ...
,optimoptions('fsolve','Display','off'));
solnTime = toc
normResidual = norm(theRes(uSoln))
normSoln = norm(uSoln)
%{
\end{matlab}
Store the solution vector into the patches, and interpolate,
but have not bothered to set boundary values so they stay
NaN from the interpolation.
\begin{matlab}
%}
u0(patches.i) = uSoln;
u0 = patchEdgeInt2(u0);
%{
\end{matlab}
\paragraph{Draw solution profile} Separate patches with
NaNs, then reshape arrays to suit 2D space surface plots.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*hsv)
patches.x(end+1,:,:)=nan; u0(end+1,:,:)=nan;
patches.y(:,end+1,:)=nan; u0(:,end+1,:)=nan;
u = reshape(permute(squeeze(u0),[1 3 2 4]) ...
, [numel(patches.x) numel(patches.y)]);
%{
\end{matlab}
Draw the patch solution surface, with boundary-values
omitted as already~\verb|NaN| by not bothering to set them.
\begin{matlab}
%}
mesh(patches.x(:),patches.y(:),u'); view(60,55)
xlabel('space $x$'), ylabel('space $y$'), zlabel('$u(x,y)$')
ifOurCf2eps(mfilename) %optionally save plot
%{
\end{matlab}
\subsection{\texttt{abdulleDiffForce2()}: microscale
discretisation inside patches of forced diffusion PDE}
\label{sec:abdulleDiffForce2}
This function codes the lattice heterogeneous diffusion of
the \pde\ inside the patches. For 6D input arrays~\verb|u|,
\verb|x|, and~\verb|y|, computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|.
\begin{matlab}
%}
function ut = abdulleDiffForce2(t,u,patches)
dx = diff(patches.x(2:3)); % x space step
dy = diff(patches.y(2:3)); % y space step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
ut = nan+u; % preallocate output array
%{
\end{matlab}
Set Dirichlet boundary value of zero around the square
domain, but also cater for zero Neumann condition on the
left boundary.
\begin{matlab}
%}
u( 1 ,:,:,:, 1 ,:)=0; % left edge of left patches
u(end,:,:,:,end,:)=0; % right edge of right patches
u(:, 1 ,:,:,:, 1 )=0; % bottom edge of bottom patches
u(:,end,:,:,:,end)=0; % top edge of top patches
if 1, u(1,:,:,:,1,:)=u(2,:,:,:,1,:); end% left Neumann
%{
\end{matlab}
Compute the time derivatives via stored forcing and
coefficients. Easier to code by conflating the last four
dimensions into the one~\verb|,:|.
\begin{matlab}
%}
ut(i,j,:) = diff(patches.cs(:,j).*diff(u(:,j,:)))/dx^2 ...
+ diff(patches.cs(i,:).*diff(u(i,:,:),1,2),1,2)/dy^2 ...
+ 10;
end%function abdulleDiffForce2
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
theRes.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/theRes.m
| 1,032 |
utf_8
|
8cdbd483b1840c6fb1b04f49c5e6fbda
|
% This functions converts a vector of values into the
% interior values of the patches, then evaluates the time
% derivative of the system at $t=1$, and returns the vector
% of patch-interior time derivatives. AJR, 1 Feb 2023
%!TEX root = doc.tex
%{
\section{\texttt{theRes()}: wrapper function to zero}
\label{sec:theRes}
This functions converts a vector of values into the interior
values of the patches, then evaluates the time derivative of
the system at time \(t=1\), and returns the vector of
patch-interior time derivatives.
\begin{matlab}
%}
function f=theRes(u)
global patches
switch numel(size(patches.x))
case 4, pSys = @patchSys1;
v=nan(size(patches.x));
case 5, pSys = @patchSys2;
v=nan(size(patches.x+patches.y));
case 6, pSys = @patchSys3;
v=nan(size(patches.x+patches.y+patches.z));
otherwise error('number of dimensions is somehow wrong')
end%switch
v(patches.i) = u;
f = pSys(1,v(:),patches);
f = f(patches.i);
end%function theRes
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
heteroDiffF.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/heteroDiffF.m
| 1,725 |
utf_8
|
05cc0adfbdb44ef3b989b2c4a40bccfa
|
% Computes the time derivatives of forced heterogeneous
% diffusion in 1D on patches. AJR, Apr 2019 -- 3 Jan 2023
%!TEX root = doc.tex
%{
\subsection{\texttt{heteroDiffF()}: forced heterogeneous diffusion}
\label{sec:heteroDiffF}
This function codes the lattice heterogeneous diffusion
inside the patches with forcing and with microscale boundary
conditions on the macroscale boundaries. Computes the time
derivative at each point in the interior of a patch, output
in~\verb|ut|. The column vector of diffusivities~\(a_i\)
has been stored in struct~\verb|patches.cs|, as has the
array of forcing coefficients.
\begin{matlab}
%}
function ut = heteroDiffF(t,u,patches)
%{
\end{matlab}
Cater for the two cases: one of a non-autonomous forcing
oscillating in time when \(\verb|microTimePeriod|>0\), or
otherwise the case of an autonomous diffusion constant in
time.
\begin{matlab}
%}
global microTimePeriod
if microTimePeriod>0 % optional time fluctuations
at = cos(2*pi*t/microTimePeriod)/30;
else at=0; end
%{
\end{matlab}
Two basic parameters, and initialise result array to NaNs.
\begin{matlab}
%}
dx = diff(patches.x(2:3)); % space step
i = 2:size(u,1)-1; % interior points in a patch
ut = nan+u; % preallocate output array
%{
\end{matlab}
The macroscale Dirichlet boundary conditions are zero at the
extreme edges of the two extreme patches.
\begin{matlab}
%}
u( 1 ,:,:, 1 )=0; % left-edge of leftmost is zero
u(end,:,:,end)=0; % right-edge of rightmost is zero
%{
\end{matlab}
Code the microscale forced diffusion.
\begin{matlab}
%}
ut(i,:,:,:) = diff((patches.cs(:,1,:)+at).*diff(u))/dx^2 ...
+patches.f2(i,:,:,:)*t^2+patches.f1(i,:,:,:)*t;
end% function
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
configPatches3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/configPatches3.m
| 32,908 |
utf_8
|
d0d168ba4e05326bca019ec74e76e6c7
|
% configPatches3() creates a data struct of the design of 3D
% patches for later use by the patch functions such as
% patchSys3(). AJR, Aug 2020 -- 2 Feb 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{configPatches3()}: configures spatial
patches in 3D}
\label{sec:configPatches3}
\localtableofcontents
Makes the struct~\verb|patches| for use by the patch\slash
gap-tooth time derivative\slash step function
\verb|patchSys3()|, and possibly other patch functions.
\cref{sec:configPatches3eg,sec:homoDiffEdgy3} list examples
of its use.
\begin{matlab}
%}
function patches = configPatches3(fun,Xlim,Dom ...
,nPatch,ordCC,dx,nSubP,varargin)
%{
\end{matlab}
\paragraph{Input}
If invoked with no input arguments, then executes an example
of simulating a heterogeneous wave \pde---see
\cref{sec:configPatches3eg} for an example code.
\begin{itemize}
\item \verb|fun| is the name of the user function,
\verb|fun(t,u,patches)| or \verb|fun(t,u)|, that computes
time-derivatives (or time-steps) of quantities on the 3D
micro-grid within all the 3D~patches.
\item \verb|Xlim| array/vector giving the rectangular-cuboid
macro-space domain of the computation: namely
$[\verb|Xlim(1)|, \verb|Xlim(2)|] \times [\verb|Xlim(3)|,
\verb|Xlim(4)| \times [\verb|Xlim(5)|, \verb|Xlim(6)|]$. If
\verb|Xlim| has two elements, then the domain is the cubic
domain of the same interval in all three directions.
\item \verb|Dom| sets the type of macroscale conditions for
the patches, and reflects the type of microscale boundary
conditions of the problem. If \verb|Dom| is \verb|NaN| or
\verb|[]|, then the field~\verb|u| is triply macro-periodic
in the 3D spatial domain, and resolved on equi-spaced
patches. If \verb|Dom| is a character string, then that
specifies the \verb|.type| of the following structure, with
\verb|.bcOffset| set to the default zero. Otherwise
\verb|Dom| is a structure with the following components.
\begin{itemize}
\item \verb|.type|, string, of either \verb|'periodic'| (the
default), \verb|'equispace'|, \verb|'chebyshev'|,
\verb|'usergiven'|. For all cases except \verb|'periodic'|,
users \emph{must} code into \verb|fun| the micro-grid
boundary conditions that apply at the left\slash right\slash
bottom\slash top\slash back\slash front faces of the
leftmost\slash rightmost\slash bottommost\slash
topmost\slash backmost\slash frontmost patches,
respectively.
\item \verb|.bcOffset|, optional one, three or six element
vector/array, in the cases of \verb|'equispace'| or
\verb|'chebyshev'| the patches are placed so the left\slash
right macroscale boundaries are aligned to the left\slash
right faces of the corresponding extreme patches, but offset
by \verb|bcOffset| of the sub-patch micro-grid spacing. For
example, use \verb|bcOffset=0| when the micro-code applies
Dirichlet boundary values on the extreme face micro-grid
points, whereas use \verb|bcOffset=0.5| when the microcode
applies Neumann boundary conditions halfway between the
extreme face micro-grid points. Similarly for the top,
bottom, back, and front faces.
If \verb|.bcOffset| is a scalar, then apply the same offset
to all boundaries. If three elements, then apply the first
offset to both \(x\)-boundaries, the second offset to both
\(y\)-boundaries, and the third offset to both
\(z\)-boundaries. If six elements, then apply the first two
offsets to the respective \(x\)-boundaries, the middle two
offsets to the respective \(y\)-boundaries, and the last two
offsets to the respective \(z\)-boundaries.
\item \verb|.X|, optional vector/array with \verb|nPatch(1)|
elements, in the case \verb|'usergiven'| it specifies the
\(x\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\item \verb|.Y|, optional vector/array with \verb|nPatch(2)|
elements, in the case \verb|'usergiven'| it specifies the
\(y\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\item \verb|.Z|, optional vector/array with \verb|nPatch(3)|
elements, in the case \verb|'usergiven'| it specifies the
\(z\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\end{itemize}
\item \verb|nPatch| sets the number of equi-spaced spatial
patches: if scalar, then use the same number of patches in
all three directions, otherwise \verb|nPatch(1:3)| gives the
number~($\geq1$) of patches in each direction.
\item \verb|ordCC| is the `order' of interpolation for
inter-patch coupling across empty space of the macroscale
patch values to the face-values of the patches: currently
must be~$0,2,4,\ldots$; where $0$~gives spectral
interpolation.
\item \verb|dx| (real---scalar or three elements) is usually
the sub-patch micro-grid spacing in~\(x\), \(y\) and~\(z\).
If scalar, then use the same \verb|dx| in all three
directions, otherwise \verb|dx(1:3)| gives the spacing in
each of the three directions.
However, if \verb|Dom| is~\verb|NaN| (as for pre-2023), then
\verb|dx| actually is \verb|ratio| (scalar or three elements),
namely the ratio of (depending upon \verb|EdgyInt|) either
the half-width or full-width of a patch to the equi-spacing
of the patch mid-points. So either $\verb|ratio|=\tfrac12$
means the patches abut and $\verb|ratio|=1$ is overlapping
patches as in holistic discretisation, or $\verb|ratio|=1$
means the patches abut. Small~\verb|ratio| should greatly
reduce computational time.
\item \verb|nSubP| is the number of equi-spaced microscale
lattice points in each patch: if scalar, then use the same
number in all three directions, otherwise \verb|nSubP(1:3)|
gives the number in each direction. If not using
\verb|EdgyInt|, then must be odd so that there is/are
centre-patch micro-grid point\slash planes in each patch.
\item \verb|'nEdge'| (not yet implemented), \emph{optional},
default=1, for each patch, the number of face values set by
interpolation at the face regions of each patch. The
default is one (suitable for microscale lattices with only
nearest neighbour interactions).
\item \verb|'EdgyInt'|, true/false, \emph{optional},
default=false. If true, then interpolate to left\slash
right\slash top\slash bottom\slash front\slash back
face-values from right\slash left\slash bottom\slash
top\slash back\slash front next-to-face values. If false or
omitted, then interpolate from centre-patch planes.
\item \verb|'nEnsem'|, \emph{optional-experimental},
default one, but if more, then an ensemble over this number
of realisations.
\item \verb|'hetCoeffs'|, \emph{optional}, default empty.
Supply a 3D or 4D array of microscale heterogeneous
coefficients to be used by the given microscale \verb|fun|
in each patch. Say the given array~\verb|cs| is of size
$m_x\times m_y\times m_z\times n_c$, where $n_c$~is the
number of different arrays of coefficients. For example, in
heterogeneous diffusion, $n_c=3$ for the diffusivities in
the \emph{three} different spatial directions (or $n_c=6$
for the diffusivity tensor). The coefficients are to be the
same for each and every patch. However, macroscale
variations are catered for by the $n_c$~coefficients being
$n_c$~parameters in some macroscale formula.
\begin{itemize}
\item If $\verb|nEnsem|=1$, then the array of coefficients
is just tiled across the patch size to fill up each patch,
starting from the $(1,1,1)$-point in each patch.
\item If $\verb|nEnsem|>1$ (value immaterial), then reset
$\verb|nEnsem|:=m_x\cdot m_y\cdot m_z$ and construct an
ensemble of all $m_x\cdot m_y\cdot m_z$ phase-shifts of
the coefficients. In this scenario, the inter-patch
coupling couples different members in the ensemble. When
\verb|EdgyInt| is true, and when the coefficients are
diffusivities\slash elasticities in $x,y,z$-directions,
respectively, then this coupling cunningly preserves
symmetry.
\end{itemize}
\item \verb|'parallel'|, true/false, \emph{optional},
default=false. If false, then all patch computations are on
the user's main \textsc{cpu}---although a user may well
separately invoke, say, a \textsc{gpu} to accelerate
sub-patch computations.
If true, and it requires that you have \Matlab's Parallel
Computing Toolbox, then it will distribute the patches over
multiple \textsc{cpu}s\slash cores. In \Matlab, only one
array dimension can be split in the distribution, so it
chooses the one space dimension~$x,y,z$ corresponding to
the highest~\verb|nPatch| (if a tie, then chooses the
rightmost of~$x,y,z$). A user may correspondingly
distribute arrays with property \verb|patches.codist|, or
simply use formulas invoking the preset distributed arrays
\verb|patches.x|, \verb|patches.y|, and \verb|patches.z|. If
a user has not yet established a parallel pool, then a
`local' pool is started.
\end{itemize}
\paragraph{Output} The struct \verb|patches| is created and
set with the following components. If no output variable is
provided for \verb|patches|, then make the struct available
as a global variable.\footnote{When using \texttt{spmd}
parallel computing, it is generally best to avoid global
variables, and so instead prefer using an explicit output
variable.}
\begin{matlab}
%}
if nargout==0, global patches, end
%{
\end{matlab}
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| or \verb|fun(t,u)| that computes the
time derivatives (or steps) on the patchy lattice.
\item \verb|.ordCC| is the specified order of inter-patch
coupling.
\item \verb|.periodic|: either true, for interpolation on
the macro-periodic domain; or false, for general
interpolation by divided differences over non-periodic
domain or unevenly distributed patches.
\item \verb|.stag| is true for interpolation using only odd
neighbouring patches as for staggered grids, and false for
the usual case of all neighbour coupling---not yet
implemented.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the
$\verb|ordCC|\times 3$-array of weights for the inter-patch
interpolation onto the right\slash top\slash front and
left\slash bottom\slash back faces (respectively) with
patch:macroscale ratio as specified or as derived
from~\verb|dx|.
\item \verb|.x| (8D) is $\verb|nSubP(1)| \times1 \times1
\times1 \times1 \times \verb|nPatch(1)| \times1 \times1$
array of the regular spatial locations~$x_{iI}$ of the
microscale grid points in every patch.
\item \verb|.y| (8D) is $1 \times \verb|nSubP(2)| \times1
\times1 \times1 \times1 \times \verb|nPatch(2)| \times1$
array of the regular spatial locations~$y_{jJ}$ of the
microscale grid points in every patch.
\item \verb|.z| (8D) is $1 \times1 \times \verb|nSubP(3)|
\times1 \times1 \times1 \times1 \times \verb|nPatch(3)|$
array of the regular spatial locations~$z_{kK}$ of the
microscale grid points in every patch.
\item \verb|.ratio| $1\times 3$, only for macro-periodic
conditions, are the size ratios of every patch.
\item \verb|.nEdge| is, for each patch, the number of face
values set by interpolation at the face regions of each
patch.
\item \verb|.le|, \verb|.ri|, \verb|.bo|, \verb|.to|,
\verb|.ba|, \verb|.fr| determine inter-patch coupling of
members in an ensemble. Each a column vector of
length~\verb|nEnsem|.
\item \verb|.cs| either
\begin{itemize}
\item \verb|[]| 0D, or
\item if $\verb|nEnsem|=1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times (\verb|nSubP(3)|-1)\times n_c$ 4D
array of microscale heterogeneous coefficients, or
\item if $\verb|nEnsem|>1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times (\verb|nSubP(3)|-1)\times
n_c\times m_xm_ym_z$ 5D array of $m_xm_ym_z$~ensemble of
phase-shifts of the microscale heterogeneous coefficients.
\end{itemize}
\item \verb|.parallel|, logical: true if patches are
distributed over multiple \textsc{cpu}s\slash cores for the
Parallel Computing Toolbox, otherwise false (the default is
to activate the \emph{local} pool).
\item \verb|.codist|, \emph{optional}, describes the
particular parallel distribution of arrays over the active
parallel pool.
\end{itemize}
\subsection{If no arguments, then execute an example}
\label{sec:configPatches3eg}
\begin{matlab}
%}
if nargin==0
disp('With no arguments, simulate example of heterogeneous wave')
%{
\end{matlab}
The code here shows one way to get started: a user's script
may have the following three steps (``\into'' denotes function
recursion).
\begin{enumerate}\def\itemsep{-1.5ex}
\item configPatches3
\item ode23 integrator \into patchSys3 \into user's PDE
\item process results
\end{enumerate}
Set random heterogeneous
coefficients of period two in each of the three
directions. Crudely normalise by the harmonic mean so the
macro-wave time scale is roughly one.
\begin{matlab}
%}
mPeriod = [2 2 2];
cHetr = exp(0.9*randn([mPeriod 3]));
cHetr = cHetr*mean(1./cHetr(:))
%{
\end{matlab}
Establish global patch data struct to interface with a
function coding a nonlinear `diffusion' \pde: to be solved
on $[-\pi,\pi]^3$-periodic domain, with $5^3$~patches,
spectral interpolation~($0$) couples the patches, each patch
with micro-grid spacing~$0.22$ (relatively large for
visualisation), and with $4^3$~points forming each patch.
\begin{matlab}
%}
global patches
patches = configPatches3(@heteroWave3,[-pi pi], 'periodic' ...
, 5, 0, 0.22, mPeriod+2 ,'EdgyInt',true ...
,'hetCoeffs',cHetr);
%{
\end{matlab}
Set a wave initial state using auto-replication of the
spatial grid, and as \cref{fig:configPatches3ic} shows. This
wave propagates diagonally across space. Concatenate the two
\(u,v\)-fields to be the two components of the fourth
dimension.
\begin{matlab}
%}
u0 = 0.5+0.5*sin(patches.x+patches.y+patches.z);
v0 = -0.5*cos(patches.x+patches.y+patches.z)*sqrt(3);
uv0 = cat(4,u0,v0);
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:configPatches3ic}initial
field~$u(x,y,z,t)$ at time $t=0$ of the patch scheme
applied to a heterogeneous wave~\pde:
\cref{fig:configPatches3fin} plots the computed field at
time $t=6$.}
\includegraphics[scale=0.9]{configPatches3ic}
\end{figure}
Integrate in time to $t=6$ using standard functions. In
Matlab \verb|ode15s| would be natural as the patch scheme is
naturally stiff, but \verb|ode23| is much quicker
\cite[Fig.~4]{Maclean2020a}.
\begin{matlab}
%}
disp('Simulate heterogeneous wave u_tt=div[C*grad(u)]')
if ~exist('OCTAVE_VERSION','builtin')
[ts,us] = ode23(@patchSys3,linspace(0,6),uv0(:));
else %disp('octave version is very slow for me')
lsode_options('absolute tolerance',1e-4);
lsode_options('relative tolerance',1e-4);
[ts,us] = odeOcts(@patchSys3,[0 1 2],uv0(:));
end
%{
\end{matlab}
Animate the computed simulation to end with
\cref{fig:configPatches3fin}. Use \verb|patchEdgeInt3| to
obtain patch-face values in order to most easily reconstruct
the array data structure.
Replicate $x$, $y$, and~$z$ arrays to get individual
spatial coordinates of every data point. Then, optionally,
set faces to~\verb|nan| so the plot just shows
patch-interior data.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*jet)
xs = patches.x+0*patches.y+0*patches.z;
ys = patches.y+0*patches.x+0*patches.z;
zs = patches.z+0*patches.y+0*patches.x;
if 1, xs([1 end],:,:,:)=nan;
xs(:,[1 end],:,:)=nan;
xs(:,:,[1 end],:)=nan;
end;%option
j=find(~isnan(xs));
%{
\end{matlab}
In the scatter plot, these functions \verb|pix()| and
\verb|col()| map the $u$-data values to the size of the
dots and to the colour of the dots, respectively.
\begin{matlab}
%}
pix = @(u) 15*abs(u)+7;
col = @(u) sign(u).*abs(u);
%{
\end{matlab}
Loop to plot at each and every time step.
\begin{matlab}
%}
for i = 1:length(ts)
uv = patchEdgeInt3(us(i,:));
u = uv(:,:,:,1,:);
for p=1:2
subplot(1,2,p)
if (i==1)| exist('OCTAVE_VERSION','builtin')
scat(p) = scatter3(xs(j),ys(j),zs(j),'filled');
axis equal, caxis(col([0 1])), view(45-5*p,25)
xlabel('x'), ylabel('y'), zlabel('z')
title('view stereo pair cross-eyed')
end % in matlab just update values
set(scat(p),'CData',col(u(j)) ...
,'SizeData',pix((8+xs(j)-ys(j)+zs(j))/6+0*u(j)));
legend(['time = ' num2str(ts(i),'%4.2f')],'Location','north')
end
%{
\end{matlab}
Optionally save the initial condition to graphic file for
\cref{fig:configPatches2ic}, and optionally save the last
plot.
\begin{matlab}
%}
if i==1,
ifOurCf2eps([mfilename 'ic'])
disp('Type space character to animate simulation')
pause
else pause(0.05)
end
end% i-loop over all times
ifOurCf2eps([mfilename 'fin'])
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:configPatches3fin}field~$u(x,y,z,t)$
at time $t=6$ of the patch scheme applied to the
heterogeneous wave~\pde\ with initial condition in
\cref{fig:configPatches3ic}.}
\includegraphics[scale=0.9]{configPatches3fin}
\end{figure}
Upon finishing execution of the example, exit this function.
\begin{matlab}
%}
return
end%if no arguments
%{
\end{matlab}
\IfFileExists{../Patch/heteroWave3.m}{\input{../Patch/heteroWave3.m}}{}
\begin{devMan}
\subsection{Parse input arguments and defaults}
\begin{matlab}
%}
p = inputParser;
fnValidation = @(f) isa(f, 'function_handle'); %test for fn name
addRequired(p,'fun',fnValidation);
addRequired(p,'Xlim',@isnumeric);
%addRequired(p,'Dom'); % too flexible
addRequired(p,'nPatch',@isnumeric);
addRequired(p,'ordCC',@isnumeric);
addRequired(p,'dx',@isnumeric);
addRequired(p,'nSubP',@isnumeric);
addParameter(p,'nEdge',1,@isnumeric);
addParameter(p,'EdgyInt',false,@islogical);
addParameter(p,'nEnsem',1,@isnumeric);
addParameter(p,'hetCoeffs',[],@isnumeric);
addParameter(p,'parallel',false,@islogical);
%addParameter(p,'nCore',1,@isnumeric); % not yet implemented
parse(p,fun,Xlim,nPatch,ordCC,dx,nSubP,varargin{:});
%{
\end{matlab}
Set the optional parameters.
\begin{matlab}
%}
patches.nEdge = p.Results.nEdge;
patches.EdgyInt = p.Results.EdgyInt;
patches.nEnsem = p.Results.nEnsem;
cs = p.Results.hetCoeffs;
patches.parallel = p.Results.parallel;
%patches.nCore = p.Results.nCore;
%{
\end{matlab}
Initially duplicate parameters for three space dimensions as
needed.
\begin{matlab}
%}
if numel(Xlim)==2, Xlim = repmat(Xlim,1,3); end
if numel(nPatch)==1, nPatch = repmat(nPatch,1,3); end
if numel(dx)==1, dx = repmat(dx,1,3); end
if numel(nSubP)==1, nSubP = repmat(nSubP,1,3); end
%{
\end{matlab}
Check parameters.
\begin{matlab}
%}
assert(Xlim(1)<Xlim(2) ...
,'first pair of Xlim must be ordered increasing')
assert(Xlim(3)<Xlim(4) ...
,'second pair of Xlim must be ordered increasing')
assert(Xlim(5)<Xlim(6) ...
,'third pair of Xlim must be ordered increasing')
assert(patches.nEdge==1 ...
,'multi-edge-value interp not yet implemented')
assert(all(2*patches.nEdge<nSubP) ...
,'too many edge values requested')
%if patches.nCore>1
% warning('nCore>1 not yet tested in this version')
% end
%{
\end{matlab}
For compatibility with pre-2023 functions, if parameter
\verb|Dom| is \verb|Nan|, then we set the \verb|ratio| to
be the value of the so-called \verb|dx| vector.
\begin{matlab}
%}
if ~isstruct(Dom), pre2023=isnan(Dom);
else pre2023=false; end
if pre2023, ratio=dx; dx=nan; end
%{
\end{matlab}
Default macroscale conditions are periodic with evenly
spaced patches.
\begin{matlab}
%}
if isempty(Dom), Dom=struct('type','periodic'); end
if (~isstruct(Dom))&isnan(Dom), Dom=struct('type','periodic'); end
%{
\end{matlab}
If \verb|Dom| is a string, then just set type to that
string, and subsequently set corresponding defaults for
others fields.
\begin{matlab}
%}
if ischar(Dom), Dom=struct('type',Dom); end
%{
\end{matlab}
We allow different macroscale domain conditions in the
different directions. But for the moment do not allow
periodic to be mixed with the others (as the interpolation
mechanism is different code)---hence why we choose
\verb|periodic| be seven characters, whereas the others are
eight characters. The different conditions are coded in
different rows of \verb|Dom.type|, so we duplicate the
string if only one row specified.
\begin{matlab}
%}
if size(Dom.type,1)==1, Dom.type=repmat(Dom.type,3,1); end
%{
\end{matlab}
Check what is and is not specified, and provide default of
Dirichlet boundaries if no \verb|bcOffset| specified when
needed. Do so for all three directions independently.
\begin{matlab}
%}
patches.periodic=false;
for p=1:3
switch Dom.type(p,:)
case 'periodic'
patches.periodic=true;
if isfield(Dom,'bcOffset')
warning('bcOffset not available for Dom.type = periodic'), end
msg=' not available for Dom.type = periodic';
if isfield(Dom,'X'), warning(['X' msg]), end
if isfield(Dom,'Y'), warning(['Y' msg]), end
if isfield(Dom,'Z'), warning(['Z' msg]), end
case {'equispace','chebyshev'}
if ~isfield(Dom,'bcOffset'), Dom.bcOffset=zeros(2,3); end
% for mixed with usergiven, following should still work
if numel(Dom.bcOffset)==1
Dom.bcOffset=repmat(Dom.bcOffset,2,3); end
if numel(Dom.bcOffset)==3
Dom.bcOffset=repmat(Dom.bcOffset(:)',2,1); end
msg=' not available for Dom.type = equispace or chebyshev';
if (p==1)& isfield(Dom,'X'), warning(['X' msg]), end
if (p==2)& isfield(Dom,'Y'), warning(['Y' msg]), end
if (p==3)& isfield(Dom,'Z'), warning(['Z' msg]), end
case 'usergiven'
% if isfield(Dom,'bcOffset')
% warning('bcOffset not available for usergiven Dom.type'), end
msg=' required for Dom.type = usergiven';
if p==1, assert(isfield(Dom,'X'),['X' msg]), end
if p==2, assert(isfield(Dom,'Y'),['Y' msg]), end
if p==3, assert(isfield(Dom,'Z'),['Z' msg]), end
otherwise
error([Dom.type 'is unknown Dom.type'])
end%switch Dom.type
end%for p
%{
\end{matlab}
\subsection{The code to make patches}
First, store the pointer to the time derivative function in
the struct.
\begin{matlab}
%}
patches.fun = fun;
%{
\end{matlab}
Second, store the order of interpolation that is to provide
the values for the inter-patch coupling conditions. Spectral
coupling is \verb|ordCC| of~$0$ or (not yet??)~$-1$.
\begin{matlab}
%}
assert((ordCC>=-1) & (floor(ordCC)==ordCC), ...
'ordCC out of allowed range integer>=-1')
%{
\end{matlab}
For odd~\verb|ordCC| do interpolation based upon odd
neighbouring patches as is useful for staggered grids.
\begin{matlab}
%}
patches.stag = mod(ordCC,2);
assert(patches.stag==0,'staggered not yet implemented??')
ordCC = ordCC+patches.stag;
patches.ordCC = ordCC;
%{
\end{matlab}
Check for staggered grid and periodic case.
\begin{matlab}
%}
if patches.stag, assert(all(mod(nPatch,2)==0), ...
'Require an even number of patches for staggered grid')
end
%{
\end{matlab}
\paragraph{Set the macro-distribution of patches}
Third, set the centre of the patches in the macroscale grid
of patches. Loop over the coordinate directions, setting
the distribution into~\verb|Q| and finally assigning to
array of corresponding direction.
\begin{matlab}
%}
for q=1:3
qq=2*q-1;
%{
\end{matlab}
Distribution depends upon \verb|Dom.type|:
\begin{matlab}
%}
switch Dom.type(q,:)
%{
\end{matlab}
%: case periodic
The periodic case is evenly spaced within the spatial
domain. Store the size ratio in \verb|patches|.
\begin{matlab}
%}
case 'periodic'
Q=linspace(Xlim(qq),Xlim(qq+1),nPatch(q)+1);
DQ=Q(2)-Q(1);
Q=Q(1:nPatch(q))+diff(Q)/2;
pEI=patches.EdgyInt;% abbreviation
if pre2023, dx(q) = ratio(q)*DQ/(nSubP(q)-1-pEI)*(2-pEI);
else ratio(q) = dx(q)/DQ*(nSubP(q)-1-pEI)/(2-pEI);
end
patches.ratio=ratio;
%{
\end{matlab}
%: case equispace
The equi-spaced case is also evenly spaced but with the
extreme edges aligned with the spatial domain boundaries,
modified by the offset.
\begin{matlab}
%}
case 'equispace'
Q=linspace(Xlim(qq)+((nSubP(q)-1)/2-Dom.bcOffset(qq))*dx(q) ...
,Xlim(qq+1)-((nSubP(q)-1)/2-Dom.bcOffset(qq+1))*dx(q) ...
,nPatch(q));
DQ=diff(Q(1:2));
width=(1+patches.EdgyInt)/2*(nSubP(q)-1-patches.EdgyInt)*dx;
if DQ<width*0.999999
warning('too many equispace patches (double overlapping)')
end
%{
\end{matlab}
%: case chebyshev
The Chebyshev case is spaced according to the Chebyshev
distribution in order to reduce macro-interpolation errors,
\(Q_i \propto -\cos(i\pi/N)\), but with the extreme edges
aligned with the spatial domain boundaries, modified by the
offset, and modified by possible `boundary layers'.
\footnote{ However, maybe overlapping patches near a
boundary should be viewed as some sort of spatially analogue
of the `christmas tree' of projective integration and its
integration to a slow manifold. Here maybe the overlapping
patches allow for a `christmas tree' approach to the
boundary layers. Needs to be explored??}
\begin{matlab}
%}
case 'chebyshev'
halfWidth=dx(q)*(nSubP(q)-1)/2;
Q1 = Xlim(1)+halfWidth-Dom.bcOffset(qq)*dx(q);
Q2 = Xlim(2)-halfWidth+Dom.bcOffset(qq+1)*dx(q);
% Q = (Q1+Q2)/2-(Q2-Q1)/2*cos(linspace(0,pi,nPatch));
%{
\end{matlab}
Search for total width of `boundary layers' so that in the
interior the patches are non-overlapping Chebyshev. But
the width for assessing overlap of patches is the following
variable \verb|width|.
\begin{matlab}
%}
width=(1+patches.EdgyInt)/2*(nSubP(q)-1-patches.EdgyInt)*dx(q);
for b=0:2:nPatch(q)-2
DQmin=(Q2-Q1-b*width)/2*( 1-cos(pi/(nPatch(q)-b-1)) );
if DQmin>width, break, end
end%for
if DQmin<width*0.999999
warning('too many Chebyshev patches (mid-domain overlap)')
end%if
%{
\end{matlab}
Assign the centre-patch coordinates.
\begin{matlab}
%}
Q =[ Q1+(0:b/2-1)*width ...
(Q1+Q2)/2-(Q2-Q1-b*width)/2*cos(linspace(0,pi,nPatch(q)-b)) ...
Q2+(1-b/2:0)*width ];
%{
\end{matlab}
%: case usergiven
The user-given case is entirely up to a user to specify, we
just ensure it has the correct shape of a row.
\begin{matlab}
%}
case 'usergiven'
if q==1, Q = reshape(Dom.X,1,[]); end
if q==2, Q = reshape(Dom.Y,1,[]); end
if q==3, Q = reshape(Dom.Z,1,[]); end
end%switch Dom.type
%{
\end{matlab}
Assign \(Q\)-coordinates to the correct spatial direction.
At this stage they are all rows.
\begin{matlab}
%}
if q==1, X=Q; end
if q==2, Y=Q; end
if q==3, Z=Q; end
end%for q
%{
\end{matlab}
\paragraph{Construct the micro-grids}
Construct the microscale in each patch. Reshape the grid
to be 8D to suit dimensions (micro,Vars,Ens,macro).
\begin{matlab}
%}
nSubP = reshape(nSubP,1,3); % force to be row vector
assert(patches.EdgyInt | all(mod(nSubP,2)==1), ...
'configPatches3: nSubP must be odd')
i0 = (nSubP(1)+1)/2;
patches.x = reshape( dx(1)*(-i0+1:i0-1)'+X ...
,nSubP(1),1,1,1,1,nPatch(1),1,1);
i0 = (nSubP(2)+1)/2;
patches.y = reshape( dx(2)*(-i0+1:i0-1)'+Y ...
,1,nSubP(2),1,1,1,1,nPatch(2),1);
i0 = (nSubP(3)+1)/2;
patches.z = reshape( dx(3)*(-i0+1:i0-1)'+Z ...
,1,1,nSubP(3),1,1,1,1,nPatch(3));
%{
\end{matlab}
\paragraph{Pre-compute weights for macro-periodic} In the
case of macro-periodicity, precompute the weightings to
interpolate field values for coupling. \todo{Might sometime
extend to coupling via derivative values.}
\begin{matlab}
%}
if patches.periodic
ratio = reshape(ratio,1,3); % force to be row vector
patches.ratio = ratio;
if ordCC>0
[Cwtsr,Cwtsl] = patchCwts(ratio,ordCC,patches.stag);
patches.Cwtsr = Cwtsr; patches.Cwtsl = Cwtsl;
end%if
end%if patches.periodic
%{
\end{matlab}
\subsection{Set ensemble inter-patch communication}
For \verb|EdgyInt| or centre interpolation respectively,
\begin{itemize}
\item the right-face\slash centre realisations
\verb|1:nEnsem| are to interpolate to left-face~\verb|le|,
and
\item the left-face\slash centre realisations
\verb|1:nEnsem| are to interpolate to~\verb|re|.
\end{itemize}
\verb|re| and \verb|li| are `transposes' of each other as
\verb|re(li)=le(ri)| are both \verb|1:nEnsem|. Similarly for
bottom-face\slash centre interpolation to top-face
via~\verb|to|, top-face\slash centre interpolation to
bottom-face via~\verb|bo|, back-face\slash centre
interpolation to front-face via~\verb|fr|, and
front-face\slash centre interpolation to back-face
via~\verb|ba|.
The default is nothing shifty. This setting reduces the
number of if-statements in function \verb|patchEdgeInt3()|.
\begin{matlab}
%}
nE = patches.nEnsem;
patches.le = 1:nE; patches.ri = 1:nE;
patches.bo = 1:nE; patches.to = 1:nE;
patches.ba = 1:nE; patches.fr = 1:nE;
%{
\end{matlab}
However, if heterogeneous coefficients are supplied via
\verb|hetCoeffs|, then do some non-trivial replications.
First, get microscale periods, patch size, and replicate
many times in order to subsequently sub-sample: \verb|nSubP|
times should be enough. If \verb|cs| is more then 4D, then
the higher-dimensions are reshaped into the 4th dimension.
\begin{matlab}
%}
if ~isempty(cs)
[mx,my,mz,nc] = size(cs);
nx = nSubP(1); ny = nSubP(2); nz = nSubP(3);
cs = repmat(cs,nSubP);
%{
\end{matlab}
If only one member of the ensemble is required, then
sub-sample to patch size, and store coefficients in
\verb|patches| as is.
\begin{matlab}
%}
if nE==1, patches.cs = cs(1:nx-1,1:ny-1,1:nz-1,:); else
%{
\end{matlab}
But for $\verb|nEnsem|>1$ an ensemble of
$m_xm_ym_z$~phase-shifts of the coefficients is
constructed from the over-supply. Here code phase-shifts
over the periods---the phase shifts are like
Hankel-matrices.
\begin{matlab}
%}
patches.nEnsem = mx*my*mz;
patches.cs = nan(nx-1,ny-1,nz-1,nc,mx,my,mz);
for k = 1:mz
ks = (k:k+nz-2);
for j = 1:my
js = (j:j+ny-2);
for i = 1:mx
is = (i:i+nx-2);
patches.cs(:,:,:,:,i,j,k) = cs(is,js,ks,:);
end
end
end
patches.cs = reshape(patches.cs,nx-1,ny-1,nz-1,nc,[]);
%{
\end{matlab}
Further, set a cunning left\slash right\slash bottom\slash
top\slash front\slash back realisation of inter-patch
coupling. The aim is to preserve symmetry in the system
when also invoking \verb|EdgyInt|. What this coupling does
without \verb|EdgyInt| is unknown. Use auto-replication.
\begin{matlab}
%}
mmx=(0:mx-1)'; mmy=0:my-1; mmz=shiftdim(0:mz-1,-1);
le = mod(mmx+mod(nx-2,mx),mx)+1;
patches.le = reshape( le+mx*(mmy+my*mmz) ,[],1);
ri = mod(mmx-mod(nx-2,mx),mx)+1;
patches.ri = reshape( ri+mx*(mmy+my*mmz) ,[],1);
bo = mod(mmy+mod(ny-2,my),my)+1;
patches.bo = reshape( 1+mmx+mx*(bo-1+my*mmz) ,[],1);
to = mod(mmy-mod(ny-2,my),my)+1;
patches.to = reshape( 1+mmx+mx*(to-1+my*mmz) ,[],1);
ba = mod(mmz+mod(nz-2,mz),mz)+1;
patches.ba = reshape( 1+mmx+mx*(mmy+my*(ba-1)) ,[],1);
fr = mod(mmz-mod(nz-2,mz),mz)+1;
patches.fr = reshape( 1+mmx+mx*(mmy+my*(fr-1)) ,[],1);
%{
\end{matlab}
Issue warning if the ensemble is likely to be affected by
lack of scale separation. \todo{Need to justify this and
the arbitrary threshold more carefully??}
\begin{matlab}
%}
if prod(ratio)*patches.nEnsem>0.9, warning( ...
'Probably poor scale separation in ensemble of coupled phase-shifts')
scaleSeparationParameter = ratio*patches.nEnsem
end
%{
\end{matlab}
End the two if-statements.
\begin{matlab}
%}
end%if-else nEnsem>1
end%if not-empty(cs)
%{
\end{matlab}
\paragraph{If parallel code} then first assume this is not
within an \verb|spmd|-environment, and so we invoke
\verb|spmd...end| (which starts a parallel pool if not
already started). At this point, the global \verb|patches|
is copied for each worker processor and so it becomes
\emph{composite} when we distribute any one of the fields.
Hereafter, {\em all fields in the global variable
\verb|patches| must only be referenced within an
\verb|spmd|-environment.}%
\footnote{If subsequently outside spmd, then one must use
functions like \texttt{getfield(patches\{1\},'a')}.}
\begin{matlab}
%}
if patches.parallel
spmd
%{
\end{matlab}
Second, decide which dimension is to be sliced among
parallel workers (for the moment, do not consider slicing
the ensemble). Choose the direction of most patches, biased
towards the last.
\begin{matlab}
%}
[~,pari]=max(nPatch+0.01*(1:3));
patches.codist=codistributor1d(5+pari);
%{
\end{matlab}
\verb|patches.codist.Dimension| is the index that is split
among workers. Then distribute the appropriate coordinate
direction among the workers: the function must be invoked
inside an \verb|spmd|-group in order for this to work---so
we do not need \verb|parallel| in argument list.
\begin{matlab}
%}
switch pari
case 1, patches.x=codistributed(patches.x,patches.codist);
case 2, patches.y=codistributed(patches.y,patches.codist);
case 3, patches.z=codistributed(patches.z,patches.codist);
otherwise
error('should never have bad index for parallel distribution')
end%switch
end%spmd
%{
\end{matlab}
If not parallel, then clean out \verb|patches.codist| if it exists.
May not need, but safer.
\begin{matlab}
%}
else% not parallel
if isfield(patches,'codist'), rmfield(patches,'codist'); end
end%if-parallel
%{
\end{matlab}
\paragraph{Fin}
\begin{matlab}
%}
end% function
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
monoscaleDiffEquil2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/monoscaleDiffEquil2.m
| 6,300 |
utf_8
|
b5bff0521417654313c3c19b2d649993
|
% Solve for steady state of monoscale heterogeneous
% diffusion in 2D on patches as an example application, from
% section 5.2 of Freese, 2211.13731. AJR, 31 Jan 2023
%!TEX root = doc.tex
%{
\section{\texttt{monoscaleDiffEquil2}: equilibrium of a 2D
monoscale heterogeneous diffusion via small patches}
\label{sec:monoscaleDiffEquil2}
Here we find the steady state~\(u(x,y)\), see
\cref{fig:monoscaleDiffEquil2}, to the heterogeneous \pde
(inspired by Freese et al.\footnote{ \protect
\url{http://arxiv.org/abs/2211.13731}} \S5.2)
\begin{equation*}
u_t=A(x,y)\grad\grad u-f,
\end{equation*}
on domain \([-1,1]^2\) with Dirichlet BCs, for coefficient
pseudo-diffusion matrix
\begin{equation*}
A:=\begin{bmatrix} 2& a\\a & 2 \end{bmatrix}
\quad \text{with } a:=\sign(xy)
\text{ or }a:=\sin(\pi x)\sin(\pi y),
\end{equation*}
and for forcing~\(f(x,y)\) such that the exact equilibrium
is \(u = x\big(1-e^{1-|x|}\big) y \big(1-e^{1-|y|}\big)\).
But for simplicity, let's obtain \(u = x(1-x^2) y(1-y^2)\)
for which we code~\(f\) later---as determined by this Reduce
algebra code.
\begin{figure}
\centering\begin{tabular}{@{}c@{\ }c@{}}
\parbox[t]{10em}{\caption{\label{fig:monoscaleDiffEquil2}%
Equilibrium of the macroscale diffusion problem of Freese
with Dirichlet zero-value boundary conditions
(\cref{sec:monoscaleDiffEquil2}). The patch size is not
small so we can see the patches.}} &
\def\extraAxisOptions{label shift={-1.5ex}}
\raisebox{-\height}{\input{Figs/monoscaleDiffEquil2}}
\end{tabular}
\end{figure}
%let { df(sign(~x),~x)=>0
% , df(abs(~x),~x)=>sign(x)
% , abs(~x)^2=>abs(x), sign(~x)^2=>1 };
%u:=x*(1-exp(1-abs(x)))*y*(1-exp(1-abs(y)));
\begin{verbatim}
on gcd; factor sin;
u:=x*(1-x^2)*y*(1-y^2);
a:=sin(pi*x)*sin(pi*y);
f:=2*df(u,x,x)+2*a*df(u,x,y)+2*df(u,y,y);
\end{verbatim}
Clear, and initiate globals.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plot
%{
\end{matlab}
\paragraph{Patch configuration} Initially use \(7\times7\)
patches in the square \((-1,1)^2\). For continuous forcing
we may have small patches of any reasonable microgrid
spacing---here the microgrid error dominates.
\begin{matlab}
%}
nPatch = 7
nSubP = 5
dx = 0.03
%{
\end{matlab}
Specify some order of interpolation.
\begin{matlab}
%}
configPatches2(@monoscaleDiffForce2,[-1 1 -1 1],'equispace' ...
,nPatch ,4 ,dx ,nSubP ,'EdgyInt',true );
%{
\end{matlab}
Compute the time-constant coefficient and time-constant
forcing, and store them in struct \verb|patches| for access
by the microcode of \cref{sec:monoscaleDiffForce2}.
\begin{matlab}
%}
x=patches.x; y=patches.y;
patches.A = sin(pi*x).*sin(pi*y);
patches.fu = ...
+2*patches.A.*(9*x.^2.*y.^2-3*x.^2-3*y.^2+1) ...
+12*x.*y.*(x.^2+y.^2-2);
%{
\end{matlab}
By construction, the \pde\ has analytic solution
\begin{matlab}
%}
uAnal = x.*(1-x.^2).*y.*(1-y.^2);
%{
\end{matlab}
\paragraph{Solve for steady state} Set initial guess of
zero, with \verb|NaN| to indicate patch-edge values.
Index~\verb|i| are the indices of patch-interior points, and
the number of unknowns is then its length.
\begin{matlab}
%}
u0 = zeros(nSubP,nSubP,1,1,nPatch,nPatch);
u0([1 end],:,:) = nan; u0(:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
Solve by iteration. Use \verb|fsolve| for simplicity and
robustness (using \verb|optimoptions| to omit its trace
information), and give magnitudes.
\begin{matlab}
%}
tic;
uSoln = fsolve(@theRes,u0(patches.i) ...
,optimoptions('fsolve','Display','off'));
solnTime = toc
normResidual = norm(theRes(uSoln))
normSoln = norm(uSoln)
normError = norm(uSoln-uAnal(patches.i))
%{
\end{matlab}
Store the solution vector into the patches, and interpolate,
but have not bothered to set boundary values so they stay
NaN from the interpolation.
\begin{matlab}
%}
u0(patches.i) = uSoln;
u0 = patchEdgeInt2(u0);
%{
\end{matlab}
\paragraph{Draw solution profile} Separate patches with
NaNs, then reshape arrays to suit 2D space surface plots.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*hsv)
x(end+1,:,:)=nan; u0(end+1,:,:)=nan;
y(:,end+1,:)=nan; u0(:,end+1,:)=nan;
u = reshape(permute(squeeze(u0),[1 3 2 4]), [numel(x) numel(y)]);
%{
\end{matlab}
Draw the patch solution surface, with boundary-values omitted as
already~\verb|NaN| by not bothering to set them.
\begin{matlab}
%}
mesh(x(:),y(:),u'); view(60,55)
xlabel('space $x$'), ylabel('space $y$'), zlabel('$u(x,y)$')
ifOurCf2tex(mfilename)%optionally save
%{
\end{matlab}
\subsection{\texttt{monoscaleDiffForce2()}: microscale
discretisation inside patches of forced diffusion PDE}
\label{sec:monoscaleDiffForce2}
This function codes the lattice heterogeneous diffusion of
the \pde\ inside the patches. For 6D input arrays~\verb|u|,
\verb|x|, and~\verb|y|, computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|.
\begin{matlab}
%}
function ut = monoscaleDiffForce2(t,u,patches)
dx = diff(patches.x(2:3)); % x space step
dy = diff(patches.y(2:3)); % y space step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
ut = nan+u; % preallocate output array
%{
\end{matlab}
Set Dirichlet boundary value of zero around the square
domain.
\begin{matlab}
%}
u( 1 ,:,:,:, 1 ,:)=0; % left edge of left patches
u(end,:,:,:,end,:)=0; % right edge of right patches
u(:, 1 ,:,:,:, 1 )=0; % bottom edge of bottom patches
u(:,end,:,:,:,end)=0; % top edge of top patches
%{
\end{matlab}
Or code some function variation around the boundary, such as
a function of~\(y\) on the left boundary, and a (constant)
function of~\(x\) at the top boundary.
\begin{matlab}
%}
if 0
u(1,:,:,:,1,:)=(1+patches.y)/2; % left edge of left patches
u(:,end,:,:,:,end)=1; % top edge of top patches
end%if
%{
\end{matlab}
Compute the time derivatives via stored forcing and
coefficients. Easier to code by conflating the last four
dimensions into the one~\verb|,:|.
\begin{matlab}
%}
ut(i,j,:) ...
= 2*diff(u(:,j,:),2,1)/dx^2 +2*diff(u(i,:,:),2,2)/dy^2 ...
+2*patches.A(i,j,:).*( u(i+1,j+1,:) -u(i-1,j+1,:) ...
-u(i+1,j-1,:) +u(i-1,j-1,:) )/(4*dx*dy) ...
-patches.fu(i,j,:);
end%function monoscaleDiffForce2
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
randAdvecDiffEquil2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/randAdvecDiffEquil2.m
| 6,862 |
utf_8
|
8ec5f7b765db0f9321d4903f46912f15
|
% Solve for steady state of two-scale heterogeneous
% diffusion in 2D on patches as an example application
% involving Neumann boundary conditions, from section 6.2 of
% Bonizzoni, 2211.15221. AJR, 1 Feb 2023
%!TEX root = doc.tex
%{
\section{\texttt{randAdvecDiffEquil2}: equilibrium of a 2D
random heterogeneous advection-diffusion via small patches}
\label{sec:randAdvecDiffEquil2}
Here we find the steady state~\(u(x,y)\) of the
heterogeneous \pde\ (inspired by Bonizzoni et al.\footnote{
\protect \url{http://arxiv.org/abs/2211.15221}} \S6.2)
\begin{equation*}
u_t=\mu_1\delsq u -(\cos\mu_2,\sin\mu_2)\cdot\grad u -u +f\,,
\end{equation*}
on domain \([0,1]^2\) with Neumann boundary conditions, for
microscale random pseudo-diffusion and pseudo-advection
coefficients, \(\mu_1(x,y)\in[0.01,0.1]\)\footnote{More
interesting microscale structure arises here for~\(\mu_1\) a
factor of three smaller.} and \(\mu_2(x,y)\in[0,2\pi)\), and
for forcing
\begin{equation*}
f(x,y):=\exp\left[-\frac{(x-\mu_3)^2+(y-\mu_4)^2}{\mu_5^2}\right],
\end{equation*}
smoothly varying in space for fixed \(\mu_3, \mu_4 \in
[0.25,0.75]\) and \(\mu_5 \in [0.1,0.25]\). The above
system is dominantly diffusive for lengths scales
\(\ell<0.01 = \min\mu_1\). Due to the randomness, we get
different solutions each execution of this code.
\cref{fig:randAdvecDiffEquil2} plots one example. A
physical interpretation of the solution field is confounded
because the problem is pseudo-advection-diffusion due to the
varying coefficients being outside the \(\grad\)~operator.
\begin{figure}
\centering\caption{\label{fig:randAdvecDiffEquil2}%
Equilibrium of the macroscale diffusion problem of Bonizzoni
et al.\ with Neumann boundary conditions of zero
(\cref{sec:randAdvecDiffEquil2}). Here the patches have a
equispaced spatial distribution. The microscale periodicity,
and hence the patch size, is chosen large enough to see
within.}
\includegraphics[scale=0.8]{Figs/randAdvecDiffEquil2}
\end{figure}
Clear, and initiate globals.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plot
%{
\end{matlab}
First establish the microscale heterogeneity has
micro-period \verb|mPeriod| on the spatial lattice. Then
\verb|configPatches2| replicates the heterogeneity to fill
each patch.
\begin{matlab}
%}
mPeriod = 4
mu1 = 0.01*10.^rand(mPeriod)
mu2 = 2*pi*rand(mPeriod)
cs = cat(3,mu1,cos(mu2),sin(mu2));
meanDiffAdvec=squeeze(mean(mean(cs)))
%{
\end{matlab}
Set the periodicity~\(\epsilon\), here big enough so we can
see the patches, and other microscale parameters.
\begin{matlab}
%}
epsilon = 0.04
dx = epsilon/mPeriod
nPeriodsPatch = 1 % any integer
nSubP = nPeriodsPatch*mPeriod+2 % for edgy int
%{
\end{matlab}
\paragraph{Patch configuration}
Say use \(7\times7\) patches in \((0,1)^2\), fourth order
interpolation, either `equispace' or `chebyshev', and the
offset for Neumann boundary conditions:
\begin{matlab}
%}
nPatch = 7
Dom.type= 'equispace';
Dom.bcOffset = 0.5;
configPatches2(@randAdvecDiffForce2,[0 1],Dom ...
,nPatch ,4 ,dx ,nSubP ,'EdgyInt',true ,'hetCoeffs',cs );
%{
\end{matlab}
Compute the time-constant forcing, and store in struct
\verb|patches| for access by the microcode of
\cref{sec:randAdvecDiffForce2}.
\begin{matlab}
%}
mu = [ 0.25+0.5*rand(1,2) 0.1+0.15*rand ]
patches.fu = exp(-((patches.x-mu(1)).^2 ...
+(patches.y-mu(2)).^2)/mu(3)^2);
%{
\end{matlab}
\paragraph{Solve for steady state}
Set initial guess of zero, with \verb|NaN| to indicate
patch-edge values. Index~\verb|i| are the indices of
patch-interior points, store in global patches for access by
\verb|theRes|, and the number of unknowns is then its
number of elements.
\begin{matlab}
%}
u0 = zeros(nSubP,nSubP,1,1,nPatch,nPatch);
u0([1 end],:,:) = nan; u0(:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
Solve by iteration. Use \verb|fsolve| for simplicity and
robustness (and using \verb|optimoptions| to omit trace
information), via the generic patch system wrapper
\verb|theRes| (\cref{sec:theRes}).
\begin{matlab}
%}
tic;
uSoln = fsolve(@theRes,u0(patches.i) ...
,optimoptions('fsolve','Display','off'));
solnTime = toc
normResidual = norm(theRes(uSoln))
normSoln = norm(uSoln)
%{
\end{matlab}
Store the solution vector into the patches, and interpolate,
but have not bothered to set boundary values so they stay
NaN from the interpolation.
\begin{matlab}
%}
u0(patches.i) = uSoln;
u0 = patchEdgeInt2(u0);
%{
\end{matlab}
\paragraph{Draw solution profile} Separate patches with
NaNs, then reshape arrays to suit 2D space surface plots.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*hsv)
patches.x(end+1,:,:)=nan; u0(end+1,:,:)=nan;
patches.y(:,end+1,:)=nan; u0(:,end+1,:)=nan;
u = reshape(permute(squeeze(u0),[1 3 2 4]) ...
, [numel(patches.x) numel(patches.y)]);
%{
\end{matlab}
Draw the patch solution surface, with boundary-values
omitted as already~\verb|NaN| by not bothering to set them.
\begin{matlab}
%}
mesh(patches.x(:),patches.y(:),u'); view(60,55)
xlabel('space $x$'), ylabel('space $y$'), zlabel('$u(x,y)$')
ifOurCf2eps(mfilename) %optionally save plot
%{
\end{matlab}
\subsection{\texttt{randAdvecDiffForce2()}: microscale
discretisation inside patches of forced diffusion PDE}
\label{sec:randAdvecDiffForce2}
This function codes the lattice heterogeneous diffusion of
the \pde\ inside the patches. For 6D input arrays~\verb|u|,
\verb|x|, and~\verb|y|, computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|.
\begin{matlab}
%}
function ut = randAdvecDiffForce2(t,u,patches)
dx = diff(patches.x(2:3)); % x space step
dy = diff(patches.y(2:3)); % y space step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
ut = nan+u; % preallocate output array
%{
\end{matlab}
Set Neumann boundary condition of zero derivative around the
square domain: that is, the edge value equals the
next-to-edge value.
\begin{matlab}
%}
u( 1 ,:,:,:, 1 ,:)=u( 2 ,:,:,:, 1 ,:); % left edge of left patches
u(end,:,:,:,end,:)=u(end-1,:,:,:,end,:); % right edge of right patches
u(:, 1 ,:,:,:, 1 )=u(:, 2 ,:,:,:, 1 ); % bottom edge of bottom patches
u(:,end,:,:,:,end)=u(:,end-1,:,:,:,end); % top edge of top patches
%{
\end{matlab}
Compute the time derivatives via stored forcing and
coefficients. Easier to code by conflating the last four
dimensions into the one~\verb|,:|.
\begin{matlab}
%}
ut(i,j,:) ...
= patches.cs(i,j,1).*(diff(u(:,j,:),2,1)/dx^2 ...
+diff(u(i,:,:),2,2)/dy^2)...
-patches.cs(i,j,2).*(u(i+1,j,:)-u(i-1,j,:))/(2*dx) ...
-patches.cs(i,j,3).*(u(i,j+1,:)-u(i,j-1,:))/(2*dy) ...
-u(i,j,:) +patches.fu(i,j,:);
end%function randAdvecDiffForce2
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
twoscaleDiffEquil2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/twoscaleDiffEquil2.m
| 5,848 |
utf_8
|
b5a2f015f12f802529041681a6493474
|
% Solve for steady state of twoscale heterogeneous diffusion
% in 2D on patches as an example application, from section
% 5.3.1 of Freese, 2211.13731. AJR, 31 Jan 2023
%!TEX root = doc.tex
%{
\section{\texttt{twoscaleDiffEquil2}: equilibrium of a 2D
twoscale heterogeneous diffusion via small patches}
\label{sec:twoscaleDiffEquil2}
Here we find the steady state~\(u(x,y)\) to the
heterogeneous \pde\ (inspired by Freese et al.\footnote{
\protect \url{http://arxiv.org/abs/2211.13731}} \S5.3.1)
\begin{equation*}
u_t=A(x,y)\grad\grad u-f,
\end{equation*}
on domain \([-1,1]^2\) with Dirichlet BCs, for coefficient
`diffusion' matrix, varying with period~\(2\epsilon\) on the
microscale \(\epsilon=2^{-7}\), of
\begin{equation*}
A:=\begin{bmatrix} 2& a\\a & 2 \end{bmatrix}
\quad \text{with } a:=\sin(\pi x/\epsilon)\sin(\pi y/\epsilon),
\end{equation*}
and for forcing \(f:=(x+\cos3\pi x)y^3\).
\begin{figure}
\centering\begin{tabular}{@{}c@{\ }c@{}}
\parbox[t]{10em}{\caption{\label{fig:twoscaleDiffEquil2}%
Equilibrium of the multiscale diffusion problem of Freese
with Dirichlet zero-value boundary conditions
(\cref{sec:twoscaleDiffEquil2}). The patch size is not
small so we can see the patches and the sub-patch grid. The
solution~\(u(x,y)\) is boringly smooth.}} &
\def\extraAxisOptions{label shift={-1.5ex}}
\raisebox{-\height}{\input{Figs/twoscaleDiffEquil2}}
\end{tabular}
\end{figure}
Clear, and initiate globals.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plot
%{
\end{matlab}
First establish the microscale heterogeneity has
micro-period \verb|mPeriod| on the spatial lattice. Set the
phase of the heterogeneity so that each patch centre is a
point of symmetry of the diffusivity. Then
\verb|configPatches2| replicates the heterogeneity to fill
each patch.
\begin{matlab}
%}
mPeriod = 6
z = (0.5:mPeriod)'/mPeriod;
A = sin(2*pi*z).*sin(2*pi*z');
%{
\end{matlab}
Set the periodicity, via~\(\epsilon\), and other microscale
parameters.
\begin{matlab}
%}
nPeriodsPatch = 1 % any integer
epsilon = 2^(-6) % 4 or 5 to see the patches
dx = (2*epsilon)/mPeriod
nSubP = nPeriodsPatch*mPeriod+2 % for edgy int
%{
\end{matlab}
\paragraph{Patch configuration}
Say use \(7\times7\) patches in \((-1,1)^2\), fourth order
interpolation, and either `equispace' or `chebyshev':
\begin{matlab}
%}
nPatch = 7
configPatches2(@twoscaleDiffForce2,[-1 1],'equispace' ...
,nPatch ,4 ,dx ,nSubP ,'EdgyInt',true ,'hetCoeffs',A );
%{
\end{matlab}
Compute the time-constant forcing, and store in struct
\verb|patches| for access by the microcode of
\cref{sec:twoscaleDiffForce2}.
\begin{matlab}
%}
x = patches.x; y = patches.y;
patches.fu = 100*(x+cos(3*pi*x)).*y.^3;
%{
\end{matlab}
\paragraph{Solve for steady state}
Set initial guess of zero, with \verb|NaN| to indicate
patch-edge values. Index~\verb|i| are the indices of
patch-interior points, and the number of unknowns is then
its length.
\begin{matlab}
%}
u0 = zeros(nSubP,nSubP,1,1,nPatch,nPatch);
u0([1 end],:,:) = nan; u0(:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
Solve by iteration. Use \verb|fsolve| for simplicity and
robustness (and using \verb|optimoptions| to omit trace
information), via the generic patch system wrapper
\verb|theRes| (\cref{sec:theRes}), and give magnitudes.
\begin{matlab}
%}
tic;
uSoln = fsolve(@theRes,u0(patches.i) ...
,optimoptions('fsolve','Display','off'));
solveTime = toc
normResidual = norm(theRes(uSoln))
normSoln = norm(uSoln)
%{
\end{matlab}
Store the solution vector into the patches, and interpolate,
but have not bothered to set boundary values so they stay
NaN from the interpolation.
\begin{matlab}
%}
u0(patches.i) = uSoln;
u0 = patchEdgeInt2(u0);
%{
\end{matlab}
\paragraph{Draw solution profile} Separate patches with
NaNs, then reshape arrays to suit 2D space surface plots.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*hsv)
x(end+1,:,:)=nan; u0(end+1,:,:)=nan;
y(:,end+1,:)=nan; u0(:,end+1,:)=nan;
u = reshape(permute(squeeze(u0),[1 3 2 4]), [numel(x) numel(y)]);
%{
\end{matlab}
Draw the patch solution surface, with boundary-values omitted as
already~\verb|NaN| by not bothering to set them.
\begin{matlab}
%}
mesh(x(:),y(:),u'); view(60,55)
xlabel('space $x$'), ylabel('space $y$'), zlabel('$u(x,y)$')
ifOurCf2tex(mfilename)%optionally save
%{
\end{matlab}
\subsection{\texttt{twoscaleDiffForce2()}: microscale
discretisation inside patches of forced diffusion PDE}
\label{sec:twoscaleDiffForce2}
This function codes the lattice heterogeneous diffusion of
the \pde\ inside the patches. For 6D input arrays~\verb|u|,
\verb|x|, and~\verb|y|, computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|.
\begin{matlab}
%}
function ut = twoscaleDiffForce2(t,u,patches)
dx = diff(patches.x(2:3)); % x space step
dy = diff(patches.y(2:3)); % y space step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
ut = nan+u; % preallocate output array
%{
\end{matlab}
Set Dirichlet boundary value of zero around the square
domain.
\begin{matlab}
%}
u( 1 ,:,:,:, 1 ,:)=0; % left edge of left patches
u(end,:,:,:,end,:)=0; % right edge of right patches
u(:, 1 ,:,:,:, 1 )=0; % bottom edge of bottom patches
u(:,end,:,:,:,end)=0; % top edge of top patches
%{
\end{matlab}
Compute the time derivatives via stored forcing and
coefficients. Easier to code by conflating the last four
dimensions into the one~\verb|,:|.
\begin{matlab}
%}
ut(i,j,:) ...
= 2*diff(u(:,j,:),2,1)/dx^2 +2*diff(u(i,:,:),2,2)/dy^2 ...
+2*patches.cs(i,j).*( u(i+1,j+1,:) -u(i-1,j+1,:) ...
-u(i+1,j-1,:) +u(i-1,j-1,:) )/(4*dx*dy) ...
-patches.fu(i,j,:);
end%function twoscaleDiffForce2
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchSys1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/BCs/patchSys1.m
| 3,474 |
utf_8
|
255dbcfbe2dcb47cbf775fe5a41f94bd
|
% patchSys1() provides an interface to time integrators
% for the dynamics on patches coupled across space. The
% system must be a smooth lattice system such as PDE
% discretisations. AJR, Nov 2017 -- Feb 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchSys1()}: interface 1D space to time integrators}
\label{sec:patchSys1}
To simulate in time with 1D spatial patches we often need to
interface a user's time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function provides an interface. It mostly assumes that
the sub-patch structure is \emph{smooth enough} so that the
patch centre-values are sensible macroscale variables, and
patch edge values are determined by macroscale interpolation
of the patch-centre or edge values. Nonetheless, microscale
heterogeneous systems may be accurately simulated with this
function via appropriate interpolation. Communicate
patch-design variables (\cref{sec:configPatches1}) either
via the global struct~\verb|patches| or via an optional
third argument (except that this last is required for
parallel computing of \verb|spmd|).
\begin{matlab}
%}
function dudt=patchSys1(t,u,patches,varargin)
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|nSubP| \cdot \verb|nVars| \cdot \verb|nEnsem| \cdot
\verb|nPatch|$ where there are $\verb|nVars| \cdot
\verb|nEnsem|$ field values at each of the points in the
$\verb|nSubP|\times \verb|nPatch|$ grid.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches1()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| that computes the time derivatives
on the patchy lattice. The array~\verb|u| has size
$\verb|nSubP| \times \verb|nVars| \times \verb|nEnsem|
\times \verb|nPatch|$. Time derivatives should be computed
into the same sized array, then herein the patch edge
values are overwritten by zeros.
\item \verb|.x| is $\verb|nSubP| \times1 \times1 \times
\verb|nPatch|$ array of the spatial locations~$x_{i}$ of
the microscale grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on the microscale.
\end{itemize}
\item \verb|varargin| is arbitrary number of parameters to
be passed onto the users time-derivative function as
specified in configPatches1.
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector\slash array of of time
derivatives, but with patch edge-values set to zero. It is
of total length $\verb|nSubP| \cdot \verb|nVars| \cdot
\verb|nEnsem| \cdot \verb|nPatch|$ and the same dimensions
as~\verb|u|.
\end{itemize}
\begin{devMan}
Reshape the fields~\verb|u| as a 4D-array, and sets the edge
values from macroscale interpolation of centre-patch values.
\cref{sec:patchEdgeInt1} describes \verb|patchEdgeInt1()|.
\begin{matlab}
%}
sizeu = size(u);
u = patchEdgeInt1(u,patches);
%{
\end{matlab}
Ask the user function for the time derivatives computed in
the array, overwrite its edge values with the dummy value of
zero (as \verb|ode15s| chokes on NaNs), then return to the
user\slash integrator as same sized array as input.
\begin{matlab}
%}
dudt=patches.fun(t,u,patches,varargin{:});
dudt([1 end],:,:,:) = 0;
dudt=reshape(dudt,sizeu);
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
projIntDMDExample1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/ProjIntDMD/projIntDMDExample1.m
| 2,643 |
utf_8
|
cea35b451ac65ded69b367b6fb56ea1a
|
% Example of the time integration function projIntDMD()
% on discretisation of nonlinear diffusion PDE.
% AJR, Oct 2017
%!TEX root = doc.tex
%{
\section{\texttt{projIntDMDExample1}: A first test of basic
projective integration}
\label{sec:ftbpi}
\localtableofcontents
Seek to simulate the nonlinear diffusion \pde\
\begin{equation*}
\D tu=u\DD xu\quad \text{such that }u(\pm 1)=0,
\end{equation*}
with random positive initial condition. \cref{fig:pit1u}
shows solutions are attracted to the parabolic
\(u=a(t)(1-x^2)\) with slow algebraic decay \(\dot
a=-2a^2\).
\begin{figure}\centering
\caption{\label{fig:pit1u}field \(u(x,t)\) tests basic
projective integration.}
\includegraphics[width=\linewidth]{pi1Example1u9}
\end{figure}
Set the number of interior points in the domain~\([-1,1]\),
and the macroscale time-step.
\begin{matlab}
%}
%function projIntDMDExample1
n=19
ts=0:1:6
%{
\end{matlab}
Set the initial condition to parabola or some skewed random
positive values.
\begin{matlab}
%}
x=linspace(-1,1,n+2)';
%u0=(1-x.^2).*(1+1e-9*randn(n+2,1));
u0=rand(n+2,1).*(1-x.^2);
%{
\end{matlab}
Projectively integrate in time with: rank-two DMD
projection; guessed microscale time-step but chosen so an
integral number of micro-steps fits into a macro-step for
comparison; and guessed transient time~\(0.4\) and
\(7\)~micro-steps `on the slow manifold'.
\begin{matlab}
%}
dt=2/n^2
[us,uss,tss]=projIntDMD(@dudt,u0,ts,2,dt,[0.5 4*dt]);
%{
\end{matlab}
Plot the macroscale predictions to draw \cref{fig:pit1u}.
\begin{matlab}
%}
clf,plot(x,us,'o-')
xlabel('space x'),ylabel('u(x,t)')
%matlab2tikz('pi1Example1u.ltx','noSize',true)
%print('-depsc2',['pi1Example1u' num2str(n)])
%{
\end{matlab}
Also plot a surface of the microscale bursts as shown in
\cref{fig:pit1micro}.
\begin{figure}\centering
\caption{\label{fig:pit1micro}field \(u(x,t)\) during each
of the microscale bursts used in the projective
integration.}
\includegraphics[width=\linewidth]{pi1Example1micro9}
\end{figure}
\begin{matlab}
%}
%tss(end)=nan;% omit the last time point
clf,mesh(tss,x,uss)%,'EdgeColor','none')
ylabel('space x'),xlabel('time t'),zlabel('u(x,t)')
view([40 30])
%print('-depsc2',['pi1Example1micro' num2str(n)])
%{
\end{matlab}
End the main function (not needed for new enough Matlab).
\begin{matlab}
%}
%end
%{
\end{matlab}
\paragraph{The nonlinear PDE discretisation}
Code the simple centred difference discretisation of the
nonlinear diffusion \pde\ with constant (usually zero)
boundary values.
\begin{matlab}
%}
function ut=dudt(t,u)
n=length(u);
dx=2/(n-1);
j=2:n-1;
ut=[0
u(j).*(u(j+1)-2*u(j)+u(j-1))/dx^2
0];
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
projIntDMDExplore2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/ProjIntDMD/projIntDMDExplore2.m
| 2,944 |
utf_8
|
78117aa55dce93ef25d0520f2fbaf9d3
|
% Explore the time integration function projIntDMD()
% on discretisation of a nonlinear diffusion PDE.
% Test dependence of errors on macro-time-step.
% AJR, Feb 2018
%!TEX root = doc.tex
%{
\section{\texttt{projIntDMDExplore2}: explore effect of varying parameters}
\label{sec:pi1eevp}
\localtableofcontents
Seek to simulate the nonlinear diffusion \pde\
\begin{equation*}
\D tu=u\DD xu\quad \text{such that }u(\pm 1)=0,
\end{equation*}
with random positive initial condition.
Set the number of interior points in the domain~\([-1,1]\), and the macroscale time-step.
\begin{matlab}
%}
function projIntDMDExplore2
n=9
dt=2/n^2
ICNoise=0
%{
\end{matlab}
Set micro-simulation parameters.
Rank two is fine when starting on the slow manifold.
Choose middle of the road transient and analysed time.
\begin{matlab}
%}
rank=2
timeSteps=[0.2 0.2]
%{
\end{matlab}
Try integrating with macro time-steps up to this sort of magnitude.
\begin{matlab}
%}
Ttot=9
%{
\end{matlab}
Set the initial condition to parabola or some skewed random positive values.
Without noise this initial condition is already on the slow manifold so only little reason for transient time.
\begin{matlab}
%}
x=linspace(-1,1,n+2)';
u0=(0.5+ICNoise*rand(n+2,1)).*(1-x.^2);
%{
\end{matlab}
First find a reference solution of the microscale dynamics over all time, here stored in \verb|Uss|.
\begin{matlab}
%}
[Us,Uss,Tss]=projIntDMD(@dudt,u0,[0 Ttot],2,dt,[0 Ttot]);
%{
\end{matlab}
Projectively integrate two steps in time with various parameters.
But remember that \verb|projIntDMD| rounds \verb|timeSteps| etc to nearest multiple of~\verb|dt|, so some of the following is a little dodgy but should not matter for overall trend.
\begin{matlab}
%}
Dts=0.1*[1 2 4 6 10 16 26]
errs=[]; relerrs=[]; DTs=[];
for p=Dts
[~,j]=min(abs(sum(timeSteps)+p-Tss))
ts=Tss(j)*(0:2)
js=1+(j-1)*(0:2);
[us,uss,tss]=projIntDMD(@dudt,u0,ts,rank,dt,timeSteps);
%{
\end{matlab}
Plot the macroscale predictions
\begin{matlab}
%}
if 1
clf,plot(x,Uss(:,js),'o-',x,us,'x--')
xlabel('space x'),ylabel('u(x,t)')
pause(0.01)
end
%{
\end{matlab}
Accumulate errors as function of time.
\begin{matlab}
%}
err=sqrt(sum((us-Uss(:,js)).^2))
errs=[errs;err];
relerrs=[relerrs;err./sqrt(sum(Uss(:,js).^2))];
%{
\end{matlab}
End the loop over parameters.
\begin{matlab}
%}
end
%{
\end{matlab}
Plot errors
\begin{matlab}
%}
loglog(Dts,errs(:,2:3),'o:')
xlabel('projective time-step')
ylabel('steps error')
legend('one','two')
grid
matlab2tikz('pi1x2.ltx')
%{
\end{matlab}
End the main function (not needed for new enough Matlab).
\begin{matlab}
%}
end
%{
\end{matlab}
\paragraph{The nonlinear PDE discretisation}
Code the simple centred difference discretisation of the nonlinear diffusion \pde\ with constant (usually zero) boundary values.
\begin{matlab}
%}
function ut=dudt(t,u)
n=length(u);
dx=2/(n-1);
j=2:n-1;
ut=[0
u(j).*(u(j+1)-2*u(j)+u(j-1))/dx^2
0];
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
projIntDMDPatches.m
|
.m
|
EquationFreeGit-master/SandpitPlay/ProjIntDMD/projIntDMDPatches.m
| 5,220 |
utf_8
|
dc589e422abbb92a08ec8450030743be
|
% Example of the time integration function projIntDMD()
% on a patch simulation of Burgers PDE.
% AJR, Oct 2017
%!TEX root = doc.tex
%{
\section{\texttt{projIntDMDPatches}: Projective integration of patch scheme}
\label{sec:pips}
\localtableofcontents
As an example of the use of projective integration, seek to simulate the nonlinear Burgers' \pde\
\begin{equation*}
\D tu+cu\D xu=\DD xu\quad \text{for $2\pi$-periodic }u,
\end{equation*}
for \(c=30\), and with various initial conditions.
Use a patch scheme \cite[]{Roberts06d} to only compute on part of space as shown in \autoref{fig:pit1psu}.
\begin{figure}
\centering
\caption{\label{fig:pit1psu}field \(u(x,t)\) tests basic projective integration of a basic patch scheme of Burgers' \pde, from randomly corrupted initial conditions.}
\includegraphics[width=\linewidth]{pi1PatchesU}
\end{figure}
Function header and variables needed by discrete patch scheme.
\begin{matlab}
%}
function projIntDMDPatches
global dx DX ratio j jp jm i I
%{
\end{matlab}
Set parameters of the patch scheme:
the number of patches;
number of micro-grid points within each patch;
the patch size to macroscale ratio.
\begin{matlab}
%}
nPatch=8
nSubP=11
ratio=0.1
%{
\end{matlab}
The points in the microscale, sub-patch, grid are indexed by~\verb|i|, and \verb|I| is the index of the mid-patch value used for coupling patches.
The macroscale patches are indexed by~\verb|j| and the neighbours by \verb|jp| and \verb|jm|.
\begin{matlab}
%}
i=2:nSubP-1; % microscopic internal points for PDE
I=round((nSubP+1)/2); % midpoint of each patch
j=1:nPatch; jp=mod(j,nPatch)+1; jm=mod(j-2,nPatch)+1; % patch index
%{
\end{matlab}
Make the spatial grid of patches centred at~\(X_j\) and of half-size \(h=r\Delta X\).
To suit Neumann boundary conditions on the patches make the micro-grid straddle the patch boundary by setting \(dx=2h/(n_\mu-2)\).
In order for the microscale simulation to be stable, we should have \(dt\ll dx^2\).
Then generate the microscale grid locations for all patches: \(x_{ij}\)~is the location of the \(i\)th~micro-point in the \(j\)th~patch.
\begin{matlab}
%}
X=linspace(0,2*pi,nPatch+1); X=X(j); % patch mid-points
DX=X(2)-X(1) % spacing of mid-patch points
dx=2*ratio*DX/(nSubP-2) % micro-grid size
dt=0.4*dx^2; % micro-time-step
x=bsxfun(@plus,dx*(-I+1:I-1)',X); % micro-grids
%{
\end{matlab}
Set the initial condition of a sine wave with random perturbations, surrounded with entries for boundary values of each patch.
\begin{matlab}
%}
u0=[nan(1,nPatch)
0.3*(1+sin(x(i,:)))+0.03*randn(size(x(i,:)))
nan(1,nPatch)];
%{
\end{matlab}
Set the desired macroscale time-steps over the time domain.
\begin{matlab}
%}
ts=linspace(0,0.45,10)
%{
\end{matlab}
Projectively integrate in time with:
\dmd\ projection of rank \(\verb|nPatch|+1\);
guessed microscale time-step~\verb|dt|; and
guessed numbers of transient and slow steps.
\begin{matlab}
%}
[us,uss,tss]=projIntDMD(@dudt,u0(:),ts,nPatch+1,dt,[20 nPatch*2]);
%{
\end{matlab}
Plot the macroscale predictions to draw \autoref{fig:pit1psu}, in groups of five in a plot.
\begin{matlab}
%}
figure(1),clf
k=length(ts); ls=nan(5,ceil(k/5)); ls(1:k)=1:k;
for k=1:size(ls,2)
subplot(size(ls,2),1,k)
plot(x(:),us(:,ls(:,k)),'.')
ylabel('u(x,t)')
legend(num2str(ts(ls(:,k))'))
end
xlabel('space x')
%matlab2tikz('pi1Test1u.ltx','noSize',true)
%print('-depsc2','pi1PatchesU')
%{
\end{matlab}
Also plot a surface of the microscale bursts as shown in \autoref{fig:piBurgersMicro}.
\begin{figure}
\centering
\caption{\label{fig:piBurgersMicro}stereo pair of the field \(u(x,t)\) during each of the microscale bursts used in the projective integration.}
\includegraphics[width=\linewidth]{pi1PatchesMicro}
\end{figure}
\begin{matlab}
%}
tss(end)=nan; %omit end time-point
figure(2),clf
for k=1:2, subplot(2,2,k)
surf(tss,x(:),uss,'EdgeColor','none')
ylabel('x'),xlabel('t'),zlabel('u(x,t)')
axis tight, view(121-4*k,45)
end
%print('-depsc2','pi1PatchesMicro')
%{
\end{matlab}
End the main function (not needed for new enough Matlab).
\begin{matlab}
%}
end
%{
\end{matlab}
\paragraph{Discretisation of Burgers PDE in coupled patches}
Code the simple centred difference discretisation of the nonlinear Burgers' \pde, \(2\pi\)-periodic in space.
\begin{matlab}
%}
function ut=dudt(t,u)
global dx DX ratio j jp jm i I
nPatch=j(end);
u=reshape(u,[],nPatch);
%{
\end{matlab}
Compute differences of the mid-patch values.
\begin{matlab}
%}
dmu=(u(I,jp)-u(I,jm))/2; % \mu\delta
ddu=(u(I,jp)-2*u(I,j)+u(I,jm)); % \delta^2
dddmu=dmu(jp)-2*dmu(j)+dmu(jm);
ddddu=ddu(jp)-2*ddu(j)+ddu(jm);
%{
\end{matlab}
Use these differences to interpolate fluxes on the patch boundaries and hence set the edge values on the patch \cite[]{Roberts06d}.
\begin{matlab}
%}
u(end,j)=u(end-1,j)+(dx/DX)*(dmu+ratio*ddu ...
-(dddmu*(1/6-ratio^2/2)+ddddu*ratio*(1/12-ratio^2/6)));
u(1,j)=u(2,j) -(dx/DX)*(dmu-ratio*ddu ...
-(dddmu*(1/6-ratio^2/2)-ddddu*ratio*(1/12-ratio^2/6)));
%{
\end{matlab}
Code Burgers' \pde\ in the interior of every patch.
\begin{matlab}
%}
ut=(u(i+1,j)-2*u(i,j)+u(i-1,j))/dx^2 ...
-30*u(i,j).*(u(i+1,j)-u(i-1,j))/(2*dx);
ut=reshape([nan(1,nPatch);ut;nan(1,nPatch)] ,[],1);
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
projIntDMD.m
|
.m
|
EquationFreeGit-master/SandpitPlay/ProjIntDMD/projIntDMD.m
| 9,508 |
utf_8
|
48b56d75182b6b1f3285402fa2864144
|
% projIntDMD() is a basic projective integration of a
% given system of stiff deterministic ODEs. AJR, Oct 2017
%!TEX root = doc.tex
%{
\section{\texttt{projIntDMD()}}
\label{sec:projIntDMD}
\localtableofcontents
This is a basic example of projective integration of a given
system of stiff deterministic \ode{}s via \dmd, the Dynamic
Mode Decomposition \cite[]{Kutz2016}.
\begin{matlab}
%}
function [xs,xss,tss]=projIntDMD(fun,x0,Ts,rank,dt,timeSteps)
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|fun()| is a function such as
\verb|dxdt=fun(t,x)| that computes the right-hand side of
the \ode\ \(d\xv/dt=\fv(t,\xv)\) where \xv~is a column
vector, say in \(\RR^n\) for \(n\geq1\)\,, \(t\)~is a
scalar, and the result~\fv\ is a column vector in~\(\RR^n\).
\item \verb|x0| is an \(n\)-vector of initial values at the
time \verb|ts(1)|. If any entries in~\verb|x0|
are~\verb|NaN|, then \verb|fun()| must cope, and only the
non-\verb|NaN| components are projected in time.
\item \verb|Ts| is a vector of times to compute the
approximate solution, say in~\(\RR^\ell\) for
\(\ell\geq2\)\,.
\item \verb|rank| is the rank of the \dmd\ extrapolation
over macroscale time-steps. Suspect \verb|rank| should be at
least one more than the effective number of slow variables.
\item \verb|dt| is the size of the microscale time-step.
Must be small enough so that RK2 integration of the \ode{}s
is stable.
\item \verb|timeSteps| is a two element vector:
\begin{itemize}
\item \verb|timeSteps(1)| is the time thought to be needed
for microscale simulation to reach the slow manifold;
\item \verb|timeSteps(2)| is the subsequent time which \dmd\
analyses to model the slow manifold (must be longer than
\(\verb|rank|\cdot\verb|dt|\)).
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|xs|, \(n\times\ell\) array of approximate
solution vector at the specified times (the transpose of
what \Matlab\ integrators do!)
\item \verb|xss|, optional, \(n\times\text{big}\) array of
the microscale simulation bursts---separated by NaNs for
possible plotting.
\item \verb|tss|, optional, \(1\times\text{big}\) vector of
times corresponding to the columns of~\verb|xss|.
\end{itemize}
Compute the time-steps and create storage for outputs.
\begin{matlab}
%}
DT=diff(Ts);
n=length(x0);
xs=nan(n,length(Ts));
xss=[];tss=[];
%{
\end{matlab}
If any~\verb|x0| are \verb|NaN|, then assume the time
derivative routine can cope, and here we just exclude these
from \dmd\ projection and from any error estimation. This
allows a user to have space in the solutions for breaks in
the data vector (that, for example, may be filled in with
boundary values for a \pde\ discretisation).
\begin{matlab}
%}
j=find(~isnan(x0));
%{
\end{matlab}
If either of the timeSteps are non-integer valued, then
assume they are both times, instead of micro-time-steps, so
set the number of time-steps accordingly (multiples
of~\verb|dt|).
\begin{matlab}
%}
timeSteps=round(timeSteps/dt);
timeSteps(2)=max(rank+1,timeSteps(2));
%{
\end{matlab}
Set an algorithmic tolerance for miscellaneous purposes. As
at Jan 2018, it is a guess. It might be similar to some
level of microscale `noise' in the burst. Also, in an
oscillatory mode for projection, set the expected maximum
number of cycles in a projection.
\begin{matlab}
%}
algTol=log(1e8);
cycMax=3;
%{
\end{matlab}
Initialise first result to the given initial condition.
\begin{matlab}
%}
xs(:,1)=x0(:);
%{
\end{matlab}
Projectively integrate each of the time-steps from~\(t_k\)
to~\(t_{k+1}\).
\begin{matlab}
%}
for k=1:length(DT)
if k>1, timeSteps(1)=timeSteps(2); end%only use long burst for initial ???????????
%{
\end{matlab}
Microscale integration is simple, second-order, Runge--Kutta
method. Reasons: the start-up time for implicit integrators,
such as ode15s, is too onerous to be worthwhile for each
short burst; the microscale time-step needed for stability
of explicit integrators is so small that a low order method
is usually accurate enough.
\begin{matlab}
%}
x=[x0(:) nan(n,sum(timeSteps))];
for i=1:sum(timeSteps)
xmid =x(:,i)+dt/2*fun(Ts(k)+(i-1)*dt,x(:,i));
x(:,i+1)=x(:,i)+dt*fun(Ts(k)+(i-0.5)*dt,xmid);
end
%{
\end{matlab}
If user requests microscale bursts, then store.
\begin{matlab}
%}
if nargout>1,xss=[xss x nan(n,1)];
if nargout>2,tss=[tss Ts(k)+(0:sum(timeSteps))*dt nan];
end,end
%{
\end{matlab}
Grossly check on whether the microscale integration is
stable. Use the 1-norm, the largest column sum of the
absolute values, for little reason. Is this any use??
\begin{matlab}
%}
if norm(x(j,ceil(end/2):end),1) ...
> 10*norm(x(j,1:floor(end/2)),1)
xMicroscaleIntegration=x, macroTime=Ts(k)
warning('projIntDMD: microscale integration appears unstable')
break%out of the integration loop
end
%{
\end{matlab}
Similarly if any non-numbers generated.
\begin{matlab}
%}
if sum(~isfinite(x(:)))>0
break%out of integration loop
end
%{
\end{matlab}
\paragraph{DMD extrapolation over the macroscale}
But skip if the simulation has already reached the next time.
\begin{matlab}
%}
iFin=1+sum(timeSteps);
DTgap=DT(k)-iFin*dt;
if DTgap*sign(dt)<=1e-9
i=round(DT(k)/dt); x0(j)=x(:,i+1);
else
%{
\end{matlab}
\dmd\ appears to work better when ones are adjoined to the
data vectors. \footnote{A reason is as follows. Consider the
one variable linear \ode\ \(\dot x=f+J(x-x_0)\) with
\(x(0)=x_0\) (as from a local linearisation of nonlinear
\ode). The solution is \(x(t)=(x_0-f/J)+(f/J)e^{Jt}\) which
sampled at a time-step~\(\tau\) is
\(x_k=(x_0-f/J)+(f/J)G^k\) for \(G:=e^{J\tau}\). Then
\(x_{k+1}\neq ax_k\) for any~\(a\). However, \(\begin{bmat}
x_{k+1}\\1 \end{bmat} =\begin{bmat} G&a\\0&1 \end{bmat}
\begin{bmat} x_k\\1 \end{bmat}\) for a constant
\(a:=(x_0-f/J)(1-G)\). That is, with ones adjoined, the data
from the \ode\ fits the \dmd\ approach.
}
\begin{matlab}
%}
iStart=1+timeSteps(1);
x=[x;ones(1,iFin)]; j1=[j;n+1];
%{
\end{matlab}
Then the basic \dmd\ algorithm: first the fit. However, need
to test whether we need to worry about the microscale
time-step being too small and leading to an effect analogous
to `numerical differentiation' errors: akin to the
rule-of-thumb in fitting chaos with time-delay coordinates
that a good time-step is approximately the time of the first
zero of the autocorrelation.
\begin{matlab}
%}
[U,S,V]=svd(x(j1,iStart:iFin-1),'econ');
S=diag(S);
Sr = S(1:rank); % singular values, rx1
AUr=bsxfun(@rdivide,x(j1,iStart+1:iFin)*V(:,1:rank),Sr.');%nxr
Atilde = U(:,1:rank)'*AUr; % low-rank dynamics, rxr
[Wr, D] = eig(Atilde); % rxr
Phi = AUr*Wr; % DMD modes, nxr
%{
\end{matlab}
Second, reconstruct a prediction for the time-step. The
current micro-simulation time is \verb|dt*iFin|, so step
forward an amount to predict the systems state at
\verb|Ts(k+1)|. Perhaps should test~\(\omega\) and abort if
'large' and/or positive?? Answer: not necessarily as if the
rank is large then the omega could contain large negative
values.
\begin{matlab}
%}
omega = log(diag(D))/dt; % continuous-time eigenvalues, rx1
bFin=Phi\x(j1,iFin); % rx1
%{
\end{matlab}
But we want to neglect modes that are insignificant as
characterised by \autoref{tbl:negbad}, or be warned of modes
that grow too rapidly.
\begin{table}
\caption{\label{tbl:negbad}criterion for deciding if some
\dmd\ modes are to be neglected, and if not neglected then
are they growing too badly?}
\begin{equation*}
\begin{array}{llp{0.5\linewidth}}\hline
\text{neglectness}&
\parbox[t]{4em}{\raggedright range for \(\varepsilon\approx 10^{-8}\)}&
\text{reason}\\\hline
\max(0,-\log_e|b_i|)& 0-19 &
Very small noise in the burst implies a numerical error mode.
\\
\max(0,-\Re\omega_i\,\Delta t)& 0-19 &
Rapidly decaying mode of the macro-time-step is a micro-mode
that happened to be resolved in the data.
\\\hline
\text{badness}& &
provided not already neglected
\\\hline
\max(0,+\Re\omega_i\,\Delta t)& 0-19 &
Micro-scale mode that rapidly grows, so macro-step should be smaller.
\\
\frac3C|\Im\omega_i|\Delta t& 0-19 &
An oscillatory mode with\({}\geq C\) cycles in macro-step~\(\Delta t\).
\\\hline
\end{array}
\end{equation*}
\end{table}
Assume appropriate to sum the neglect-ness, and the badness,
for testing. Then warn if there is a mode that is too bad.
\begin{matlab}
%}
DTgap=DT(k)-iFin*dt;
negness=max(0,-log(abs(bFin)))+max(0,-real(omega*DTgap));
badness=max(0,+real(omega*DTgap))+3/cycMax*abs(imag(omega))*DTgap;
iOK=find(negness<algTol);
iBad=find(badness(iOK)>algTol);
if ~isempty(iBad)
warning('projIntDMD: some bad modes in projection')
badness=badness(iOK(iBad))
rank=rank
burstDt=timeSteps*dt
break
end
%{
\end{matlab}
Scatter the prediction into the non-Nan elements of \verb|x0|.
\begin{matlab}
%}
x0(j)=Phi(1:end-1,iOK)*(bFin(iOK).*exp(omega(iOK)*DTgap)); % nx1
%{
\end{matlab}
End the omission of the projection in the case when the
burst is longer than the macroscale step.
\begin{matlab}
%}
end
%{
\end{matlab}
Since some of the~\(\omega\) may be complex, if the
simulation burst is real, then force the \dmd\ prediction to
be real.
\begin{matlab}
%}
if isreal(x), x0=real(x0); end
xs(:,k+1)=x0;
%{
\end{matlab}
End the macroscale time-stepping.
\begin{matlab}
%}
end
%{
\end{matlab}
If requested, then add the final point to the microscale
data.
\begin{matlab}
%}
if nargout>1,xss=[xss x0];
if nargout>2,tss=[tss Ts(end)];
end,end
%{
\end{matlab}
End of the function with result vectors returned in columns
of~\verb|xs|, one column for each time in~\verb|Ts|.
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
projIntDMDExplore1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/ProjIntDMD/projIntDMDExplore1.m
| 4,839 |
utf_8
|
25dc7d34dbd51ab52031fda41616128b
|
% Explore the time integration function projIntDMD()
% on discretisation of a nonlinear diffusion PDE.
% AJR, Jan 2018
%!TEX root = doc.tex
%{
\section{\texttt{projIntDMDExplore1}: explore effect of varying parameters}
\label{sec:pi1eevp}
\localtableofcontents
Seek to simulate the nonlinear diffusion \pde\
\begin{equation*}
\D tu=u\DD xu\quad \text{such that }u(\pm 1)=0,
\end{equation*}
with random positive initial condition.
Set the number of interior points in the domain~\([-1,1]\), and the macroscale time-step.
\begin{matlab}
%}
function projIntDMDExplore1
n=9
ts=0:2:6
dt=2/n^2
ICNoise=0.3
%{
\end{matlab}
Very strangely, the results from Matlab and Octave are different for the zero noise case!???? It should be deterministic. Significantly different in that Matlab fails more often.
\begin{figure}
\caption{\label{fig:explor1icn0}errors in the projective integration of the nonlinear diffusion \pde\ from initial conditions that are on the slow manifold. Plotted are stereo views of isosurfaces in parameter space: the first row is after the first projective step; the second row after the second step. }
\centering
\includegraphics[width=\linewidth]{explore1icn0}
\end{figure}%
\autoref{fig:explor1icn0} shows the parameter variations when the system is already on the slow manifold.
The picture after two time-steps, bottom row, appears clearer than for one time-step.
The errors do not vary with rank provided that it is\({}\geq2\).
There is only a very weak dependence upon the length of the burst being analysed---and that could be due to reduction in the gap.
There is a weak dependence upon the transient-time, but only by a factor of two across the domain considered.
\begin{figure}
\caption{\label{fig:explor1icn3}errors in the projective integration of the nonlinear diffusion \pde\ from initial conditions with noise~\texttt{0.3*rand}. Plotted are stereo views of isosurfaces in parameter space: the first row is after the first projective step; the second row after the second step. }
\centering
\includegraphics[width=\linewidth]{explore1icn3}
\end{figure}%
With the addition of a noisy initial conditions, \autoref{fig:explor1icn3}, the rank has an effect, and the transient-time appears to be a slightly stronger influence.
I suspect this means that we need to allow the initial burst to have a longer transient time than subsequent bursts.
Initial conditions may typically need a longer `healing' time.
Thus code an extra \verb|timeStep| parameter.
Set the initial condition to parabola or some skewed random positive values.
Without noise this initial condition is already on the slow manifold so only little reason for transient time.
\begin{matlab}
%}
x=linspace(-1,1,n+2)';
u0=(0.5+ICNoise*rand(n+2,1)).*(1-x.^2);
%{
\end{matlab}
First find a reference solution of the microscale dynamics over all time.
\begin{matlab}
%}
[Us,Uss,Tss]=projIntDMD(@dudt,u0,ts,2,dt,[0 2]);
%{
\end{matlab}
Set up various combinations of parameters.
\begin{matlab}
%}
[rank,trant,slowt]=meshgrid(1:5,[1 2 4 6 8]*0.05,[2 4 8 12 16]*dt);
ps=[rank(:) trant(:) slowt(:)];
%{
\end{matlab}
Projectively integrate in time with various parameters.
\begin{matlab}
%}
errs=[]; relerrs=[];
for p=ps'
[us,uss,tss]=projIntDMD(@dudt,u0,ts,p(1),dt,p(2:3));
%{
\end{matlab}
Plot the macroscale predictions
\begin{matlab}
%}
if 0
clf,plot(x,Us,'o-',x,us,'x--')
xlabel('space x'),ylabel('u(x,t)')
pause(0.01)
end
%{
\end{matlab}
Accumulate errors as function of time.
\begin{matlab}
%}
err=sqrt(sum((us-Us).^2))
errs=[errs;err];
relerrs=[relerrs;err./sqrt(sum(Us.^2))];
%{
\end{matlab}
End the loop over parameters.
\begin{matlab}
%}
end
%{
\end{matlab}
Stereo view of isosurfaces of errors after both one and two time-steps.
The three surfaces are the quartiles of the errors, coloured accordingly, but with a little extra colour from position for clarity.
\begin{matlab}
%}
clf()
vals=nan(size(rank));
for k=1:2
vals(:)=errs(:,k+1);
q=prctile(vals(:),(0:4)*25)
for j=1:2, subplot(2,2,j+2*(k-1)),hold on
for i=2:4 % draw three quartiles
isosurface(rank,trant,slowt,vals,q(i) ...
,q(i)+0.03*(rank/10-trant+slowt))
end,hold off
xlabel('rank'),ylabel('transient'),zlabel('analysed')
colorbar
set(gca,'view',[57-j*5,30])
end%j
end%k
%{
\end{matlab}
Save to file
\begin{matlab}
%}
print('-depsc2',['explore1icn' num2str(ICNoise*10)])
%{
\end{matlab}
End the main function (not needed for new enough Matlab).
\begin{matlab}
%}
end
%{
\end{matlab}
\paragraph{The nonlinear PDE discretisation}
Code the simple centred difference discretisation of the nonlinear diffusion \pde\ with constant (usually zero) boundary values.
\begin{matlab}
%}
function ut=dudt(t,u)
n=length(u);
dx=2/(n-1);
j=2:n-1;
ut=[0
u(j).*(u(j+1)-2*u(j)+u(j-1))/dx^2
0];
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
mmPatchSys2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MoveMesh/mmPatchSys2.m
| 18,670 |
utf_8
|
6414e727f6bee29c0f16dc8daec55977
|
% mmPatchSys2() provides an interface to time integrators
% for the dynamics on moving patches coupled across space. The
% system must be a lattice system such as a PDE
% discretisation. AJR, Aug 2021 -- Sep 2021
%!TEX root = doc.tex
%{
\section{\texttt{mmPatchSys2()}: interface 2D space of
moving patches to time integrators}
\label{sec:mmPatchSys2}
\paragraph{Beware ad hoc assumptions}
In an effort to get started, I make some plausible generalisations from the 1D code to this 2D code, in the option \verb|adhoc|.
Also, I code the alternative \verb|Huang98| which aims to implement the method of \cite{Huang98}.
To simulate in time with 2D patches moving in space we need
to interface a users time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function \verb|mmPatchSys2()| provides an interface.
Patch edge values are determined by macroscale interpolation
of the patch-centre or edge values. Microscale heterogeneous
systems may be accurately simulated with this function via
appropriate interpolation. Communicate patch-design
variables (\cref{sec:configPatches2}) either via the global
struct~\verb|patches| or via an optional third argument
(except that this last is required for parallel computing of
\verb|spmd|).
\begin{matlab}
%}
function dudt = mmPatchSys2(t,u,patches)
global theMethod % adhoc or Huang98
global ind % =1 for x-dirn and =2 for y-dirn testing Huang
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector of length
$2\cdot\verb|prod(nPatch)| +\verb|prod(nSubP)| \cdot
\verb|nVars| \cdot \verb|nEnsem| \cdot \verb|prod(nPatch)|$
where there are $\verb|nVars| \cdot \verb|nEnsem|$ field
values at each of the points in the $\verb|nSubP(1)| \times
\verb|nSubP(2)| \times \verb|nPatch(1)| \times
\verb|nPatch(2)|$ grid.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches2()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,M,patches)| that computes the time derivatives
on the patchy lattice, where the \((I,J)\)th~patch moves at
velocity~\((M.Vx_I,M.Vy_J)\) and at current time is
displaced~\((M.Dx_I,M.Dy_J)\) from the fixed reference
positions in~\verb|.x| and~\verb|.y|\,. The array~\verb|u|
has size $\verb|nSubP(1)| \times \verb|nSubP(2)| \times
\verb|nVars| \times \verb|nEsem| \times \verb|nPatch(1)|
\times \verb|nPatch(2)|$. Time derivatives must be computed
into the same sized array, although herein the patch
edge-values are overwritten by zeros.
\item \verb|.x| is $\verb|nSubP(1)| \times1 \times1 \times1
\verb|nPatch(1)| \times1$ array of the spatial
locations~$x_{i}$ of the microscale $(i,j)$-grid points in
every patch. Currently it \emph{must} be an equi-spaced
lattice on both macro- and micro-scales??
\item \verb|.y| is similarly $1 \times \verb|nSubP(2)|
\times1 \times1 \times1 \times \verb|nPatch(2)|$ array of
the spatial locations~$y_{j}$ of the microscale $(i,j)$-grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on both macro- and micro-scales.
\item \verb|.Xlim| ??
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector\slash array of of time
derivatives, but with patch edge-values set to zero. It is
of total length $2\cdot\verb|prod(nPatch)| + \verb|prod(nSubP)| \cdot \verb|nVars|
\cdot \verb|nEnsem| \cdot \verb|prod(nPatch)|$ and the same
dimensions as~\verb|u|.
\end{itemize}
\begin{devMan}
Extract the \(2\cdot\verb|prod(nPatch)|\) displacement
values from the start of the vectors of evolving variables.
Reshape the rest as the fields~\verb|u| in a 6D-array, and
sets the edge values from macroscale interpolation of
centre-patch values. \cref{sec:patchEdgeInt2} describes
\verb|patchEdgeInt2()|.
\begin{matlab}
%}
Nx = size(patches.x,5);
Ny = size(patches.y,6);
nM = Nx*Ny;
M.Dx = reshape(u( 1:nM ),[1 1 1 1 Nx Ny]);
M.Dy = reshape(u(nM+1:2*nM),[1 1 1 1 Nx Ny]);
u = patchEdgeInt2(u(2*nM+1:end),patches);
%{
\end{matlab}
\paragraph{Moving mesh velocity}
Developing from standard moving meshes for \pde{}s
\cite[e.g.]{Budd2009, Huang10}, we follow
\cite{Maclean2021a}, and generalise to~2D according to the algorithm of \cite{Huang98}, and also ad hoc.
Here the patch indices~\(I,J\) play the role of mesh variables~\(\xi,\eta\) of \cite{Huang98}. There
exists a set of macro-scale mesh points $\Xv_{IJ}(t) := \big(X_{IJ}(t) \C Y_{IJ}(t) \big) := \big( X_{IJ}^0+Dx_{IJ}(t) \C Y_{IJ}^0+Dy_{IJ}(t) \big)$ (at the centre) of each patch
with associated field values, say
$U_{IJ}(t):=\overline{u_{ijIJ}(t)}$.
Also, remove microscale dimensions from the front of these macro-mesh arrays, so \verb|X,Y| are~2D, and \verb|U| is~4D.
\begin{matlab}
%}
X = shiftdim( mean(patches.x,1)+M.Dx ,4);
Y = shiftdim( mean(patches.y,2)+M.Dy ,4);
U = shiftdim( mean(mean(u,1,'omitnan'),2,'omitnan') ,2);
%{
\end{matlab}
Then for every patch~\((I,J)\) we set \(??:={}\)the
\(q\)th~spatial component of the step to the next patch in
the \(p\)th~index direction, for periodic patch
indices~\((I,J)\).
Throughout, use appended \verb|r,u| to denote mesh-midpoint quantities at \(I+\frac12\) and \(J+\frac12\), respectively, and use \verb|_I,_J| to respectively denote differences in the macro-mesh indices~\(I,J\) which then estimate derivatives in the mesh parameters, \(\D\xi{}\) and \(\D\eta{}\), respectively.
\begin{matlab}
%}
I=1:Nx; Ip=[2:Nx 1]; Im=[Nx 1:Nx-1];
J=1:Ny; Jp=[2:Ny 1]; Jm=[Ny 1:Ny-1];
Xr_I = X(Ip,J)-X(I,J); % propto dX/dxi
Yr_I = Y(Ip,J)-Y(I,J); % propto dY/dxi
Xu_J = X(I,Jp)-X(I,J); % propto dX/deta
Yu_J = Y(I,Jp)-Y(I,J); % propto dY/deta
Xr_I(Nx,:) = Xr_I(Nx,:)+diff(patches.Xlim(1:2));
Yu_J(:,Ny) = Yu_J(:,Ny)+diff(patches.Xlim(3:4));
%{
\end{matlab}
\subsection{ad hoc attempt}
\begin{matlab}
%}
switch theMethod
case 'adhoc'
%{
\end{matlab}
Temporarily shift the macro-mesh info into dimensions~3 and~4:
\begin{matlab}
%}
Xr_I = shiftdim(Xr_I,-2); Yr_I = shiftdim(Yr_I,-2);
Xu_J = shiftdim(Xu_J,-2); Yu_J = shiftdim(Yu_J,-2);
%{
\end{matlab}
We discretise a moving mesh \pde\ for node
locations~$(X_{IJ},Y_{IJ})$ with field values~$U_{IJ}$ via
the second derivatives estimates ??
\begin{subequations} \label{mm2Disc}
\begin{equation}
U''_{j} := \frac2{H_j+H_{j-1}}\left[ \frac{U_{j+1} -
U_j}{H_j} - \frac{U_{j} - U_{j-1}}{H_{j-1}} \right] .
\end{equation}
First, compute first derivatives at \((I+\tfrac12,J)\) and
\((I,J+\tfrac12)\) respectively---these are derivatives in the macro-mesh directions, incorrectly scaled.
\begin{matlab}
%}
Ux = (U(:,:,Ip,J)-U(:,:,I,J))./Xr_I(:,:,I,J);
Uy = (U(:,:,I,Jp)-U(:,:,I,J))./Yu_J(:,:,I,J);
%{
\end{matlab}
Second, compute second derivative matrix, without assuming
symmetry because the derivatives in space are not quite the
same as the derivatives in indices. The mixed derivatives
are at \((I+\tfrac12,J+\tfrac12)\), so average to get at
patch locations.
\begin{matlab}
%}
Uxx = ( Ux(:,:,I,J)-Ux(:,:,Im,J) )*2./(Xr_I(:,:,I,J)+Xr_I(:,:,Im,J));
Uyy = ( Uy(:,:,I,J)-Uy(:,:,I,Jm) )*2./(Yu_J(:,:,I,J)+Yu_J(:,:,I,Jm));
Uyx = ( Uy(:,:,Ip,J)-Uy(:,:,I,J) )./Xr_I(:,:,I,J);
Uxy = ( Ux(:,:,I,Jp)-Ux(:,:,I,J) )./Yu_J(:,:,I,J);
Uyx = (Uyx(:,:,I,J)+Uyx(:,:,Im,J)+Uyx(:,:,I,Jm)+Uyx(:,:,Im,Jm))/4;
Uxy = (Uxy(:,:,I,J)+Uxy(:,:,Im,J)+Uxy(:,:,I,Jm)+Uxy(:,:,Im,Jm))/4;
%{
\end{matlab}
And compute its norm over all variables and ensembles
(arbitrarily?? chose the mean square norm here, using
\verb|abs.^2| as they may be complex), shifting the variable
and ensemble dimensions out of the result to give 2D array
of values, one for each patch (use \verb|shiftdim| rather
than \verb|squeeze| as users may invoke a 1D array of 2D
patches, as in channel dispersion).
\begin{matlab}
%}
U2 = shiftdim( mean(mean( ...
abs(Uxx).^2+abs(Uyy).^2+abs(Uxy).^2+abs(Uyx).^2 ...
,1),2) ,2);
Xr_I = shiftdim(Xr_I,2); Yr_I = shiftdim(Yr_I,2);
Xu_J = shiftdim(Xu_J,2); Yu_J = shiftdim(Yu_J,2);
%{
\end{matlab}
Having squeezed out all microscale information, the
global moderating coefficient in~1D??
\begin{equation}
\label{mm2Al}
\alpha := \max\left\{ 1\C \left[\frac{1}{b-a}\sum_{j}
H_{j-1} \frac12 \left({U''_{j}}^{2/3} +
{U''_{j-1}}^{2/3}\right)\right]^3 \right\}
\end{equation}
generalises to an integral over \emph{approximate}
parallelograms in~2D?? (area approximately?? determined by
cross-product). Rather than \(\max(1,\cdot)\) surely better
to use something smooth like~\(\sqrt(1+\cdot^2)\)??
\begin{matlab}
%}
U23 = U2.^(1/3);
alpha = sum(sum( ...
abs( Xr_I(Im,Jm).*Yu_J(Im,Jm)-Yr_I(Im,Jm).*Xu_J(Im,Jm) ) ...
.*( U23(I,J)+U23(Im,J)+U23(I,Jm)+U23(Im,Jm) )/4 ...
))/diff(patches.Xlim(1:2))/diff(patches.Xlim(3:4));
alpha = sqrt(1+alpha^6);
%{
\end{matlab}
Then the importance function at each patch is the 2D array
\begin{equation}
\label{mm2R}
\rho_j := \left(1 + \frac{1}{\alpha} {U''_{j}}^2 \right)^{1/3},
\end{equation}
\begin{matlab}
%}
rho = ( 1+U2/alpha ).^(1/3);
%{
\end{matlab}
For every patch, we move all micro-grid points according to
the following velocity of the notional macro-scale node of
that patch: (Since we differentiate the importance function,
maybe best to compute it above at half-grid points of the
patches---aka a staggered scheme??)
\begin{equation}
\label{mm2X}
V_j:= \de t{X_j} = \frac{(N-1)^2}{2\rho_j \tau } \left[
(\rho_{j+1}+\rho_j) H_j - (\rho_j + \rho_{j-1}) H_{j-1}
\right].
\end{equation}
Is the \verb|Nx| and \verb|Ny| correct here??
And are the derivatives appropriate since these here are
scaled index derivatives, not actually spatial derivatives??
\begin{matlab}
%}
M.Vx = shiftdim( ...
((rho(Ip,J)+rho(I,J)).*Xr_I(I,J) ...
-(rho(Im,J)+rho(I,J)).*Xr_I(Im,J) ) ...
./rho(I,J) *(Nx^2/2/patches.mmTime) ...
,-4);
M.Vy = shiftdim( ...
((rho(I,Jp)+rho(I,J)).*Yu_J(I,J) ...
-(rho(I,Jm)+rho(I,J)).*Yu_J(I,Jm) ) ...
./rho(I,J) *(Ny^2/2/patches.mmTime) ...
,-4);
%{
\end{matlab}
\end{subequations}
\subsection{Huang98}
Here encode the algorithm of \cite{Huang98}.
\begin{matlab}
%}
case 'Huang98' %= theMethod
%{
\end{matlab}
The Jacobian at the \(N_x\times N_y\) mesh-points is, using centred differences,
\begin{matlab}
%}
Jac = 0.25*( (Xr_I+Xr_I(Im,J)).*(Yu_J+Yu_J(I,Jm)) ...
-(Yr_I+Yr_I(Im,J)).*(Xu_J+Xu_J(I,Jm)) );
%{
\end{matlab}
\begin{subequations} \label{mm2Disc}
The mesh movement \pde\ is \cite[(24), with \(\gamma_2=0\)]{Huang98}
\begin{align}&
\D t\Xv =-\frac{\Xv_\xi}{\tau\sqrt{\tilde g_1}\cJ}\left\{
+\D\xi{}\left[\frac{\Xv_\eta^TG_1\Xv_\eta}{\cJ g_1}\right]
-\D\eta{}\left[\frac{\Xv_\xi^TG_1\Xv_\eta}{\cJ g_1}\right]
\right\}
\nonumber\\&
\phantom{\D t\Xv =}{}
-\frac{\Xv_\eta}{\tau\sqrt{\tilde g_2}\cJ}\left\{
-\D\xi{}\left[\frac{\Xv_\eta^TG_2\Xv_\xi}{\cJ g_2}\right]
+\D\eta{}\left[\frac{\Xv_\xi^TG_2\Xv_\xi}{\cJ g_2}\right]
\right\} ,
\label{mm2DiscdXdt}
\\&
\text{Jacobian }\cJ :=X_\xi Y_\eta -X_\eta Y_\xi\,,
\\&
g_k :=\det(G_k),
\\&
G_1 :=\sqrt{1+\|\grad U\|^2}\left[(1-\gamma_1)\cI
+\gamma_1S(\grad\tilde \xi)\right],
\\&
G_2 :=\sqrt{1+\|\grad U\|^2}\left[(1-\gamma_1)\cI
+\gamma_1S(\grad\tilde\eta)\right],
\\&
\text{matrix }S(\vv) :=\vv_\perp\vv_\perp^T/\|\vv\|^2
\quad\text{for }\vv_\perp:=(v_2,-v_1),
\\&\text{identity }\cI.
\end{align}
In their examples, \cite{Huang98} chose the mesh orthogonality parameter \(\gamma_1=0.1\)\,.
\begin{matlab}
%}
gamma1=0.1;
%{
\end{matlab}
The tildes appear to denote a reference mesh \cite[p.1005]{Huang98} which could be the identity map \((\tilde\xi,\tilde\eta)=(x,y)\), so here maybe \((\tilde I,\tilde J)=(\tilde\xi,\tilde\eta)=(X/H_x,Y/H_y)\).
We discretise the moving mesh \pde\ for node
locations~$(X_{IJ},Y_{IJ})$ with field values~$U_{IJ}$ via
the second derivatives estimates ??
So \cite{Huang98}'s \(\xi,i\mapsto I\), and \(\eta,j\mapsto J\), and \(\xv\mapsto \verb|Xv|\)??
\paragraph{Importance functions}
First, compute the gradients of the macroscale field formed into \(w=\sqrt{1+\|\grad\Uv\|^2}\) \cite[(30)]{Huang98}, using centred differences from patch to patch, unless we use the patches to estimate first derivatives (implicitly the interpolation).
Need to shift dimensions of macroscale mesh to cater for components of the field~\Uv.
\begin{matlab}
%}
Y_J = shiftdim( (Yu_J(I,J)+Yu_J(I,Jm))/2 ,-2);
Y_I = shiftdim( (Yr_I(I,J)+Yr_I(Im,J))/2 ,-2);
U_x = ( (Y_J(:,:,Ip,J).*U(:,:,Ip,J)-Y_J(:,:,Im,J).*U(:,:,Im,J))/2 ...
-(Y_I(:,:,I,Jp).*U(:,:,I,Jp)-Y_I(:,:,I,Jm).*U(:,:,I,Jm))/2 ...
)./Jac;
X_J = shiftdim( (Xu_J(I,J)+Xu_J(I,Jm))/2 ,-2);
X_I = shiftdim( (Xr_I(I,J)+Xr_I(Im,J))/2 ,-2);
U_y = ( (X_J(:,:,Ip,J).*U(:,:,Ip,J)-X_J(:,:,Im,J).*U(:,:,Im,J))/2 ...
-(X_I(:,:,I,Jp).*U(:,:,I,Jp)-X_I(:,:,I,Jm).*U(:,:,I,Jm))/2 ...
)./Jac;
w = sqrt(1 + sum(sum(U_x.^2+U_y.^2,1),2) );
testy(w,2+ind,'w')
%{
\end{matlab}
In order to compute~\(G_k\), it seems \(\grad\eta=(Y_\eta,-Y_\xi)/\cJ\) and \(\grad\xi=(-X_\eta,X_\xi)/\cJ\).
Then, \(S(\grad\xi)\) has \(\vv_\perp=(X_\xi,X_\eta)/\cJ\) so \(S(\grad\xi)=\begin{bmat} X_\xi^2 &X_\xi X_\eta \\ X_\xi X_\eta &X_\eta^2 \end{bmat}/(X_\xi^2+X_\eta^2)\).
Now \cite{Huang98} has tildes on these, so they are meant to be reference coordinates?? in which case we would have \(X_\eta=0\)\,, so \(S=\begin{bmat}1 &0 \\ 0 &0 \end{bmat}\), and so \(G_1\propto \begin{bmat} 1&0\\0&1-\gamma_1 \end{bmat}\)---\emph{I do not see how this helps stop the mesh degenerating}.
\begin{matlab}
%}
G1 = w.*( (1-gamma1)*eye(2) ...
+gamma1*[Y_I.^2 Y_I.*Y_J; Y_I.*Y_J Y_J.^2]./(Y_I.^2+Y_J.^2) );
G2 = w.*( (1-gamma1)*eye(2) ...
+gamma1*[X_I.^2 X_I.*X_J; X_I.*X_J X_J.^2]./(X_I.^2+X_J.^2) );
testy(G1,2+ind,'G1')
testy(G2,2+ind,'G2')
%{
\end{matlab}
Apply low-pass filter \cite[(27)]{Huang98} (although unclear whether to apply the filter four times to the whole of both matrices?? or once to each of the four components of both matrices??):
\begin{matlab}
%}
for k=1:1
G1 = G1/4 ...
+(G1(:,:,Ip,J)+G1(:,:,Im,J)+G1(:,:,I,Jp)+G1(:,:,I,Jm))/8 ...
+(G1(:,:,Ip,Jp)+G1(:,:,Im,Jm)+G1(:,:,Im,Jp)+G1(:,:,Ip,Jm))/16;
G2 = G2/4 ...
+(G2(:,:,Ip,J)+G2(:,:,Im,J)+G2(:,:,I,Jp)+G2(:,:,I,Jm))/8 ...
+(G2(:,:,Ip,Jp)+G2(:,:,Im,Jm)+G2(:,:,Im,Jp)+G2(:,:,Ip,Jm))/16;
end
testy(G1,2+ind,'G1')
testy(G2,2+ind,'G2')
%{
\end{matlab}
\paragraph{Macro-mesh movement}
These are the \(2\times2\) matrices at \(N_x\times N_y\) midpoints of the mesh-net \cite[(27)]{Huang98}:
\begin{matlab}
%}
G1r = (G1(:,:,Ip,:)+G1(:,:,I,:))/2;
G2r = (G2(:,:,Ip,:)+G2(:,:,I,:))/2;
G1u = (G1(:,:,:,Jp)+G1(:,:,:,J))/2;
G2u = (G2(:,:,:,Jp)+G2(:,:,:,J))/2;
testy(G1r,2+ind,'G1')
testy(G2r,2+ind,'G2')
testy(G1u,2+ind,'G1')
testy(G2u,2+ind,'G2')
%{
\end{matlab}
Compute \(N_x\times N_y\) determinant of matrices \cite[(27)]{Huang98}:
\begin{matlab}
%}
g1 = shiftdim( G1(1,1,:,:).*G1(2,2,:,:) ...
-G1(1,2,:,:).*G1(2,1,:,:) ,2);
g2 = shiftdim( G2(1,1,:,:).*G2(2,2,:,:) ...
-G2(1,2,:,:).*G2(2,1,:,:) ,2);
testy(g1,ind,'g1')
testy(g2,ind,'g2')
g1r = shiftdim( G1r(1,1,:,:).*G1r(2,2,:,:) ...
-G1r(1,2,:,:).*G1r(2,1,:,:) ,2);
g2r = shiftdim( G2r(1,1,:,:).*G2r(2,2,:,:) ...
-G2r(1,2,:,:).*G2r(2,1,:,:) ,2);
g1u = shiftdim( G1u(1,1,:,:).*G1u(2,2,:,:) ...
-G1u(1,2,:,:).*G1u(2,1,:,:) ,2);
g2u = shiftdim( G2u(1,1,:,:).*G2u(2,2,:,:) ...
-G2u(1,2,:,:).*G2u(2,1,:,:) ,2);
%{
\end{matlab}
Compute vector \verb|Xv._.| of coordinate derivatives \cite[(27)]{Huang98}---use arrays \verb|X_.| and \verb|Y_.| here as they know the macro-periodicity.
\begin{matlab}
%}
Xr_J = 0.25*(Xu_J(I,Jm)+Xu_J(I,J)+Xu_J(Ip,Jm)+Xu_J(Ip,J));
Yr_J = 0.25*(Yu_J(I,Jm)+Yu_J(I,J)+Yu_J(Ip,Jm)+Yu_J(Ip,J));
Xvr_J = [shiftdim(Xr_J,-1);shiftdim(Yr_J,-1)];
Xvr_I = [shiftdim(Xr_I,-1);shiftdim(Yr_I,-1)];
testy(Xvr_J,1+ind,'Xvr_J')
testy(Xvr_I,1+ind,'Xvr_I')
Xu_I = 0.25*(Xr_I(Im,J)+Xr_I(I,J)+Xr_I(Im,Jp)+Xr_I(I,Jp));
Yu_I = 0.25*(Yr_I(Im,J)+Yr_I(I,J)+Yr_I(Im,Jp)+Yr_I(I,Jp));
Xvu_I = [shiftdim(Xu_I,-1);shiftdim(Yu_I,-1)];
Xvu_J = [shiftdim(Xu_J,-1);shiftdim(Yu_J,-1)];
testy(Xvu_J,1+ind,'Xvu_J')
testy(Xvu_I,1+ind,'Xvu_I')
%{
\end{matlab}
Then the two Jacobians at the \(N_x\times N_y\) midpoints of the mesh-net are \cite[(27)]{Huang98}:
\begin{matlab}
%}
Jacr = Xr_I.*Yr_J - Yr_I.*Xr_J;
Jacu = Yu_J.*Xu_I - Xu_J.*Yu_I;
testy(Jacr,ind,'Jacr')
testy(Jacu,ind,'Jacu')
%{
\end{matlab}
For vectors~\xv,\yv\ of dimension \(d\times N_x\times N_y\) and array~\(G\) of dimension \(d\times d\times N_x\times N_y\), define function to evaluate product~\(\xv^TG\yv\) of dimension \(N_x\times N_y\):
\begin{matlab}
%}
xtGy = @(x,G,y) shiftdim(sum(sum( ...
permute(x,[1 4 2 3]).*G.*shiftdim(y,-1) ...
)),2);
%{
\end{matlab}
The moving mesh \ode{}s~\eqref{mm2DiscdXdt} are then coded
\cite[(26)]{Huang98} as
(should \verb|sqrt(g1)| be \verb|sqrt(g1tilde)|??)
\begin{matlab}
%}
brace1 = xtGy(Xvr_J(:,I,J),G1r(:,:,I,J),Xvr_J(:,I,J))...
./Jacr(I,J)./g1r(I,J) ...
-xtGy(Xvr_J(:,Im,J),G1r(:,:,Im,J),Xvr_J(:,Im,J))...
./Jacr(Im,J)./g1r(Im,J) ...
-xtGy(Xvr_I(:,I,J),G1u(:,:,I,J),Xvr_J(:,I,J))...
./Jacu(I,J)./g1r(I,J) ...
+xtGy(Xvr_I(:,I,Jm),G1u(:,:,I,Jm),Xvr_J(:,I,Jm))...
./Jacu(I,Jm)./g1r(I,Jm);
brace2 =-xtGy(Xvr_J(:,I,J),G2r(:,:,I,J),Xvr_I(:,I,J))...
./Jacr(I,J)./g2r(I,J) ...
+xtGy(Xvr_J(:,Im,J),G2r(:,:,Im,J),Xvr_I(:,Im,J))...
./Jacr(Im,J)./g2r(Im,J) ...
+xtGy(Xvr_I(:,I,J),G2u(:,:,I,J),Xvr_I(:,I,J))...
./Jacu(I,J)./g2u(I,J) ...
-xtGy(Xvr_I(:,I,Jm),G2u(:,:,I,Jm),Xvr_I(:,I,Jm))...
./Jacu(I,Jm)./g2u(I,Jm);
testy(brace1,ind,'brace1')
testy(brace2,ind,'brace2')
M.Vx = shiftdim( ...
-squeeze(X_I)./(sqrt(g1).*Jac).*brace1 ...
-squeeze(X_J)./(sqrt(g2).*Jac).*brace2 ...
,-4)/patches.mmTime;
M.Vy = shiftdim( ...
-squeeze(Y_I)./(sqrt(g1).*Jac).*brace1 ...
-squeeze(Y_J)./(sqrt(g2).*Jac).*brace2 ...
,-4)/patches.mmTime;
testy(M.Vx ,4+ind,'M.Vx')
testy(M.Vy ,4+ind,'M.Vy')
%{
\end{matlab}
\end{subequations}
\begin{matlab}
%}
end% switch theMethod
%{
\end{matlab}
\subsection{Evaluate system differential equation}
Ask the user function for the time derivatives computed in
the array, overwrite its edge values with the dummy value of
zero (as \verb|ode15s| chokes on NaNs), then return to the
user\slash integrator as same sized array as input.
\begin{matlab}
%}
dudt = patches.fun(t,u,M,patches);
dudt([1 end],:,:,:,:,:) = 0;
dudt(:,[1 end],:,:,:,:) = 0;
dudt=[M.Vx(:); M.Vy(:); dudt(:)];
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
mmNonDiffPDE.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MoveMesh/mmNonDiffPDE.m
| 1,206 |
utf_8
|
ded09a422eb4981ce37cf704c78d2e51
|
% Microscale discretisation of a nonlinear diffusion PDE in
% 2D space (x,y) on moving 2D patches.
% AJR, Aug 2021 -- Sep 2021
%!TEX root = doc.tex
%{
\subsection{\texttt{mmNonDiffPDE():} (non)linear diffusion PDE inside moving patches}
As a microscale discretisation of \(u_t=\Vv\cdot\grad u+\delsq(u^3)\), code
\(\dot u_{ijkl} =\cdots +\frac1{\delta x^2} (u_{i+1,j,k,l}^3
-2u_{i,j,k,l}^3 +u_{i-1,j,k,l}^3) + \frac1{\delta y^2}
(u_{i,j+1,k,l}^3 -2u_{i,j,k,l}^3 +u_{i,j-1,k,l}^3)\).
\begin{matlab}
%}
function ut = mmNonDiffPDE(t,u,M,patches)
if nargin<3, global patches, end
u = squeeze(u); % reduce to 4D
Vx = shiftdim(M.Vx,2); % omit two singleton dimens
Vy = shiftdim(M.Vy,2); % omit two singleton dimens
dx = diff(patches.x(1:2)); % microgrid spacing
dy = diff(patches.y(1:2));
i = 2:size(u,1)-1; j = 2:size(u,2)-1; % interior patch points
ut = nan+u; % preallocate output array
ut(i,j,:,:) = ...
+Vx.*(u(i+1,j,:,:)-u(i-1,j,:,:))/(2*dx) ...
+Vy.*(u(i,j+1,:,:)-u(i,j-1,:,:))/(2*dy) ...
+diff(u(:,j,:,:),2,1)/dx^2 ...
+diff(u(i,:,:,:),2,2)/dy^2 ;
% +diff(u(:,j,:,:).^3,2,1)/dx^2 ...
% +diff(u(i,:,:,:).^3,2,2)/dy^2 ;
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
mmBurgersPDE.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MoveMesh/mmBurgersPDE.m
| 2,354 |
utf_8
|
d592a3874ab094fa21b653f27077e4b9
|
% mmBurgersPDE() is a microscale discretisation of Burgers'
% PDE on multiscale patches of a lattice x, when the patches
% move according to some scheme. AJR, Aug 2021
%!TEX root = doc.tex
%{
\subsection{\texttt{mmBurgersPDE()}: Burgers PDE inside a
moving mesh of patches}
For the evolving scalar field~\(u(t,x)\), we code a
microscale discretisation of Burgers' \pde\ \(u_t = \epsilon
u_{xx} -uu_x\), for say \(\epsilon=0.02\)\,, when the
patches of microscale lattice move with various
velocities~\(V\).
\begin{matlab}
%}
function ut = mmBurgersPDE(t,u,M,patches)
epsilon = 0.02;
%{
\end{matlab}
\paragraph{Generic input/output variables}
\begin{itemize}
\item \verb|t| (scalar) current time---not used here as the
\pde\ has no explicit time dependence (autonomous).
\item \verb|u| (\(n\times1\times1\times N\)) field values on
the patches of microscale lattice.
\item \verb|M| a struct of the following components.
\begin{itemize}
\item \verb|V| (\(1\times1\times1\times N\)) moving velocity of
the \(j\)th~patch.
\item \verb|D| (\(1\times1\times1\times N\)) displacement of
the \(j\)th~patch from the fixed spatial positions stored in
\verb|patches.x|---not used here as the \pde\ has no
explicit space dependence (homogeneous).
\end{itemize}
\item \verb|patches| struct of patch configuration
information.
\item \verb|ut| (\(n\times1\times1\times N\)) output
computed values of the time derivatives \(Du/Dt\) on the
patches of microscale lattice.
\end{itemize}
Here there is only one field variable, and one in the
ensemble, so for simpler coding of the \pde\ we squeeze them
out (no need to reshape when via \verb|mmPatchSys1|).
\begin{matlab}
%}
u=squeeze(u); % omit singleton dimensions
V=shiftdim(M.V,2); % omit two singleton dimens
%{
\end{matlab}
\paragraph{Burgers PDE}
In terms of the moving derivative \(Du/Dt:=u_t+Vu_x\) the
\pde\ becomes \(Du/Dt=\epsilon u_{xx}+(V-u)u_x\)\,. So code
for every patch that \(\dot u_{ij} =\frac\epsilon{h^2}
(u_{i+1,j}-2u_{i,j}+u_{i-1,j}) +(V_j-u_{ij})
\frac1{2h}(u_{i+1,j}-u_{i-1,j})\) at all interior lattice
points.
\begin{matlab}
%}
dx=diff(patches.x(1:2)); % microscale spacing
i=2:size(u,1)-1; % interior points in patches
ut=nan+u; % preallocate output array
ut(i,:) = epsilon*diff(u,2)/dx^2 ...
+(V-u(i,:)).*(u(i+1,:)-u(i-1,:))/(2*dx);
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
mmPatchSys1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MoveMesh/mmPatchSys1.m
| 11,231 |
utf_8
|
1adfa605d2346d08dd479dce644de6a6
|
% mmPatchSys1() provides an interface to time integrators
% for the dynamics on moving patches coupled across space. The
% system must be a lattice system such as a PDE
% discretisation. AJR, Aug 2021
%!TEX root = doc.tex
%{
\section{\texttt{mmPatchSys1()}: interface 1D space of
moving patches to time integrators}
\label{sec:mmPatchSys1}
To simulate in time with moving 1D spatial patches we need
to interface a user's time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function \verb|mmPatchSys1()| provides an interface.
Patch edge values are determined by macroscale
interpolation of the patch-centre or edge values.
Microscale heterogeneous systems may be accurately simulated
with this function via appropriate interpolation.
Communicate patch-design variables
(\cref{sec:configPatches1}) either via the global
struct~\verb|patches| or via an optional third argument
(except that this last is required for parallel computing of
\verb|spmd|).
\begin{matlab}
%}
function dudt = mmPatchSys1(t,u,patches)
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector of length $\verb|nPatch| +
\verb|nSubP| \cdot \verb|nVars| \cdot \verb|nEnsem| \cdot
\verb|nPatch|$ where there are $\verb|nVars| \cdot
\verb|nEnsem|$ field values at each of the points in the
$\verb|nSubP|\times \verb|nPatch|$ grid, and because of the
moving mesh there are an additional \verb|nPatch| patch
displacement values at its start.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches1()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,M,patches)| that computes the time derivatives
on the patchy lattice, where the \(j\)th~patch moves at
velocity~\(M.V_j\) and at current time is
displaced~\(M.D_j\) from the fixed reference position
in~\verb|.x|\,. The array~\verb|u| has size $\verb|nSubP|
\times \verb|nVars| \times \verb|nEnsem| \times
\verb|nPatch|$. Time derivatives should be computed into
the same sized array, then herein the patch edge values are
overwritten by zeros.
\item \verb|.x| is $\verb|nSubP| \times1 \times1 \times
\verb|nPatch|$ array of the spatial locations~$x_{i}$ of
the microscale grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on both macro- and
microscales ??
\item \verb|.Xlim| is two element vector of the (periodic)
spatial domain within which the patches are placed.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector of of time
derivatives, but with patch edge-values set to zero. It is
of total length $\verb|nPatch| + \verb|nSubP| \cdot
\verb|nVars| \cdot \verb|nEnsem| \cdot \verb|nPatch|$.
\end{itemize}
\begin{devMan}
\paragraph{Alternative estimates of derivatives}
The moving mesh depends upon estimates of the second
derivative of macroscale fields. Traditionally these are
obtained from the macroscale variations in the fields. But
with the patch scheme we can also estimate from the
sub-patch fields. As yet we have little idea which is
better. So here code three alternatives depending upon
\begin{matlab}
%}
subpatDerivs = 2;
%{
\end{matlab}
\begin{itemize}
\begin{figure}
\centering
\begin{tabular}{cc}
\parbox[b]{0.3\linewidth}{%
\caption{\label{fig:mm1dBurgersExampleMesh0}patch locations
as a function of time for the case \(\texttt{subpatDerivs} =
0\): these locations form a macroscale moving mesh. The
shock here should be moving but appears to get pinned.
These three are for \(u_0=0.3+\sin(2\pi x)\), spectral
interpolation, mesh \(\tau=0.8\)\,.}}
&\includegraphics[width=0.6\linewidth]{Figs/mm1dBurgersExampleMesh0}
\end{tabular}
\end{figure}
\item \verb|subpatDerivs=0|, implements classic moving mesh
algorithm obtaining estimates of the 2nd derivative at each
patch from the macroscale inter-patch field---the moving
shock is does not appear well represented (what about more
patches?);
\begin{figure}
\centering
\begin{tabular}{cc}
\parbox[b]{0.3\linewidth}{%
\caption{\label{fig:mm1dBurgersExampleMesh2}patch locations
as a function of time for the case \(\texttt{subpatDerivs} =
2\): these locations form a macroscale moving mesh. The
shock here moves nicely, and the patches do not appear to
overlap (much, or at all??). But what happens at
time~0.4??}}
&\includegraphics[width=0.6\linewidth]{Figs/mm1dBurgersExampleMesh2}
\end{tabular}
\end{figure}
\item \verb|subpatDerivs=2|, obtains estimates of the 2nd
derivative at each patch from the microscale sub-patch field
(potentially subject to round-off problems)---but appears to
track the shock OK;
\begin{figure}
\centering
\begin{tabular}{cc}
\parbox[b]{0.3\linewidth}{%
\caption{\label{fig:mm1dBurgersExampleMesh1}patch locations
as a function of time for the case \(\texttt{subpatDerivs} =
1\): these locations form a macroscale moving mesh. The
moving macroscale mesh of patches has some wacko oscillatory
instability!}}
&\includegraphics[width=0.6\linewidth]{Figs/mm1dBurgersExampleMesh1}
\end{tabular}
\end{figure}
\item \verb|subpatDerivs=1|, estimates the first derivative
from the microscale sub-patch field (I expect round-off
negligible), and then using macroscale differences to
estimate the 2nd derivative at points mid-way between
patches---seems to be subject to weird mesh oscillations.
\end{itemize}
\paragraph{Preliminaries}
Extract the \verb|nPatch| displacement values from the start
of the vectors of evolving variables. Reshape the rest as
the fields~\verb|u| in a 4D-array, and sets the edge values
from macroscale interpolation of centre-patch values.
\cref{sec:patchEdgeInt1} describes \verb|patchEdgeInt1()|.
\begin{matlab}
%}
nx= size(patches.x,1);
N = size(patches.x,4);
M.D = reshape(u(1:N),[1 1 1 N]);
u = patchEdgeInt1(u(N+1:end),patches);
%{
\end{matlab}
\paragraph{Moving mesh velocity}
Developing from standard moving meshes for \pde{}s
\cite[e.g.]{Budd2009, Huang10}, we follow
\cite{Maclean2021a}. There exists a set of macro-scale mesh
points~$X_j(t):=X_j^0+D_j(t)$ (at the centre) of each patch
with associated field values, say
$U_j(t):=\overline{u_{ij}(t)}$.
\begin{matlab}
%}
X = mean(patches.x,1)+M.D;
if subpatDerivs==0, U = mean(u,1); end
%{
\end{matlab}
Then for every patch~\(j\) we set \(H_j:=X_{j+1}-X_j\) for
periodic patch indices~\(j\)
\begin{matlab}
%}
j=1:N; jp=[2:N 1]; jm=[N 1:N-1];
H = X(:,:,:,jp)-X(:,:,:,j);
H(N) = H(N)+diff(patches.Xlim);
%{
\end{matlab}
we discretise a moving mesh \pde\ for node locations~$X_j$
with field values~$U_j$ via the second derivative w.r.t.~\(x\),
estimated by
\begin{subequations} \label{mmDisc}
\begin{equation}
U''_{j} := \frac2{H_j+H_{j-1}}\left[ \frac{U_{j+1} -
U_j}{H_j} - \frac{U_{j} - U_{j-1}}{H_{j-1}} \right] .
\end{equation}
Here \(\verb|U2|:=\Uv''_j\),
\begin{matlab}
%}
switch subpatDerivs
case 0
U2 = ( (U(:,:,:,jp)-U(:,:,:,j))./H(:,:,:,j) ...
-(U(:,:,:,j)-U(:,:,:,jm))./H(:,:,:,jm) ...
)*2./(H(:,:,:,j)+H(:,:,:,jm));
%{
\end{matlab}
Alternatively, use the sub-patch field to determine the
second derivatives. It should be more accurate, unless
round-off error becomes significant. However, it may focus
too much on the microscale, and not enough on the macroscale
variation.
\begin{itemize}
\item In the case of non-edgy interpolation, since we here
use near edge-values, the derivative is essentially a
numerical derivative of the interpolation scheme.
\item In the case of edgy-interpolation, \emph{and} if
periodic heterogeneous micro-structure, then we must have an
\emph{even number of periods} in every patch so that the
second differences steps are done over a whole number of
micro-scale periods.
\end{itemize}
\begin{matlab}
%}
case 2
idel=floor((nx-1)/2);
dx=diff(patches.x([1 idel+1]));
U2=diff(u(1:idel:nx,:,:,:),2,1)/dx^2;
if rem(nx,2)==0 % use average when even sub-patch points
U2=( U2+diff(u(2:idel:nx,:,:,:),2,1)/dx^2 )/2;
end%if nx even
%{
\end{matlab}
Alternatively, use the sub-patch field to determine the
first derivatives at each patch, and then a macroscale
derivative to determine second derivative at mid-gaps
inter-patch. The sub-patch first derivative is a numerical
estimate of the derivative of the inter-patch interpolation
scheme as it only uses edge-values, values which come
directly from the patch interpolation scheme.
\begin{matlab}
%}
case 1
dx = diff(patches.x([1 nx]));
U2 = diff(u([1 nx],:,:,:),1)/dx;
U2 = (U2(:,:,:,jp)-U2(:,:,:,j))./H(:,:,:,j);
end%switch subpatDerivs
%{
\end{matlab}
Compute a norm over ensemble and all variables
(arbitrarily?? chose the mean square norm here, so here
\verb|U2| denotes both 2nd derivative and the square, here
\(\verb|U2|:= \|\Uv''_j\|^2\)).
\begin{matlab}
%}
U2 = squeeze( mean(mean( abs(U2).^2 ,2),3) );
H = squeeze(H);
%{
\end{matlab}
Having squeezed out all microscale information, the
coefficient
\begin{equation}
\label{mmAl}
\alpha := \max\left\{ 1\C \left[\frac{1}{b-a}\sum_{j}
H_{j-1} \frac12 \left({U''_{j}}^{2/3} +
{U''_{j-1}}^{2/3}\right)\right]^3 \right\}
\end{equation}
Rather than \(\max(1,\cdot)\) surely better to use something
smooth like~\(\sqrt{1+\cdot^2}\)??
\begin{matlab}
%}
if subpatDerivs==1 % mid-point integration
alpha = sum( H.*U2.^(1/3) )/sum(H);
else % trapezoidal integration
alpha = sum( H(jm).*( U2(j).^(1/3)+U2(jm).^(1/3) ))/2/sum(H);
end%if
%alpha = max(1,alpha^3);
alpha = sqrt(1+alpha^6);
%{
\end{matlab}
Then the importance function (alternatively at patches or at
mid-gap inter-patch)
\begin{equation}
\label{mmR}
\rho_j := \left(1 + \frac{1}{\alpha} {U''_{j}}^2 \right)^{1/3},
\end{equation}
\begin{matlab}
%}
rho = ( 1+U2/alpha ).^(1/3);
%{
\end{matlab}
For every patch, we move all micro-grid points according to
the following velocity of the notional macro-scale node of
that patch:
\begin{equation}
\label{mmX}
V_j:= \de t{X_j} = \frac{(N-1)^2}{2\rho_j \tau } \left[
(\rho_{j+1}+\rho_j) H_j - (\rho_j + \rho_{j-1}) H_{j-1}
\right].
\end{equation}
\begin{matlab}
%}
M.V = nan+M.D; % allocate storage
if subpatDerivs==1 % mid-point derivative
M.V(:) = ( rho(j).*H(j) -rho(jm).*H(jm) ) ...
./(rho(j)+rho(jm)) *((N-1)^2*2/patches.mmTime);
else % derivative of linear interpolation
M.V(:) = ( (rho(jp)+rho(j)).*H(j) -(rho(j)+rho(jm)).*H(jm) ) ...
./rho(j) *((N-1)^2/2/patches.mmTime);
end%if
%{
\end{matlab}
\end{subequations}
\paragraph{Control overlapping of patches?} Surely cannot
yet be done because the interpolation is in index space, so
that adjoining patches generally have different field values
interpolated to their edges. Need to interpolate in
physical space in order to get the interpolated field to
`merge' adjoining patches.
\paragraph{Evaluate system differential equation}
Ask the user function for the advected time derivatives on
the moving patches, overwrite its edge values with the dummy
value of zero (since \verb|ode15s| chokes on NaNs), then
return to the user\slash integrator as a vector.
\begin{matlab}
%}
dudt=patches.fun(t,u,M,patches);
dudt([1 end],:,:,:) = 0;
dudt=[M.V(:); dudt(:)];
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
mm2dExample.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MoveMesh/mm2dExample.m
| 9,008 |
utf_8
|
a64d0699cbdd1be97f6526f8e6569531
|
% mm2dExample: moving patches of Burgers PDE
%!TEX root = doc.tex
%{
\section{\texttt{mm2dExample}: example of moving
patches in 2D for nonlinear diffusion}
\label{sec:mm2dExample}
The code here shows two ways to use moving patches in 2D.
Plausible generalisations from the 1D code to this 2D code is the case \verb|adhoc|.
The alternative \verb|Huang98| aims to implement the method of \cite{Huang98}.
\begin{matlab}
%}
clear all
global theMethod
if 0, theMethod = 'adhoc',
else theMethod = 'Huang98', end
%{
\end{matlab}
However, \verb|mmPatchSys2()| has far too many ad hoc assumptions,
so fix those before exploring predictions here.
Establish global patch data struct to interface with a
function coding the microscale.
Prefer EdgyInt as we suspect it performs better
for moving meshes.
Using \verb|nxy=3| means that there are no sub-patch modes, all modes are those of the macro-diffusion and the macro-mesh movement.
There are \(N_x+N_y\) zero eigenvalues associated with the mesh movement.
And there are \(N_xN_y\) slow eigenvalues of the diffusion (one of them looks like zero badly affected by round-off to be as big as \(10^{-4}\) or so).
So far we generally see the macro-diffusion is poorly perturbed by the mesh movement in that there are some diffusion modes with imaginary part up to five.
\begin{matlab}
%}
global patches
nxy=3 % =3 means no sub-patch dynamics
Nx=7, Ny=5
patches = configPatches2(@mmNonDiffPDE,[-3 3 -2 2], nan ...
, [Nx Ny], 0, 0.1, nxy ,'EdgyInt',true);
patches.mmTime=0.03;
patches.Xlim=[-3 3 -2 2];
Npts = Nx*Ny;
%{
\end{matlab}
The above two amendments to \verb|patches| should eventually be
part of the configuration function.
\paragraph{Decide the moving mesh time parameter}
%Here for \(\epsilon=0.02\).
%\begin{itemize}
%\item Would be best if the moving mesh was no stiffer than
%the stiffest microscale sub-patch mode. These would both be
%the zig-zag modes.
%\begin{itemize}
%\item Here the mesh \pde\ is \(X_t=(N^2/\tau)X_{jj}\) so its
%zig-zag mode decays with rate \(4N^2/\tau\)\,.
%\item Here the patch width is~\(h=0.2/15=1/75\), and so the
%microscale step is \(\delta=h/4=1/300\). Hence the
%diffusion \(u_t=\epsilon u_{xx}\) has zig-zag mode decaying
%at rate \(4\epsilon/\delta^2\).
%\end{itemize}
%So, surely best to have \(4N^2/\tau \lesssim 4\epsilon
%/\delta^2\), that is, \(\tau \gtrsim N^2\delta^2 /\epsilon
%\approx 0.1\).
%
%\item But also we do not want the slowest modes of the
%moving mesh to obfuscate the system's macroscale modes---the
%macroscale zig-zag.
%\begin{itemize}
%\item The slowest moving mesh mode has wavenumber in~\(j\)
%of~\(2\pi/N\), and hence rate of decay \((N^2/\tau)
%(2\pi/N)^2 =4\pi^2/\tau\).
%\item The fastest zig-zag mode of the system \(U_t=\epsilon
%U_{xx}\) on step~\(H\) has decay rate \(4\epsilon/H^2\).
%\end{itemize}
%So best if \(4\pi^2/\tau \gtrsim 4\epsilon/H^2\), that is,
%\(\tau \lesssim \pi^2H^2 /\epsilon \approx 2\)\,.
%
%(Computations indicate need \(\tau<0.8\)??)
%\end{itemize}
\paragraph{Spectrum of the moving patch system}
Compute the spectrum based upon the linearisation about some
state: \(u={}\)constant with \(D=0\) are equilibria;
otherwise the computation is about a 'quasi-equilibrium' on
the `fast-time'.
\begin{matlab}
%}
global ind, ind=2
evals=[];
patches.mmTime = patches.mmTime/0.95;
for iv=1:4
patches.mmTime = 0.95*patches.mmTime;
%
u00 = 0.1
u0 = u00+sin(0*patches.x*pi/3+0*patches.y*pi/2);
u0([1 end],:,:)=nan; u0(:,[1 end],:)=nan;
u0 = [zeros(2*Npts,1); u0(:)];
f0 = mmPatchSys2(0,u0);
normf0 = norm(f0)
%if normf0>1e-9, error('Jacobian: u0 is not equilibrium'),end
%{
\end{matlab}
But we must only use the dynamic variables, so let's find
where they are.
\begin{matlab}
%}
i=find(~isnan( u0(:) ));
nJac=length(i)
%{
\end{matlab}
Construct Jacobian with numerical differentiation.
\begin{matlab}
%}
deltau=1e-7;
Jac=nan(nJac);
for j=1:nJac
uj=u0; uj(i(j))=uj(i(j))+deltau;
fj = mmPatchSys2(0,uj);
Jac(:,j)=(fj(i)-f0(i))/deltau;
end
%{
\end{matlab}
Compute and plot the spectrum with non-linear axis scaling
(\cref{fig:mm2dExampleSpec}).
\begin{matlab}
%}
eval=eig(Jac);
[~,k]=sort(-real(eval));
eval=eval(k);
nZero = sum(abs(real(eval))<1e-3)
nSlow = sum(-100<real(eval))-nZero
%eSlowest = eval(1:30) %(0+(1:2:nSlow))
%eFast = eval([nZero+nSlow+1 end])
evals=[evals eval];
end%iv-loop
%{
\end{matlab}
\paragraph{Plot spectrum}
Choose whether to save some plots, or not.
\begin{matlab}
%}
global OurCf2eps
OurCf2eps = false;
%{
\end{matlab}
Draw spectrum on quasi-log axes.
\begin{matlab}
%}
figure(3),clf
hp = plot(real(evals),imag(evals),'.');
xlabel('Re\lambda'), ylabel('Im\lambda')
quasiLogAxes(hp,1,1);
ifOurCf2eps([mfilename theMethod 'Spec'])
return%%%%%%%%%%%%%%
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:mm2dExampleadhocSpec}spectrum
of the \emph{adhoc} moving mesh 2D diffusion system (about \(u=0.1\)). The
clusters are: right real, macroscale diffusion modes with some neutral mesh deformations;
left real, moving mesh and sub-patch modes. Coloured dots are `trails' for \(\tau\)~reducing by~5\% between each, starting from blue dots.}
\includegraphics[scale=0.85]{Figs/mm2dExampleadhocSpec}
\end{figure}
\begin{figure}
\centering \caption{\label{fig:mm2dExampleHuang98Spec}spectrum
of the \emph{Huang98} moving mesh 2D diffusion system (about \(u=0.1\)).
Currently there are badly unstable modes. The
clusters are: \dotfill\ confused.}
\includegraphics[scale=0.85]{Figs/mm2dExampleHuang98Spec}
\end{figure}
\paragraph{Simulate in time}
Set an initial condition of a perturbed-Gaussian using
auto-replication of the spatial grid.
\begin{matlab}
%}
u0 = exp(-patches.x.^2-patches.y.^2);
u0 = 1+0*u0.*(0.9+0.0*rand(size(u0)));
D0 = zeros(2*Npts,1);
%{
\end{matlab}
Integrate in time to $t=2$ using standard functions. In
\Matlab\ \verb|ode15s| would be natural as the patch scheme
is naturally stiff, but \verb|ode23| is quicker \cite
[Fig.~4] {Maclean2020a}. Ask for output at non-uniform
times because the diffusion slows.
\begin{matlab}
%}
disp('Simulating nonlinear diffusion h_t=(h^3)_xx+(h^3)_yy')
tic
[ts,us] = ode23(@mmPatchSys2,2*linspace(0,1).^2,[D0;u0(:)]);
cpuTime = toc
%{
\end{matlab}
\paragraph{Plots}
Extract data from time simulation. Be wary that the patch-edge values do not change from initial, so either set to~\verb|NaN|, or set via interpolation.
\begin{matlab}
%}
nTime=length(ts);
Ds=reshape(us(:,1:2*Npts).',1,1,Nx,Ny,2,nTime);
us=reshape(us(:,2*Npts+1:end).',nxy,nxy,Nx,Ny,nTime);
us([1 end],:,:,:)=nan; us(:,[1 end],:,:)=nan; % nan edges
%{
\end{matlab}
Choose macro-mesh plot or micro-surf-patch plots.
\begin{matlab}
%}
if 1
%{
\end{matlab}
Plot the movement of the mesh, with the field vertical, at
the centre of each patch.
\begin{matlab}
%}
%% section marker for macro-mesh plot execution
figure(1),clf, colormap(0.8*hsv)
Us=shiftdim( mean(mean(us,1,'omitnan'),2,'omitnan') ,2);
Xs=shiftdim(mean(patches.x),4);
Ys=shiftdim(mean(patches.y),4);
for k=1:nTime
Xk=Xs+shiftdim(Ds(:,:,:,:,1,k),2);
Yk=Ys+shiftdim(Ds(:,:,:,:,2,k),2);
if k==1,
hand=mesh(Xk,Yk,Us(:,:,k));
ylabel('space y'),xlabel('space x'),zlabel('mean field U')
axis([patches.Xlim 0 1]), caxis([0 1])
colorbar
if 0, view(0,90) % vertical view
else view(-25,60) % 3D perspective
end
else
set(hand,'XData',Xk,'YData',Yk ...
,'ZData',Us(:,:,k),'CData',Us(:,:,k))
end
legend(['time =' num2str(ts(k),4)],'Location','north')
if rem(k,31)==1, ifOurCf2eps([mfilename theMethod num2str(k)]), end
pause(0.05)
end% for each time
else%if macro-mesh or micro-surf
%{
\end{matlab}
Plot the movement of the patches, with the field vertical in
each patch.
\begin{matlab}
%}
%% section marker for patch-surf plot execution
figure(2),clf, colormap(0.8*hsv)
xs=reshape(patches.x,nxy,1,Nx,1);
ys=reshape(patches.y,1,nxy,1,Ny);
for k=1:nTime
xk=xs+0*ys+Ds(:,:,:,:,1,k);
yk=ys+0*xs+Ds(:,:,:,:,2,k);
uk=reshape(permute(us(:,:,:,:,k),[1 3 2 4]),nxy*Nx,nxy*Ny);
xk=reshape(permute(xk,[1 3 2 4]),nxy*Nx,nxy*Ny);
yk=reshape(permute(yk,[1 3 2 4]),nxy*Nx,nxy*Ny);
if k==1,
hand=surf(xk,yk,uk);
ylabel('space y'),xlabel('space x'),zlabel('field u(x,y,t)')
axis([patches.Xlim 0 1]), caxis([0 1])
colorbar
else
set(hand,'XData',xk,'YData',yk,'ZData',uk,'CData',uk)
end
legend(['time =' num2str(ts(k),4)],'Location','north')
% if rem(k,31)==1, ifOurCf2eps([mfilename theMethod num2str(k)]), end
pause(0.05)
end% for each time
%%
end%if macro-mesh or micro-surf
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:mm2dExample}field
$u(x,t)$ of the moving patch scheme applied to nonlinear diffusion~\pde.}
\begin{tabular}{@{}cc@{}}
\includegraphics[width=0.47\linewidth]{Figs/mm2dExample1}
&
\includegraphics[width=0.47\linewidth]{Figs/mm2dExample32}
\\
\includegraphics[width=0.47\linewidth]{Figs/mm2dExample63}
&
\includegraphics[width=0.47\linewidth]{Figs/mm2dExample94}
\end{tabular}
\end{figure}
Fin.
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
mm1dBurgersExample.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MoveMesh/mm1dBurgersExample.m
| 6,382 |
utf_8
|
e41c7863cd3185ecc93835286bc7fdd7
|
% mm1dBurgersExample: moving patches of Burgers PDE
%!TEX root = doc.tex
%{
\section{\texttt{mm1dBurgersExample}: example of moving
patches for Burgers' PDE}
\label{sec:mm1dBurgersExample}
The code here shows one way to get started: a user's script
may have the following three steps (left-right arrows denote
function recursion).
\begin{enumerate}\def\itemsep{-1ex}
\item configPatches1
\item ode15s integrator \into\ mmPatchSys1 \into\ user's PDE
\item process results
\end{enumerate}
The simulation seems perfectly happy for the patches to move
so that they overlap in the shock! and then separate again
as the shock decays.
Establish global patch data struct to point to and interface
with a function coding Burgers' \pde: to be solved on
$1$-periodic domain, with fifteen patches, spectral
interpolation couples the patches, each patch of half-size
ratio~$0.2$, and with five microscale points forming each
patch. Prefer EdgyInt as we suspect it performs better
for moving meshes.
\begin{matlab}
%}
clear all
global patches
patches = configPatches1(@mmBurgersPDE,[0 1], nan, 15, 0, 0.2, 5 ...
,'EdgyInt',true);
patches.mmTime=0.8;
patches.Xlim=[0 1];
%{
\end{matlab}
The above two amendments to \verb|patches| should eventually be
part of the configuration function.
\paragraph{Decide the moving mesh time parameter}
Here for \(\epsilon=0.02\).
\begin{itemize}
\item Would be best if the moving mesh was no stiffer than
the stiffest microscale sub-patch mode. These would both be
the zig-zag modes.
\begin{itemize}
\item Here the mesh \pde\ is \(X_t=(N^2/\tau)X_{jj}\) so its
zig-zag mode decays with rate~\(4N^2/\tau\)\,.
\item Here the patch width is~\(h=0.2/15=1/75\), and so the
microscale step is \(\delta=h/4=1/300\). Hence the
diffusion \(u_t=\epsilon u_{xx}\) has zig-zag mode decaying
at rate~\(4\epsilon/\delta^2\).
\end{itemize}
So, surely best to have \(4N^2/\tau \lesssim 4\epsilon
/\delta^2\), that is, \(\tau \gtrsim N^2\delta^2 /\epsilon
\approx 0.1\).
\item But also we do not want the slowest modes of the
moving mesh to obfuscate the system's macroscale modes---the
macroscale zig-zag.
\begin{itemize}
\item The slowest moving mesh mode has wavenumber in~\(j\)
of~\(2\pi/N\), and hence rate of decay \((N^2/\tau)
(2\pi/N)^2 =4\pi^2/\tau\).
\item The fastest zig-zag mode of the system \(U_t=\epsilon
U_{xx}\) on step~\(H\) has decay rate \(4\epsilon/H^2\).
\end{itemize}
So best if \(4\pi^2/\tau \gtrsim 4\epsilon/H^2\), that is,
\(\tau \lesssim \pi^2H^2 /\epsilon \approx 2\)\,.
(Computations indicate need \(\tau<0.8\)??)
\end{itemize}
\paragraph{Simulate in time}
Set usual sinusoidal initial condition. Add some microscale
randomness that decays within time of~\(0.01\), but also
seeds slight macroscale variations.
\begin{matlab}
%}
u0 = 0.3+sin(2*pi*patches.x)+0.0*randn(size(patches.x));
N = size(patches.x,4)
D0 = zeros(N,1);
%ud=mmPatchSys1(0,[D0;u0(:)],patches);
%return
%{
\end{matlab}
Simulate in time using a standard stiff integrator and the
interface function \verb|mmPatchSys1()|
(\cref{sec:mmPatchSys1}).
\begin{matlab}
%}
tic
[ts,us] = ode15s(@mmPatchSys1,linspace(0,0.8),[D0;u0(:)]);
cpuTime = toc
%{
\end{matlab}
\paragraph{Plots}
Choose whether to save some plots, or not.
\begin{matlab}
%}
global OurCf2eps
OurCf2eps = false;
%{
\end{matlab}
Plot the movement of the mesh, the centre of each patch, as
a function of time: spatial domain horizontal, and time
vertical.
\begin{matlab}
%}
figure(1),clf
Ds=us(:,1:N);
Xs=shiftdim(mean(patches.x),2);
plot(Xs+Ds,ts), ylabel('time t'),xlabel('space x')
title('Burgers PDE: patch locations over time')
ifOurCf2eps([mfilename 'Mesh'])
%{
\end{matlab}
Animate the simulation using only the microscale values
interior to the patches: set $x$-edges to \verb|nan| to
leave the gaps. \cref{fig:mmBurgersExample} illustrates an
example simulation in time generated by the patch scheme
applied to Burgers'~\pde.
\begin{matlab}
%}
uLim=[min(u0(:)) max(u0(:))]
us=us(:,N+1:end).';
us(abs(us)>2)=nan;
x0s=squeeze(patches.x); x0s([1 end],:)=nan;
%% section break to ease rerun of animation
figure(2),clf
for i=1:length(ts)
xs=x0s+Ds(i,:);
if i==1, hpts=plot(xs(:),us(:,i),'.');
ylabel('field u'), xlabel('space x')
axis([0 1 uLim])
else set(hpts,'XData',xs(:),'YData',us(:,i));
end
legend(['time = ' num2str(ts(i),2)],'Location','north')
if rem(i,31)==1, ifOurCf2eps([mfilename num2str(i)]), end
pause(0.09)
end
%%
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:mmBurgersExample}field
$u(x,t)$ of the moving patch scheme applied to Burgers'~\pde.}
\begin{tabular}{@{}cc@{}}
\includegraphics[width=0.47\linewidth]{Figs/mmBurgersExample1}
&
\includegraphics[width=0.47\linewidth]{Figs/mmBurgersExample32}
\\
\includegraphics[width=0.47\linewidth]{Figs/mmBurgersExample63}
&
\includegraphics[width=0.47\linewidth]{Figs/mmBurgersExample94}
\end{tabular}
\end{figure}
\paragraph{Spectrum of the moving patch system}
Compute the spectrum based upon the linearisation about some
state: \(u={}\)constant with \(D=0\) are equilibria;
otherwise the computation is about a 'quasi-equilibrium' on
the `fast-time'.
\begin{matlab}
%}
u0 = 0.1+0*sin(2*pi*patches.x);
u0 = [zeros(N,1); u0(:)];
f0 = mmPatchSys1(0,u0);
normf0=norm(f0)
%{
\end{matlab}
But we must only use the dynamic variables, so let's find
where they are.
\begin{matlab}
%}
xs=patches.x; xs([1 end],:,:,:)=nan;
i=find(~isnan( [zeros(N,1);xs(:)] ));
nJac=length(i)
%{
\end{matlab}
Construct Jacobian with numerical differentiation.
\begin{matlab}
%}
deltau=1e-7;
Jac=nan(nJac);
for j=1:nJac
uj=u0; uj(i(j))=uj(i(j))+deltau;
fj = mmPatchSys1(0,uj);
Jac(:,j)=(fj(i)-f0(i))/deltau;
end
%{
\end{matlab}
Compute and plot the spectrum with non-linear axis scaling
(\cref{fig:mm1dBurgersExampleSpec}).
\begin{matlab}
%}
eval=-sort(-eig(Jac))
figure(3),clf
hp=plot(real(eval),imag(eval),'.');
xlabel('Re\lambda'), ylabel('Im\lambda')
quasiLogAxes(hp,10,1)
ifOurCf2eps([mfilename 'Spec'])
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:mm1dBurgersExampleSpec}spectrum
of the moving mesh Burgers' system (about \(u=0.1\)). The
four clusters are: right, macroscale Burgers' \pde\ (complex
conjugate pairs); left complex pairs, sub-patch \pde\ modes;
left real, moving mesh modes.}
\includegraphics[scale=0.85]{Figs/mm1dBurgersExampleSpec}
\end{figure}
Fin.
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/patchEdgeInt3.m
| 28,529 |
utf_8
|
994388f67e0cb617d206311ba65f6db3
|
% patchEdgeInt3() provides the interpolation across 3D space
% for 3D patches of simulations of a smooth lattice system
% such as PDE discretisations. AJR, Aug 2020 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt3()}: sets 3D patch
face values from 3D macroscale interpolation}
\label{sec:patchEdgeInt3}
Couples 3D patches across 3D space by computing their face
values via macroscale interpolation. Assumes patch face
values are determined by macroscale interpolation of the
patch centre-plane values \cite[]{Roberts2011a,
Bunder2019d}, or patch next-to-face values which appears
better \cite[]{Bunder2020a}. This function is primarily
used by \verb|patchSys3()| but is also useful for user
graphics. \footnote{Script \texttt{patchEdgeInt3test.m}
verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global
struct~\verb|patches|.
\begin{matlab}
%}
function u = patchEdgeInt3(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP1| \cdot \verb|nSubP2| \cdot \verb|nSubP3|
\cdot \verb|nPatch1| \cdot \verb|nPatch2| \cdot
\verb|nPatch3|$ multiscale spatial grid on the
$\verb|nPatch1| \cdot \verb|nPatch2| \cdot \verb|nPatch3|$
array of patches.
\item \verb|patches| a struct set by \verb|configPatches3()|
which includes the following information.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP1| \times1 \times1 \times1
\times1 \times \verb|nPatch1| \times1 \times1 $ array of the
spatial locations~$x_{iI}$ of the microscale grid points in
every patch. Currently it \emph{must} be an equi-spaced
lattice on the microscale index~$i$, but may be variable
spaced in macroscale index~$I$.
\item \verb|.y| is similarly $1\times \verb|nSubP2| \times1
\times1 \times1 \times1 \times \verb|nPatch2| \times1$ array
of the spatial locations~$y_{jJ}$ of the microscale grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on the microscale index~$j$, but may be
variable spaced in macroscale index~$J$.
\item \verb|.z| is similarly $1 \times1 \times \verb|nSubP3|
\times1 \times1 \times1 \times1 \times \verb|nPatch3|$ array
of the spatial locations~$z_{kK}$ of the microscale grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on the microscale index~$k$, but may be
variable spaced in macroscale index~$K$.
\item \verb|.ordCC| is order of interpolation, currently
only $\{0,2,4,\ldots\}$
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left, right, top, bottom, front and back boundaries so
interpolation is via divided differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation. Currently must be zero.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation in each of the
$x,y,z$-directions---when invoking a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation: true, from opposite-edge
next-to-edge values (often preserves symmetry); false, from
centre cross-patch values (near original scheme).
\item \verb|.nEdge|, three elements, the width of edge
values set by interpolation at the \(x,y,z\)-face regions,
respectively, of each patch (default is one all
\(x,y,z\)-faces).
\item \verb|.nEnsem| the number of realisations in the
ensemble.
\item \verb|.parallel| whether serial or parallel.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 8D array, $\verb|nSubP1| \cdot
\verb|nSubP2| \cdot \verb|nSubP3| \cdot \verb|nVars| \cdot
\verb|nEnsem| \cdot \verb|nPatch1| \cdot \verb|nPatch2|
\cdot \verb|nPatch3|$, of the fields with face values set by
interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[~,~,nz,~,~,~,~,Nz] = size(patches.z);
[~,ny,~,~,~,~,Ny,~] = size(patches.y);
[nx,~,~,~,~,Nx,~,~] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round( numel(u)/numel(patches.x) ...
/numel(patches.y)/numel(patches.z)/nEnsem );
assert(numel(u) == nx*ny*nz*Nx*Ny*Nz*nVars*nEnsem ...
,'patchEdgeInt3: input u has wrong size for parameters')
u = reshape(u,[nx ny nz nVars nEnsem Nx Ny Nz]);
%{
\end{matlab}
For the moment assume the physical domain is either
macroscale periodic or macroscale rectangle so that the
coupling formulas are simplest. These index vectors point
to patches and, if periodic, their six immediate neighbours.
\begin{matlab}
%}
I=1:Nx; Ip=mod(I,Nx)+1; Im=mod(I-2,Nx)+1;
J=1:Ny; Jp=mod(J,Ny)+1; Jm=mod(J-2,Ny)+1;
K=1:Nz; Kp=mod(K,Nz)+1; Km=mod(K-2,Nz)+1;
%{
\end{matlab}
\paragraph{Implement multiple width edges by folding}
Subsample~\(x,y,z\) coordinates, noting it is only differences
that count \emph{and} the microgrid~\(x,y,z\) spacing must be
uniform.
\begin{matlab}
%}
%x = patches.x;
%if patches.nEdge(1)>1
% m = patches.nEdge(1);
% x = x(1:m:nx,:,:,:,:,:,:,:);
% nx = nx/m;
% u = reshape(u,m,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
% nVars = nVars*m;
% u = reshape( permute(u,[2:4 1 5:9]) ...
% ,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
%end%if patches.nEdge(1)
%y = patches.y;
%if patches.nEdge(2)>1
% m = patches.nEdge(2);
% y = y(:,1:m:ny,:,:,:,:,:,:);
% ny = ny/m;
% u = reshape(u,nx,m,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
% nVars = nVars*m;
% u = reshape( permute(u,[1 3:4 2 5:9]) ...
% ,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
%end%if patches.nEdge(2)
%z = patches.z;
%if patches.nEdge(3)>1
% m = patches.nEdge(3);
% z = z(:,:,1:m:nz,:,:,:,:,:);
% nz = nz/m;
% u = reshape(u,nx,ny,m,nz,nVars,nEnsem,Nx,Ny,Nz);
% nVars = nVars*m;
% u = reshape( permute(u,[1:2 4 3 5:9]) ...
% ,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
%end%if patches.nEdge(3)
x = patches.x;
y = patches.y;
z = patches.z;
if mean(patches.nEdge)>1
mx = patches.nEdge(1);
my = patches.nEdge(2);
mz = patches.nEdge(3);
x = x(1:mx:nx,:,:,:,:,:,:,:);
y = y(:,1:my:ny,:,:,:,:,:,:);
z = z(:,:,1:mz:nz,:,:,:,:,:);
nx = nx/mx;
ny = ny/my;
nz = nz/mz;
u = reshape(u,mx,nx,my,ny,mz,nz,nVars,nEnsem,Nx,Ny,Nz);
nVars = nVars*mx*my*mz;
u = reshape( permute(u,[2:2:6 1:2:5 7:11]) ...
,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
end%if patches.nEdge
%{
\end{matlab}
The centre of each patch (as \verb|nx|, \verb|ny| and
\verb|nz| are odd for centre-patch interpolation) is at
indices
\begin{matlab}
%}
i0 = round((nx+1)/2);
j0 = round((ny+1)/2);
k0 = round((nz+1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches in each direction.
\begin{matlab}
%}
rx = patches.ratio(1);
ry = patches.ratio(2);
rz = patches.ratio(3);
%{
\end{matlab}
\subsubsection{Lagrange interpolation gives patch-face values}
Compute centred differences of the mid-patch values for the
macro-interpolation, of all fields. Here the domain is
macro-periodic.
\begin{matlab}
%}
ordCC = patches.ordCC;
if ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in face-edge and corner values. Start with
\(x\)-direction, and give most documentation for that case
as the others are essentially the same.
\paragraph{\(x\)-normal face values} The patch-edge values
are either interpolated from the next-to-edge-face values,
or from the centre-cross-plane values (not the patch-centre
value itself as that seems to have worse properties in
general). Have not yet implemented core averages.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u([2 nx-1],2:(ny-1),2:(nz-1),:,:,I,J,K);
else % interpolate centre-cross values
U = u(i0,2:(ny-1),2:(nz-1),:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Just in case any last array dimension(s) are one, we force a
padding of the sizes, then adjoin the extra dimension for
the subsequent array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in these arrays. When parallel, in order
to preserve the distributed array structure we use an index
at the end for the differences.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
% dmux(:,:,:,:,:,I,:,:,1) = (Ux(:,:,:,:,:,Ip,:,:) +Ux(:,:,:,:,:,Im,:,:))/2; % \mu
% dmux(:,:,:,:,:,I,:,:,2) = (Ux(:,:,:,:,:,Ip,:,:) -Ux(:,:,:,:,:,Im,:,:)); % \delta
% Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
% dmuy(:,:,:,:,:,:,J,:,1) = (Ux(:,:,:,:,:,:,Jp,:)+Ux(:,:,:,:,:,:,Jm,:))/2; % \mu
% dmuy(:,:,:,:,:,:,J,:,2) = (Ux(:,:,:,:,:,:,Jp,:)-Ux(:,:,:,:,:,:,Jm,:)); % \delta
% Jp = Jp(Jp); Jm = Jm(Jm); % increase shifts to \pm2
% dmuz(:,:,:,:,:,:,:,K,1) = (Ux(:,:,:,:,:,:,:,Kp)+Ux(:,:,:,:,:,:,:,Km))/2; % \mu
% dmuz(:,:,:,:,:,:,:,K,2) = (Ux(:,:,:,:,:,:,:,Kp)-Ux(:,:,:,:,:,:,:,Km)); % \delta
% Kp = Kp(Kp); Km = Km(Km); % increase shifts to \pm2
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,I,:,:,1) = (U(:,:,:,:,:,Ip,:,:) ...
-U(:,:,:,:,:,Im,:,:))/2; %\mu\delta
dmu(:,:,:,:,:,I,:,:,2) = (U(:,:,:,:,:,Ip,:,:) ...
-2*U(:,:,:,:,:,I,:,:) +U(:,:,:,:,:,Im,:,:)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,I,:,:,k) = dmu(:,:,:,:,:,Ip,:,:,k-2) ...
-2*dmu(:,:,:,:,:,I,:,:,k-2) +dmu(:,:,:,:,:,Im,:,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet face values for
each patch \cite[]{Roberts06d, Bunder2013b}, using the weights
pre-computed by \verb|configPatches3()|. Here interpolate to
specified order.
For the case where next-to-face values interpolate to the
opposite face-values: when we have an ensemble of
configurations, different configurations might be coupled to
each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to|, \verb|patches.bo|,
\verb|patches.fr| and \verb|patches.ba|.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(nx,2:(ny-1),2:(nz-1),:,patches.ri,I,:,:) ...
= U(1,:,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,1),-8).*dmu(1,:,:,:,:,:,:,:,:) ,9);
u(1 ,2:(ny-1),2:(nz-1),:,patches.le,I,:,:) ...
= U(k,:,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,1),-8).*dmu(k,:,:,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\paragraph{\(y\)-normal face values} Interpolate from either
the next-to-edge-face values, or the centre-cross-plane
values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,[2 ny-1],2:(nz-1),:,:,I,J,K);
else % interpolate centre-cross values
U = u(:,j0,2:(nz-1),:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,:,J,:,1) = (U(:,:,:,:,:,:,Jp,:) ...
-U(:,:,:,:,:,:,Jm,:))/2; %\mu\delta
dmu(:,:,:,:,:,:,J,:,2) = (U(:,:,:,:,:,:,Jp,:) ...
-2*U(:,:,:,:,:,:,J,:) +U(:,:,:,:,:,:,Jm,:)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,:,J,:,k) = dmu(:,:,:,:,:,:,Jp,:,k-2) ...
-2*dmu(:,:,:,:,:,:,J,:,k-2) +dmu(:,:,:,:,:,:,Jm,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches3()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(:,ny,2:(nz-1),:,patches.to,:,J,:) ...
= U(:,1,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,2),-8).*dmu(:,1,:,:,:,:,:,:,:) ,9);
u(:,1 ,2:(nz-1),:,patches.bo,:,J,:) ...
= U(:,k,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,2),-8).*dmu(:,k,:,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\paragraph{\(z\)-normal face values} Interpolate from either
the next-to-edge-face values, or the centre-cross-plane
values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,:,[2 nz-1],:,:,I,J,K);
else % interpolate centre-cross values
U = u(:,:,k0,:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,:,:,K,1) = (U(:,:,:,:,:,:,:,Kp) ...
-U(:,:,:,:,:,:,:,Km))/2; %\mu\delta
dmu(:,:,:,:,:,:,:,K,2) = (U(:,:,:,:,:,:,:,Kp) ...
-2*U(:,:,:,:,:,:,:,K) +U(:,:,:,:,:,:,:,Km)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,:,:,K,k) = dmu(:,:,:,:,:,:,:,Kp,k-2) ...
-2*dmu(:,:,:,:,:,:,:,K,k-2) +dmu(:,:,:,:,:,:,:,Km,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches3()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(:,:,nz,:,patches.fr,:,:,K) ...
= U(:,:,1,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,3),-8).*dmu(:,:,1,:,:,:,:,:,:) ,9);
u(:,:,1 ,:,patches.ba,:,:,K) ...
= U(:,:,k,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,3),-8).*dmu(:,:,k,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\subsubsection{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
We interpolate in terms of the patch index, $I$~say, not
directly in space. As the macroscale fields are $N$-periodic
in the patch index~$I$, the macroscale Fourier transform
writes the centre-patch values as $U_I=\sum_{k}C_ke^{ik2\pi
I/N}$. Then the face-patch values $U_{I\pm r}
=\sum_{k}C_ke^{ik2\pi/N(I\pm r)} =\sum_{k}C'_ke^{ik2\pi
I/N}$ where $C'_k =C_ke^{ikr2\pi/N}$. For $N$~patches we
resolve `wavenumbers' $|k|<N/2$, so set row vector
$\verb|ks| =k2\pi/N$ for `wavenumbers' $\mathcode`\,="213B
k=(0,1, \ldots, k_{\max}, -k_{\max}, \ldots, -1)$ for
odd~$N$, and $\mathcode`\,="213B k=(0,1, \ldots, k_{\max},
\pm(k_{\max}+1) -k_{\max}, \ldots, -1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches3|
tests there are an even number of patches). Then the
patch-ratio is effectively halved. The patch faces are near
the middle of the gaps and swapped.
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
error('staggered grid not yet implemented??')
v=nan(size(u)); % currently to restore the shape of u
u=cat(3,u(:,1:2:nPatch,:),u(:,2:2:nPatch,:));
stagShift=reshape(0.5*[ones(nVars,1);-ones(nVars,1)],1,1,[]);
iV=[nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r=r/2; % ratio effectively halved
nPatch=nPatch/2; % halve the number of patches
nVars=nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in face-edge and corner values. Start with
\(x\)-direction, and give most documentation for that case
as the others are essentially the same. Need these indices
of patch interior.
\begin{matlab}
%}
ix = 2:nx-1; iy = 2:ny-1; iz = 2:nz-1;
%{
\end{matlab}
\paragraph{\(x\)-normal face values} Now set wavenumbers
into a vector at the correct dimension. In the case of
even~$N$ these compute the $+$-case for the highest
wavenumber zig-zag mode, $\mathcode`\,="213B k=(0,1, \ldots,
k_{\max}, +(k_{\max}+1) -k_{\max}, \ldots, -1)$.
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
kr = shiftdim( rx*2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ,-4);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields. Unless doing patch-edgy
interpolation when FT the next-to-face values. If there are
an even number of points, then if complex, treat as positive
wavenumber, but if real, treat as cosine. When using an
ensemble of configurations, different configurations might
be coupled to each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to|, \verb|patches.bo|,
\verb|patches.fr| and \verb|patches.ba|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(i0,iy,iz,:,:,:,:,:) ,[],6);
Cp = Cm;
else
Cm = fft( u( 2,iy,iz ,:,patches.le,:,:,:) ,[],6);
Cp = fft( u(nx-1,iy,iz ,:,patches.ri,:,:,:) ,[],6);
end%if ~patches.EdgyInt
%{
\end{matlab}
Now invert the Fourier transforms to complete interpolation.
Enforce reality when appropriate.
\begin{matlab}
%}
u(nx,iy,iz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],6) );
u( 1,iy,iz,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],6) );
%{
\end{matlab}
\paragraph{\(y\)-normal face values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Ny-1)/2);
kr = shiftdim( ry*2*pi/Ny*(mod((0:Ny-1)+kMax,Ny)-kMax) ,-5);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,j0,iz,:,:,:,:,:) ,[],7);
Cp = Cm;
else
Cm = fft( u(:,2 ,iz ,:,patches.bo,:,:,:) ,[],7);
Cp = fft( u(:,ny-1,iz ,:,patches.to,:,:,:) ,[],7);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,ny,iz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],7) );
u(:, 1,iz,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],7) );
%{
\end{matlab}
\paragraph{\(z\)-normal face values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Nz-1)/2);
kr = shiftdim( rz*2*pi/Nz*(mod((0:Nz-1)+kMax,Nz)-kMax) ,-6);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,:,k0,:,:,:,:,:) ,[],8);
Cp = Cm;
else
Cm = fft( u(:,:,2 ,:,patches.ba,:,:,:) ,[],8);
Cp = fft( u(:,:,nz-1 ,:,patches.fr,:,:,:) ,[],8);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,:,nz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],8) );
u(:,:, 1,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],8) );
%{
\end{matlab}
\begin{matlab}
%}
end% if ordCC>0
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|px|, \verb|py|
and~\verb|pz| (potentially different in the different
directions!), and hence size of the (forward) divided
difference tables in~\verb|F|~(9D) for interpolating to
left/right, top/bottom, and front/back faces. Because of the
product-form of the patch grid, and because we are doing
\emph{only} either edgy interpolation or cross-patch
interpolation (\emph{not} just the centre patch value), the
interpolations are all 1D interpolations.
\begin{matlab}
%}
if patches.ordCC<1
px = Nx-1; py = Ny-1; pz = Nz-1;
else px = min(patches.ordCC,Nx-1);
py = min(patches.ordCC,Ny-1);
pz = min(patches.ordCC,Nz-1);
end
% interior indices of faces (ix n/a)
ix=2:nx-1; iy=2:ny-1; iz=2:nz-1;
%{
\end{matlab}
\subsubsection{\(x\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-face values are because their
values are to interpolate to the opposite face of each
patch. \todo{Have no plans to implement core averaging as yet.}
\begin{matlab}
%}
F = nan(patches.EdgyInt+1,ny-2,nz-2,nVars,nEnsem,Nx,Ny,Nz,px+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u([nx-1 2],iy,iz,:,:,:,:,:);
X = x([nx-1 2],:,:,:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(i0,iy,iz,:,:,:,:,:);
X = x(i0,:,:,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
\paragraph{Form tables of divided differences} Compute
tables of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable, and
across ensemble, and in both directions, and for all three
types of faces (left/right, top/bottom, and front/back).
Recursively find all divided differences in the respective
direction.
\begin{matlab}
%}
for q = 1:px
i = 1:Nx-q;
F(:,:,:,:,:,i,:,:,q+1) ...
= ( F(:,:,:,:,:,i+1,:,:,q)-F(:,:,:,:,:,i,:,:,q)) ...
./(X(:,:,:,:,:,i+q,:,:) -X(:,:,:,:,:,i,:,:));
end
%{
\end{matlab}
\paragraph{Interpolate with divided differences} Now
interpolate to find the face-values on left/right faces
at~\verb|Xface| for every interior~\verb|Y,Z|.
\begin{matlab}
%}
Xface = x([1 nx],:,:,:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|i| are those of the left face of
each interpolation stencil, because the table is of forward
differences. This alternative: the case of order~\(p_x\),
\(p_y\) and~\(p_z\) interpolation across the domain,
asymmetric near the boundaries of the rectangular domain.
\begin{matlab}
%}
i = max(1,min(1:Nx,Nx-ceil(px/2))-floor(px/2));
Uface = F(:,:,:,:,:,i,:,:,px+1);
for q = px:-1:1
Uface = F(:,:,:,:,:,i,:,:,q) ...
+(Xface-X(:,:,:,:,:,i+q-1,:,:)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,iy,iz,:,patches.le,:,:,:) = Uface(1,:,:,:,:,:,:,:);
u(nx,iy,iz,:,patches.ri,:,:,:) = Uface(2,:,:,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(y\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,patches.EdgyInt+1,nz-2,nVars,nEnsem,Nx,Ny,Nz,py+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u(:,[ny-1 2],iz,:,:,:,:,:);
Y = y(:,[ny-1 2],:,:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(:,j0,iz,:,:,:,:,:);
Y = y(:,j0,:,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:py
j = 1:Ny-q;
F(:,:,:,:,:,:,j,:,q+1) ...
= ( F(:,:,:,:,:,:,j+1,:,q)-F(:,:,:,:,:,:,j,:,q)) ...
./(Y(:,:,:,:,:,:,j+q,:) -Y(:,:,:,:,:,:,j,:));
end
%{
\end{matlab}
Interpolate to find the top/bottom faces~\verb|Yface| for
every~\(x\) and interior~\(z\).
\begin{matlab}
%}
Yface = y(:,[1 ny],:,:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|j| are those of the bottom face
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
j = max(1,min(1:Ny,Ny-ceil(py/2))-floor(py/2));
Uface = F(:,:,:,:,:,:,j,:,py+1);
for q = py:-1:1
Uface = F(:,:,:,:,:,:,j,:,q) ...
+(Yface-Y(:,:,:,:,:,:,j+q-1,:)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,1 ,iz,:,patches.bo,:,:,:) = Uface(:,1,:,:,:,:,:,:);
u(:,ny,iz,:,patches.to,:,:,:) = Uface(:,2,:,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(z\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,ny,patches.EdgyInt+1,nVars,nEnsem,Nx,Ny,Nz,pz+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u(:,:,[nz-1 2],:,:,:,:,:);
Z = z(:,:,[nz-1 2],:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(:,:,k0,:,:,:,:,:);
Z = z(:,:,k0,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:pz
k = 1:Nz-q;
F(:,:,:,:,:,:,:,k,q+1) ...
= ( F(:,:,:,:,:,:,:,k+1,q)-F(:,:,:,:,:,:,:,k,q)) ...
./(Z(:,:,:,:,:,:,:,k+q) -Z(:,:,:,:,:,:,:,k));
end
%{
\end{matlab}
Interpolate to find the face-values on front/back
faces~\verb|Zface| for every~\(x,y\).
\begin{matlab}
%}
Zface = z(:,:,[1 nz],:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|k| are those of the bottom face
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
k = max(1,min(1:Nz,Nz-ceil(pz/2))-floor(pz/2));
Uface = F(:,:,:,:,:,:,:,k,pz+1);
for q = pz:-1:1
Uface = F(:,:,:,:,:,:,:,k,q) ...
+(Zface-Z(:,:,:,:,:,:,:,k+q-1)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,:,1 ,:,patches.fr,:,:,:) = Uface(:,:,1,:,:,:,:,:);
u(:,:,nz,:,patches.ba,:,:,:) = Uface(:,:,2,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{Optional NaNs for safety}
We want a user to set outer face values on the extreme
patches according to the microscale boundary conditions that
hold at the extremes of the domain. Consequently, unless testing, override
their computed interpolation values with~\verb|NaN|.
\begin{matlab}
%}
if isfield(patches,'intTest')&&patches.intTest
else % usual case
u( 1,:,:,:,:, 1,:,:) = nan;
u(nx,:,:,:,:,Nx,:,:) = nan;
u(:, 1,:,:,:,:, 1,:) = nan;
u(:,ny,:,:,:,:,Ny,:) = nan;
u(:,:, 1,:,:,:,:, 1) = nan;
u(:,:,nz,:,:,:,:,Nz) = nan;
end%if
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic else
%{
\end{matlab}
\paragraph{Unfold multiple edges} No need to restore~\(x,y,z\).
\begin{matlab}
%}
if mean(patches.nEdge)>1
nVars = nVars/(mx*my*mz);
u = reshape( u ,nx,ny,nz,mx,my,mz,nVars,nEnsem,Nx,Ny,Nz);
nx = nx*mx;
ny = ny*my;
nz = nz*mz;
u = reshape( permute(u,[4 1 5 2 6 3 7:11]) ...
,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
end%if patches.nEdge
%{
\end{matlab}
Fin, returning the 8D array of field values with
interpolated faces.
\begin{matlab}
%}
end% function patchEdgeInt3
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
configPatches1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/configPatches1.m
| 24,736 |
utf_8
|
658f09fbcd57e0cafaf7592fe95529ef
|
% configPatches1() creates a data struct of the design of
% 1D patches for later use by the patch functions such as
% patchSys1(). AJR, Nov 2017 -- 23 Mar 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{configPatches1()}: configure spatial
patches in 1D}
\label{sec:configPatches1}
\localtableofcontents
Makes the struct~\verb|patches| for use by the patch\slash
gap-tooth time derivative\slash step function
\verb|patchSys1()|. \cref{sec:configPatches1eg} lists an
example of its use.
\begin{matlab}
%}
function patches = configPatches1(fun,Xlim,Dom ...
,nPatch,ordCC,dx,nSubP,varargin)
version = '2023-03-23';
%{
\end{matlab}
\paragraph{Input}
If invoked with no input arguments, then executes an example
of simulating Burgers' \pde---see \cref{sec:configPatches1eg}
for the example code.
\begin{itemize}
\item \verb|fun| is the name of the user function,
\verb|fun(t,u,patches)| or \verb|fun(t,u)| or
\verb|fun(t,u,patches,...)|, that computes time derivatives
(or time-steps) of quantities on the 1D micro-grid within
all the 1D~patches.
\item \verb|Xlim| give the macro-space spatial domain of the
computation, namely the interval $[ \verb|Xlim(1)|,
\verb|Xlim(2)|]$.
\item \verb|Dom| sets the type of macroscale conditions for
the patches, and reflects the type of microscale boundary
conditions of the problem. If \verb|Dom| is \verb|NaN| or
\verb|[]|, then the field~\verb|u| is macro-periodic in the
1D spatial domain, and resolved on equi-spaced patches. If
\verb|Dom| is a character string, then that specifies the
\verb|.type| of the following structure, with
\verb|.bcOffset| set to the default zero. Otherwise
\verb|Dom| is a structure with the following components.
\begin{itemize}
\item \verb|.type|, string, of either \verb|'periodic'| (the
default), \verb|'equispace'|, \verb|'chebyshev'|,
\verb|'usergiven'|. For all cases except \verb|'periodic'|,
users \emph{must} code into \verb|fun| the micro-grid
boundary conditions that apply at the left(right) edge of
the leftmost(rightmost) patches.
\item \verb|.bcOffset|, optional one or two element array,
in the cases of \verb|'equispace'| or \verb|'chebyshev'|
the patches are placed so the left\slash right macroscale
boundaries are aligned to the left\slash right edges of the
corresponding extreme patches, but offset by \verb|bcOffset|
of the sub-patch micro-grid spacing. For example, use
\verb|bcOffset=0| when applying Dirichlet boundary values on
the extreme edge micro-grid points, whereas use
\verb|bcOffset=0.5| when applying Neumann boundary conditions
halfway between the extreme edge micro-grid points.
\item \verb|.X|, optional array, in the case~\verb|'usergiven'|
it specifies the locations of the centres of the
\verb|nPatch| patches---the user is responsible it makes
sense.
\end{itemize}
\item \verb|nPatch| is the number of equi-spaced spatial
patches.
\item \verb|ordCC|, must be~$\geq -1$, is the `order' of
interpolation across empty space of the macroscale patch
values to the edge of the patches for inter-patch coupling:
where \verb|ordCC| of~$0$ or~$-1$ gives spectral
interpolation; and \verb|ordCC| being odd specifies
staggered spatial grids.
\item \verb|dx| (real) is usually the sub-patch micro-grid
spacing in~\(x\).
However, if \verb|Dom| is~\verb|NaN| (as for pre-2023), then
\verb|dx| actually is \verb|ratio|, namely the ratio of
(depending upon \verb|EdgyInt|) either the half-width or
full-width of a patch to the equi-spacing of the patch
mid-points---adjusted a little when $\verb|nEdge|>1$. So
either $\verb|ratio|=\tfrac12$ means the patches abut and
$\verb|ratio|=1$ is overlapping patches as in holistic
discretisation, or $\verb|ratio|=1$ means the patches abut.
Small~\verb|ratio| should greatly reduce computational time.
\item \verb|nSubP| is the number of equi-spaced microscale
lattice points in each patch. If not using \verb|EdgyInt|,
then $\verb|nSubP/nEdge|$ must be odd integer so that there
is/are centre-patch lattice point(s). So for the defaults
of $\verb|nEdge|=1$ and not \verb|EdgyInt|, then
\verb|nSubP| must be odd.
\item \verb|'nEdge'|, \emph{optional}, default=1, the number
of edge values set by interpolation at the edge regions of
each patch. The default is one (suitable for microscale
lattices with only nearest neighbour interactions).
\item \verb|EdgyInt|, true/false, \emph{optional},
default=false. If true, then interpolate to left\slash
right edge-values from right\slash left next-to-edge values.
If false or omitted, then interpolate from centre-patch
values.
\item \verb|nEnsem|, \emph{optional-experimental},
default one, but if more, then an ensemble over this
number of realisations.
\item \verb|hetCoeffs|, \emph{optional}, default empty.
Supply a 1D or 2D array of microscale heterogeneous
coefficients to be used by the given microscale \verb|fun|
in each patch. Say the given array~\verb|cs| is of size
$m_x\times n_c$, where $n_c$~is the number of different sets
of coefficients. The coefficients are to be the same for
each and every patch; however, macroscale variations are
catered for by the $n_c$~coefficients being $n_c$~parameters
in some macroscale formula.
\begin{itemize}
\item If $\verb|nEnsem|=1$, then the array of coefficients
is just tiled across the patch size to fill up each patch,
starting from the first point in each patch. Best accuracy
usually obtained when the periodicity of the coefficients
is a factor of \verb|nSubP-2*nEdge| for \verb|EdgyInt|, or
a factor of \verb|(nSubP-nEdge)/2| for not \verb|EdgyInt|.
\item If $\verb|nEnsem|>1$ (value immaterial), then reset
$\verb|nEnsem|:=m_x$ and construct an ensemble of all
$m_x$~phase-shifts of the coefficients. In this scenario,
the inter-patch coupling couples different members in the
ensemble. When \verb|EdgyInt| is true, and when the
coefficients are diffusivities\slash elasticities, then this
coupling cunningly preserves symmetry.
\end{itemize}
\item \verb|nCore|, \emph{optional-experimental}, default
one, but if more, and only for non-EdgyInt, then
interpolates from an average over the core of a patch, a
core of size ??. Then edge values are set according to
interpolation of the averages?? or so that average at edges
is the interpolant??
\item \verb|'parallel'|, true/false, \emph{optional},
default=false. If false, then all patch computations are on
the user's main \textsc{cpu}---although a user may well
separately invoke, say, a \textsc{gpu} to accelerate
sub-patch computations.
If true, and it requires that you have \Matlab's Parallel
Computing Toolbox, then it will distribute the patches over
multiple \textsc{cpu}s\slash cores. In \Matlab, only one
array dimension can be split in the distribution, so it
chooses the one space dimension~$x$. A user may
correspondingly distribute arrays with property
\verb|patches.codist|, or simply use formulas invoking the
preset distributed arrays \verb|patches.x|. If a user has
not yet established a parallel pool, then a `local' pool is
started.
\end{itemize}
\paragraph{Output} The struct \verb|patches| is created and
set with the following components. If no output variable is
provided for \verb|patches|, then make the struct available
as a global variable.\footnote{When using \texttt{spmd}
parallel computing, it is generally best to avoid global
variables, and so instead prefer using an explicit output
variable.}
\begin{matlab}
%}
if nargout==0, global patches, end
patches.version = version;
%{
\end{matlab}
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| or \verb|fun(t,u)| or
\verb|fun(t,u,patches,...)|, that computes the time
derivatives (or steps) on the patchy lattice.
\item \verb|.ordCC| is the specified order of inter-patch
coupling.
\item \verb|.periodic|: either true, for interpolation on
the macro-periodic domain; or false, for general
interpolation by divided differences over non-periodic
domain or unevenly distributed patches.
\item \verb|.stag| is true for interpolation using only odd
neighbouring patches as for staggered grids, and false for
the usual case of all neighbour coupling.
\item \verb|.Cwtsr| and \verb|.Cwtsl|, only for
macro-periodic conditions, are the $\verb|ordCC|$-vector of
weights for the inter-patch interpolation onto the right and
left edges (respectively) with patch:macroscale ratio as
specified or as derived from~\verb|dx|.
\item \verb|.x| (4D) is $\verb|nSubP| \times1 \times1
\times \verb|nPatch|$ array of the regular spatial
locations~$x_{iI}$ of the $i$th~microscale grid point in
the $I$th~patch.
\item \verb|.ratio|, only for macro-periodic conditions, is
the size ratio of every patch.
\item \verb|.nEdge| is, for each patch, the number of edge
values set by interpolation at the edge regions of each
patch.
\item \verb|.le|, \verb|.ri| determine inter-patch coupling
of members in an ensemble. Each a column vector of
length~\verb|nEnsem|.
\item \verb|.cs| either
\begin{itemize}
\item \verb|[]| 0D, or
\item if $\verb|nEnsem|=1$, $(\verb|nSubP(1)|-1)\times
n_c$ 2D array of microscale heterogeneous coefficients, or
\item if $\verb|nEnsem|>1$, $(\verb|nSubP(1)|-1) \times
n_c\times m_x$ 3D array of $m_x$~ensemble of phase-shifts
of the microscale
heterogeneous coefficients.
\end{itemize}
\item \verb|.parallel|, logical: true if patches are
distributed over multiple \textsc{cpu}s\slash cores for the
Parallel Computing Toolbox, otherwise false (the default is
to activate the \emph{local} pool).
\item \verb|.codist|, \emph{optional}, describes the
particular parallel distribution of arrays over the active
parallel pool.
\end{itemize}
\subsection{If no arguments, then execute an example}
\label{sec:configPatches1eg}
\begin{matlab}
%}
if nargin==0
disp('With no arguments, simulate example of Burgers PDE')
%{
\end{matlab}
The code here shows one way to get started: a user's script
may have the following three steps (``\into'' denotes
function recursion).
\begin{enumerate}\def\itemsep{-1.5ex}
\item configPatches1
\item ode15s integrator \into patchSys1 \into user's PDE
\item process results
\end{enumerate}
Establish global patch data struct to point to and interface
with a function coding Burgers' \pde: to be solved on
$2\pi$-periodic domain, with eight patches, spectral
interpolation couples the patches, with micro-grid
spacing~$0.06$, and with seven microscale points forming
each patch.
\begin{matlab}
%}
global patches
patches = configPatches1(@BurgersPDE, [0 2*pi], ...
'periodic', 8, 0, 0.06, 7);
%{
\end{matlab}
Set some initial condition, with some microscale randomness.
\begin{matlab}
%}
u0=0.3*(1+sin(patches.x))+0.1*randn(size(patches.x));
%{
\end{matlab}
Simulate in time using a standard stiff integrator and the
interface function \verb|patchSys1()|
(\cref{sec:patchSys1}).
\begin{matlab}
%}
if ~exist('OCTAVE_VERSION','builtin')
[ts,us] = ode15s( @patchSys1,[0 0.5],u0(:));
else % octave version
[ts,us] = odeOcts(@patchSys1,[0 0.5],u0(:));
end
%{
\end{matlab}
Plot the simulation using only the microscale values
interior to the patches: either set $x$-edges to \verb|nan|
to leave the gaps; or use \verb|patchEdgyInt1| to
re-interpolate correct patch edge values and thereby join
the patches. \cref{fig:config1Burgers} illustrates an
example simulation in time generated by the patch scheme
applied to Burgers'~\pde.
\begin{matlab}
%}
figure(1),clf
if 1, patches.x([1 end],:,:,:)=nan; us=us.';
else us=reshape(patchEdgyInt1(us.'),[],length(ts));
end
mesh(ts,patches.x(:),us)
view(60,40), colormap(0.7*hsv)
title('Burgers PDE: patches in space, continuous time')
xlabel('time t'), ylabel('space x'), zlabel('u(x,t)')
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:config1Burgers}field
$u(x,t)$ of the patch scheme applied to Burgers'~\pde.}
\includegraphics[scale=0.85]{configPatches1}
\end{figure}
Upon finishing execution of the example, optionally save
the graph to be shown in \cref{fig:config1Burgers}, then
exit this function.
\begin{matlab}
%}
ifOurCf2eps(mfilename)
return
end%if nargin==0
%{
\end{matlab}
\IfFileExists{../Patch/BurgersPDE.m}{\input{../Patch/BurgersPDE.m}}{}
\IfFileExists{../Patch/odeOcts.m}{\input{../Patch/odeOcts.m}}{}
\begin{devMan}
\subsection{Parse input arguments and defaults}
\begin{matlab}
%}
p = inputParser;
fnValidation = @(f) isa(f, 'function_handle'); %test for fn name
addRequired(p,'fun',fnValidation);
addRequired(p,'Xlim',@isnumeric);
%addRequired(p,'Dom'); % nothing yet decided
addRequired(p,'nPatch',@isnumeric);
addRequired(p,'ordCC',@isnumeric);
addRequired(p,'dx',@isnumeric);
addRequired(p,'nSubP',@isnumeric);
addParameter(p,'nEdge',1,@isnumeric);
addParameter(p,'EdgyInt',false,@islogical);
addParameter(p,'nEnsem',1,@isnumeric);
addParameter(p,'hetCoeffs',[],@isnumeric);
addParameter(p,'parallel',false,@islogical);
addParameter(p,'nCore',1,@isnumeric);
parse(p,fun,Xlim,nPatch,ordCC,dx,nSubP,varargin{:});
%{
\end{matlab}
Set the optional parameters.
\begin{matlab}
%}
patches.nEdge = p.Results.nEdge;
patches.EdgyInt = p.Results.EdgyInt;
patches.nEnsem = p.Results.nEnsem;
cs = p.Results.hetCoeffs;
patches.parallel = p.Results.parallel;
patches.nCore = p.Results.nCore;
%{
\end{matlab}
Check parameters.
\begin{matlab}
%}
assert(Xlim(1)<Xlim(2) ...
,'two entries of Xlim must be ordered increasing')
assert((mod(ordCC,2)==0)|(patches.nEdge==1) ...
,'Cannot yet have nEdge>1 and staggered patch grids')
assert(3*patches.nEdge<=nSubP ...
,'too many edge values requested')
assert(rem(nSubP,patches.nEdge)==0 ...
,'nSubP must be integer multiple of nEdge')
if ~patches.EdgyInt, assert(rem(nSubP/patches.nEdge,2)==1 ...
,'for non-edgyInt, nSubP/nEdge must be odd integer')
end
if (patches.nEnsem>1)&(patches.nEdge>1)
warning('not yet tested when both nEnsem and nEdge non-one')
end
if patches.nCore>1
warning('nCore>1 not yet tested in this version')
end
%{
\end{matlab}
For compatibility with pre-2023 functions, if parameter
\verb|Dom| is \verb|Nan|, then we set the \verb|ratio| to
be the value of the so-called \verb|dx| parameter.
\begin{matlab}
%}
if ~isstruct(Dom), pre2023=isnan(Dom);
else pre2023=false; end
if pre2023, ratio=dx; dx=nan; end
%{
\end{matlab}
Default macroscale conditions are periodic with evenly
spaced patches.
\begin{matlab}
%}
if isempty(Dom), Dom=struct('type','periodic'); end
if (~isstruct(Dom))&isnan(Dom), Dom=struct('type','periodic'); end
%{
\end{matlab}
If \verb|Dom| is a string, then just set type to that
string, and then get corresponding defaults for others
fields.
\begin{matlab}
%}
if ischar(Dom), Dom=struct('type',Dom); end
%{
\end{matlab}
Check what is and is not specified, and provide default of
Dirichlet boundaries if no \verb|bcOffset| specified when
needed.
\begin{matlab}
%}
patches.periodic=false;
switch Dom.type
case 'periodic'
patches.periodic=true;
if isfield(Dom,'bcOffset')
warning('bcOffset not available for Dom.type = periodic'), end
if isfield(Dom,'X')
warning('X not available for Dom.type = periodic'), end
case {'equispace','chebyshev'}
if ~isfield(Dom,'bcOffset'), Dom.bcOffset=[0;0]; end
if length(Dom.bcOffset)==1
Dom.bcOffset=repmat(Dom.bcOffset,2,1); end
if isfield(Dom,'X')
warning('X not available for Dom.type = equispace or chebyshev')
end
case 'usergiven'
if isfield(Dom,'bcOffset')
warning('bcOffset not available for usergiven Dom.type'), end
assert(isfield(Dom,'X'),'X required for Dom.type = usergiven')
otherwise
error([Dom.type ' is unknown Dom.type'])
end%switch Dom.type
%{
\end{matlab}
\subsection{The code to make patches and interpolation}
First, store the pointer to the time derivative function in
the struct.
\begin{matlab}
%}
patches.fun=fun;
%{
\end{matlab}
Second, store the order of interpolation that is to provide
the values for the inter-patch coupling conditions. Spectral
coupling is \verb|ordCC| of~$0$ and~$-1$.
\begin{matlab}
%}
assert((ordCC>=-1) & (floor(ordCC)==ordCC), ...
'ordCC out of allowed range integer>=-1')
%{
\end{matlab}
For odd~\verb|ordCC|, interpolate based upon odd
neighbouring patches as is useful for staggered grids.
\begin{matlab}
%}
patches.stag=mod(ordCC,2);
ordCC=ordCC+patches.stag;
patches.ordCC=ordCC;
%{
\end{matlab}
Check for staggered grid and periodic case.
\begin{matlab}
%}
if patches.stag, assert(mod(nPatch,2)==0, ...
'Require an even number of patches for staggered grid')
end
%{
\end{matlab}
Third, set the centre of the patches in the macroscale grid
of patches, depending upon \verb|Dom.type|.
\begin{matlab}
%}
switch Dom.type
%{
\end{matlab}
%: case periodic
The periodic case is evenly spaced within the spatial domain.
Store the size ratio in \verb|patches|.
\begin{matlab}
%}
case 'periodic'
X=linspace(Xlim(1),Xlim(2),nPatch+1);
DX=X(2)-X(1);
X=X(1:nPatch)+diff(X)/2;
pEI=patches.EdgyInt;% abbreviation
pnE=patches.nEdge; % abbreviation
if pre2023, dx = ratio*DX/(nSubP-pnE*(1+pEI))*(2-pEI);
else ratio = dx/DX*(nSubP-pnE*(1+pEI))/(2-pEI); end
patches.ratio=ratio;
%{
\end{matlab}
In the case of macro-periodicity, precompute the weightings
to interpolate field values for coupling.
\todo{Might sometime extend to coupling via derivative values.}
\begin{matlab}
%}
if ordCC>0
[Cwtsr,Cwtsl] = patchCwts(ratio,ordCC,patches.stag);
patches.Cwtsr = Cwtsr; patches.Cwtsl = Cwtsl;
end
%{
\end{matlab}
%: case equispace
The equi-spaced case is also evenly spaced but with the
extreme edges aligned with the spatial domain boundaries,
modified by the offset.
%\todo{This warning needs refinement for multi-edges??}
\begin{matlab}
%}
case 'equispace'
X=linspace(Xlim(1)+((nSubP-1)/2-Dom.bcOffset(1))*dx ...
,Xlim(2)-((nSubP-1)/2-Dom.bcOffset(2))*dx ,nPatch);
DX=diff(X(1:2));
width=(1+patches.EdgyInt)/2*(nSubP-1-patches.EdgyInt)*dx;
if DX<width*0.999999
warning('too many equispace patches (double overlapping)')
end
%{
\end{matlab}
%: case chebyshev
The Chebyshev case is spaced according to the Chebyshev
distribution in order to reduce macro-interpolation errors,
\(X_i \propto -\cos(i\pi/N)\), but with the extreme edges
aligned with the spatial domain boundaries, modified by the
offset, and modified by possible `boundary layers'.
\footnote{ However, maybe overlapping patches near a
boundary should be viewed as some sort of spatial analogue
of the `christmas tree' of projective integration and its
projection to a slow manifold. Here maybe the overlapping
patches allow for a `christmas tree' approach to the
boundary layers. Needs to be explored??}
\begin{matlab}
%}
case 'chebyshev'
halfWidth=dx*(nSubP-1)/2;
X1 = Xlim(1)+halfWidth-Dom.bcOffset(1)*dx;
X2 = Xlim(2)-halfWidth+Dom.bcOffset(2)*dx;
% X = (X1+X2)/2-(X2-X1)/2*cos(linspace(0,pi,nPatch));
%{
\end{matlab}
Search for total width of `boundary layers' so that in the
interior the patches are non-overlapping Chebyshev. But
the width for assessing overlap of patches is the following
variable \verb|width|. We need to find~\verb|b|, the number of patches `glued' together at the boundaries.
\begin{matlab}
%}
pEI=patches.EdgyInt;% abbreviation
pnE=patches.nEdge; % abbreviation
width=(1+pEI)/2*(nSubP-pnE-pEI*pnE)*dx;
for b=0:2:nPatch-2
DXmin=(X2-X1-b*width)/2*( 1-cos(pi/(nPatch-b-1)) );
if DXmin>width, break, end
end%for
if DXmin<width*0.999999
warning('too many Chebyshev patches (mid-domain overlap)')
end
%{
\end{matlab}
Assign the centre-patch coordinates.
\begin{matlab}
%}
X = [ X1+(0:b/2-1)*width ...
(X1+X2)/2-(X2-X1-b*width)/2*cos(linspace(0,pi,nPatch-b)) ...
X2+(1-b/2:0)*width ];
%{
\end{matlab}
%: case usergiven
The user-given case is entirely up to a user to specify, we
just force it to have the correct shape of a row.
\begin{matlab}
%}
case 'usergiven'
X = reshape(Dom.X,1,[]);
end%switch Dom.type
%{
\end{matlab}
Fourth, construct the microscale grid in each patch, centred
about the given mid-points~\verb|X|. Reshape the grid to be
4D to suit dimensions (micro,Vars,Ens,macro).
\begin{matlab}
%}
xs = dx*( (1:nSubP)-mean(1:nSubP) );
patches.x = reshape( xs'+X ,nSubP,1,1,nPatch);
%{
\end{matlab}
\subsection{Set ensemble inter-patch communication}
For \verb|EdgyInt| or centre interpolation respectively,
\begin{itemize}
\item the right-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to left-edge~\verb|le|,
and
\item the left-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to~\verb|re|.
\end{itemize}
\verb|re| and \verb|li| are `transposes' of each other as
\verb|re(li)=le(ri)| are both \verb|1:nEnsem|.
Alternatively, one may use the statement
\begin{verbatim}
c=hankel(c(1:nSubP-1),c([nSubP 1:nSubP-2]));
\end{verbatim}
to \emph{correspondingly} generates all phase shifted copies
of microscale heterogeneity (see \verb|homoDiffEdgy1| of
\cref{sec:homoDiffEdgy1}).
The default is nothing shifty. This setting reduces the
number of if-statements in function \verb|patchEdgeInt1()|.
\begin{matlab}
%}
nE = patches.nEnsem;
patches.le = 1:nE;
patches.ri = 1:nE;
%{
\end{matlab}
However, if heterogeneous coefficients are supplied via
\verb|hetCoeffs|, then do some non-trivial replications.
First, get microscale periods, patch size, and replicate
many times in order to subsequently sub-sample: \verb|nSubP|
times should be enough. If \verb|cs| is more then 2D, then
the higher-dimensions are reshaped into the 2nd dimension.
\begin{matlab}
%}
if ~isempty(cs)
[mx,nc] = size(cs);
nx = nSubP(1);
cs = repmat(cs,nSubP,1);
%{
\end{matlab}
If only one member of the ensemble is required, then
sub-sample to patch size, and store coefficients in
\verb|patches| as is.
\begin{matlab}
%}
if nE==1, patches.cs = cs(1:nx-1,:); else
%{
\end{matlab}
But for $\verb|nEnsem|>1$ an ensemble of
$m_x$~phase-shifts of the coefficients is constructed from
the over-supply. Here code phase-shifts over the
periods---the phase shifts are like Hankel-matrices.
\begin{matlab}
%}
patches.nEnsem = mx;
patches.cs = nan(nx-1,nc,mx);
for i = 1:mx
is = (i:i+nx-2);
patches.cs(:,:,i) = cs(is,:);
end
patches.cs = reshape(patches.cs,nx-1,nc,[]);
%{
\end{matlab}
Further, set a cunning left\slash right realisation of
inter-patch coupling. The aim is to preserve symmetry in
the system when also invoking \verb|EdgyInt|. What this
coupling does without \verb|EdgyInt| is unknown. Use
auto-replication.
\begin{matlab}
%}
patches.le = mod((0:mx-1)'+mod(nx-2,mx),mx)+1;
patches.ri = mod((0:mx-1)'-mod(nx-2,mx),mx)+1;
%{
\end{matlab}
Issue warning if the ensemble is likely to be affected by
lack of scale separation. Need to justify this and the
arbitrary threshold more carefully??
\begin{matlab}
%}
if ratio*patches.nEnsem>0.9, warning( ...
'Probably poor scale separation in ensemble of coupled phase-shifts')
scaleSeparationParameter = ratio*patches.nEnsem
end
%{
\end{matlab}
End the two if-statements.
\begin{matlab}
%}
end%if-else nEnsem>1
end%if not-empty(cs)
%{
\end{matlab}
\paragraph{If parallel code} then first assume this is not
within an \verb|spmd|-environment, and so we invoke
\verb|spmd...end| (which starts a parallel pool if not
already started). At this point, the global \verb|patches|
is copied for each worker processor and so it becomes
\emph{composite} when we distribute any one of the fields.
Hereafter, {\em all fields in the global variable
\verb|patches| must only be referenced within an
\verb|spmd|-environment.}%
\footnote{If subsequently outside spmd, then one must use
functions like \texttt{getfield(patches\{1\},'a')}.}
\begin{matlab}
%}
if patches.parallel
% theparpool=gcp()
spmd
%{
\end{matlab}
Second, choose to slice parallel workers in the spatial
direction.
\begin{matlab}
%}
pari = 1;
patches.codist=codistributor1d(3+pari);
%{
\end{matlab}
\verb|patches.codist.Dimension| is the index that is split
among workers. Then distribute the coordinate direction
among the workers: the function must be invoked inside an
\verb|spmd|-group in order for this to work---so we do not
need \verb|parallel| in argument list.
\begin{matlab}
%}
switch pari
case 1, patches.x=codistributed(patches.x,patches.codist);
otherwise
error('should never have bad index for parallel distribution')
end%switch
end%spmd
%{
\end{matlab}
If not parallel, then clean out \verb|patches.codist| if it
exists. May not need, but safer.
\begin{matlab}
%}
else% not parallel
if isfield(patches,'codist'), rmfield(patches,'codist'); end
end%if-parallel
%{
\end{matlab}
\paragraph{Fin}
\begin{matlab}
%}
end% function
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
hyperDiffHetero.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/hyperDiffHetero.m
| 5,068 |
utf_8
|
86abdf14874293588d096b8c6c5856cc
|
% Simulate a heterogeneous version of hyper-diffusion PDE in
% 1D on patches as an example application with pairs of edge
% points needing to be interpolated between patches in
% space. AJR, 12 Apr 2023
%!TEX root = doc.tex
%{
\section{\texttt{hyperDiffHetero}: simulate a heterogeneous
hyper-diffusion PDE in 1D on patches}
\label{sec:hyperDiffHetero}
\localtableofcontents
\cref{fig:hyperDiffHeteroU} shows an example simulation in
time generated by the patch scheme applied to a
heterogeneous version of the hyper-diffusion \pde. That such
simulations makes valid predictions was established by
\cite{Bunder2013b} who proved that the scheme is accurate
when the number of points in a patch is tied to a multiple
of the periodicity of the pattern.
\begin{figure}
\centering \caption{\label{fig:hyperDiffHeteroU}
hyper-diffusing field~\(u(x,t)\) in the patch scheme applied
to microscale heterogeneous hyper-diffusion
(\cref{sec:hyperDiffHetero}). The log-time axis shows:
\(t<10^{-2}\), rapid decay of sub-patch micro-structure;
\(10^{-2}<t<1\), meso-time quasi-equilibrium; and
\(1<t<10^2\), slow decay of macroscale structures.}
\includegraphics[scale=0.9]{hyperDiffHeteroUxt}
\end{figure}%
We aim to simulate the heterogeneous hyper-diffusion \pde
\begin{equation}
u_t= -D[c_1(x)Du] \quad\text{where operator }
D := \partial_x( c_2(x) \partial_x ),
\label{eq:hyperDiffHetero}
\end{equation}
for microscale periodic coefficients~\(c_l(x)\), and
boundary conditions of \(u=u_x=0\) at \(x=0,L\). In this 1D
space, the macroscale, homogenised, effective
hyper-diffusion should be some unknown `average' of these
coefficients, but we use the patch scheme to provide a
computational homogenisation. We discretise the \pde\ to a
lattice of values~\(u_i(t)\), with lattice spacing~\(dx\),
and governed by
\begin{equation*}
\dot u_i = -D[c_{i1}D u_i] \quad\text{where operator }
D := \delta( c_{i2}\delta )/dx^2
\end{equation*}
in terms of centred difference operator \(\delta u_i :=
u_{i+1/2} - u_{i-1/2}\).
Set the desired microscale periodicity, and correspondingly
choose random microscale diffusion coefficients (with
some subscripts shifted by a half).
\begin{matlab}
%}
clear all
basename = mfilename
%global OurCf2eps, OurCf2eps=true %optional to save plots
nGap = 3 % controls size of gap between patches
nPtsPeriod = 5
dx = 0.5/nGap/nPtsPeriod
%{
\end{matlab}
Create some random heterogeneous coefficients, log-uniform.
\begin{matlab}
%}
csVar = 1
cs = 0.2*exp( -csVar/2+csVar.*rand(nPtsPeriod,2) )
%{
\end{matlab}
Establish global data struct~\verb|patches| for
heterogeneous hyper-diffusion on a finite domain with, on
average, one patch per unit length. Use seven patches, and
use high-order interpolation with \(\verb|ordCC|=0\).
\begin{matlab}
%}
nPatch = 7
nSubP = 2*nPtsPeriod+4 % or +2 for not-edgyInt
Len = nPatch;
ordCC = 0;
dom.type = 'equispace';
dom.bcOffset = 0.5 % for BC type
patches = configPatches1(@hyperDiffPDE,[0 Len],dom ...
,nPatch,ordCC,dx,nSubP,'EdgyInt',true,'nEdge',2 ...
,'hetCoeffs',cs);
xs=squeeze(patches.x);
%{
\end{matlab}
\paragraph{Simulate in time}
Set an initial condition, and here integrate forward in time
using a standard method for stiff systems---because of the
simplicity of linear problems this method works quite
efficiently here. Integrate the interface \verb|patchSys1|
(\cref{sec:patchSys1}) to the microscale differential
equations.
\begin{matlab}
%}
u0 = sin(2*pi/Len*patches.x).*rand(nSubP,1,1,nPatch);
tic
[ts,us] = ode15s(@patchSys1, [0 100], u0(:) ,[],patches);
simulateTime = toc
us = reshape(us,length(ts),numel(patches.x(:)),[]);
%{
\end{matlab}
Plot the simulation in \cref{fig:hyperDiffHeteroU}, using
log-axis for time so we can see a little of both micro- and
macro-dynamics.
\begin{matlab}
%}
figure(1),clf
xs([1:2 end-1:end],:) = nan;
t0=min(find(ts>1e-5));
mesh(ts(t0:3:end),xs(:),us(t0:3:end,:)'), view(55,50)
colormap(0.7*hsv)
xlabel('time t'), ylabel('space x'), zlabel('u(x,t)')
ca=gca; ca.XScale='log'; ca.XLim=ts([t0 end]);
ifOurCf2eps([basename 'Uxt'])
%{
\end{matlab}
Fin.
\subsection{Heterogeneous hyper-diffusion PDE inside patches}
As a microscale discretisation of hyper-diffusion
\pde~\cref{eq:hyperDiffHetero} \(u_t= -D[c_1(x)Du] \), where
heterogeneous operator \(D = \partial_x( c_2(x) \partial_x
)\).
\begin{matlab}
%}
function ut=hyperDiffPDE(t,u,patches)
dx=diff(patches.x(1:2)); % microscale spacing
%{
\end{matlab}
Code Dirichlet boundary conditions of zero function and
derivative at left-end of left-patch, and right-end of
right-patch. For slightly simpler coding, squeeze out the
two singleton dimensions.
\begin{matlab}
%}
u = squeeze(u);
if ~patches.periodic % discretise BC u=u_x=0
u(1:2,1)=0;
u(end-1:end,end)=0;
end%if
%{
\end{matlab}
Here code straightforward centred discretisation in space.
\begin{matlab}
%}
ut = nan+u; % preallocate output array
v = patches.cs(2:end,1).*diff(patches.cs(:,2).*diff(u))/dx^2;
ut(3:end-2,:) = -diff(patches.cs(2:end-1,2).*diff(v))/dx^2 ;
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
configPatches2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/configPatches2.m
| 31,139 |
utf_8
|
0503e5a59406ec06c7901c982f712d36
|
% configPatches2() creates a data struct of the design of 2D
% patches for later use by the patch functions such as
% patchSys2(). AJR, Nov 2018 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{configPatches2()}: configures spatial
patches in 2D}
\label{sec:configPatches2}
\localtableofcontents
Makes the struct~\verb|patches| for use by the patch\slash
gap-tooth time derivative\slash step function
\verb|patchSys2()|. \cref{sec:configPatches2eg} lists an
example of its use.
\begin{matlab}
%}
function patches = configPatches2(fun,Xlim,Dom ...
,nPatch,ordCC,dx,nSubP,varargin)
version = '2023-04-12';
%{
\end{matlab}
\paragraph{Input}
If invoked with no input arguments, then executes an example
of simulating a nonlinear diffusion \pde\ relevant to the
lubrication flow of a thin layer of fluid---see
\cref{sec:configPatches2eg} for an example code.
\begin{itemize}
\item \verb|fun| is the name of the user function,
\verb|fun(t,u,patches)| or \verb|fun(t,u)| or
\verb|fun(t,u,patches,...)|, that computes time-derivatives
(or time-steps) of quantities on the 2D micro-grid within
all the 2D~patches.
\item \verb|Xlim| array/vector giving the rectangular
macro-space domain of the computation, namely
$[\verb|Xlim(1)|, \verb|Xlim(2)|] \times [\verb|Xlim(3)|,
\verb|Xlim(4)|]$. If \verb|Xlim| has two elements, then the
domain is the square domain of the same interval in both
directions.
\item \verb|Dom| sets the type of macroscale conditions for
the patches, and reflects the type of microscale boundary
conditions of the problem. If \verb|Dom| is \verb|NaN| or
\verb|[]|, then the field~\verb|u| is doubly macro-periodic
in the 2D spatial domain, and resolved on equi-spaced
patches. If \verb|Dom| is a character string, then that
specifies the \verb|.type| of the following structure, with
\verb|.bcOffset| set to the default zero. Otherwise
\verb|Dom| is a structure with the following components.
\begin{itemize}
\item \verb|.type|, string, of either \verb|'periodic'| (the
default), \verb|'equispace'|, \verb|'chebyshev'|,
\verb|'usergiven'|. For all cases except \verb|'periodic'|,
users \emph{must} code into \verb|fun| the micro-grid
boundary conditions that apply at the left\slash right\slash
bottom\slash top edges of the leftmost\slash rightmost\slash
bottommost\slash topmost patches, respectively.
\item \verb|.bcOffset|, optional one, two or four element
vector/array, in the cases of \verb|'equispace'| or
\verb|'chebyshev'| the patches are placed so the left\slash
right\slash top\slash bottom macroscale boundaries are
aligned to the left\slash right\slash top\slash bottom edges
of the corresponding extreme patches, but offset by
\verb|.bcOffset| of the sub-patch micro-grid spacing. For
example, use \verb|bcOffset=0| when the micro-code applies
Dirichlet boundary values on the extreme edge micro-grid
points, whereas use \verb|bcOffset=0.5| when the microcode
applies Neumann boundary conditions halfway between the
extreme edge micro-grid points. Similarly for the top and
bottom edges.
If \verb|.bcOffset| is a scalar, then apply the same offset
to all boundaries. If two elements, then apply the first
offset to both \(x\)-boundaries, and the second offset to
both \(y\)-boundaries. If four elements, then apply the
first two offsets to the respective \(x\)-boundaries, and
the last two offsets to the respective \(y\)-boundaries.
\item \verb|.X|, optional vector/array with \verb|nPatch(1)|
elements, in the case \verb|'usergiven'| it specifies the
\(x\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\item \verb|.Y|, optional vector/array with \verb|nPatch(2)|
elements, in the case \verb|'usergiven'| it specifies the
\(y\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\end{itemize}
\item \verb|nPatch| sets the number of equi-spaced spatial
patches: if scalar, then use the same number of patches in
both directions, otherwise \verb|nPatch(1:2)| gives the
number of patches~($\geq1$) in each direction.
\item \verb|ordCC| is the `order' of interpolation for
inter-patch coupling across empty space of the macroscale
patch values to the edge-values of the patches: currently
must be~$0,2,4,\ldots$; where $0$~gives spectral
interpolation.
\item \verb|dx| (real---scalar or two element) is usually
the sub-patch micro-grid spacing in~\(x\) and~\(y\). If
scalar, then use the same \verb|dx| in both directions,
otherwise \verb|dx(1:2)| gives the spacing in each of the
two directions.
However, if \verb|Dom| is~\verb|NaN| (as for pre-2023), then
\verb|dx| actually is \verb|ratio| (scalar or two element),
namely the ratio of (depending upon \verb|EdgyInt|) either
the half-width or full-width of a patch to the equi-spacing
of the patch mid-points---adjusted a little when $\verb|nEdge|>1$. So
either $\verb|ratio|=\tfrac12$ means the patches abut and
$\verb|ratio|=1$ is overlapping patches as in holistic
discretisation, or $\verb|ratio|=1$ means the patches abut.
Small~\verb|ratio| should greatly reduce computational time.
\item \verb|nSubP| is the number of equi-spaced microscale
lattice points in each patch: if scalar, then use the same
number in both directions, otherwise \verb|nSubP(1:2)| gives
the number in each direction. If not using \verb|EdgyInt|,
then $\verb|nSubP./nEdge|$ must be odd integer(s) so that there
is/are centre-patch lattice lines. So for the defaults
of $\verb|nEdge|=1$ and not \verb|EdgyInt|, then
\verb|nSubP| must be odd.
\item \verb|'nEdge'|, \emph{optional} (integer---scalar or two element), default=1, the width of edge values set by interpolation at the
edge regions of each patch. If two elements, then respectively the width in \(x,y\)-directions. The default is one (suitable
for microscale lattices with only nearest neighbour
interactions).
\item \verb|EdgyInt|, true/false, \emph{optional},
default=false. If true, then interpolate to left\slash
right\slash top\slash bottom edge-values from right\slash
left\slash bottom\slash top next-to-edge values. If false
or omitted, then interpolate from centre cross-patch lines.
\item \verb|nEnsem|, \emph{optional-experimental},
default one, but if more, then an ensemble over this
number of realisations.
\item \verb|hetCoeffs|, \emph{optional}, default empty.
Supply a 2D or 3D array of microscale heterogeneous
coefficients to be used by the given microscale \verb|fun|
in each patch. Say the given array~\verb|cs| is of size
$m_x\times m_y\times n_c$, where $n_c$~is the number of
different sets of coefficients. For example, in
heterogeneous diffusion, $n_c=2$ for the diffusivities in
the \emph{two} different spatial directions (or $n_c=3$ for
the diffusivity tensor). The coefficients are to be the same
for each and every patch; however, macroscale variations are
catered for by the $n_c$~coefficients being $n_c$~parameters
in some macroscale formula.
\begin{itemize}
\item If $\verb|nEnsem|=1$, then the array of coefficients
is just tiled across the patch size to fill up each patch,
starting from the $(1,1)$-point in each patch. Best accuracy
usually obtained when the periodicity of the coefficients
is a factor of \verb|nSubP-2*nEdge| for \verb|EdgyInt|, or
a factor of \verb|(nSubP-nEdge)/2| for not \verb|EdgyInt|.
\item If $\verb|nEnsem|>1$ (value immaterial), then reset
$\verb|nEnsem|:=m_x\cdot m_y$ and construct an ensemble of
all $m_x\cdot m_y$ phase-shifts of the coefficients. In
this scenario, the inter-patch coupling couples different
members in the ensemble. When \verb|EdgyInt| is true, and
when the coefficients are diffusivities\slash elasticities
in~$x$ and~$y$ directions, respectively, then this
coupling cunningly preserves symmetry.
\end{itemize}
\item \verb|'parallel'|, true/false, \emph{optional},
default=false. If false, then all patch computations are on
the user's main \textsc{cpu}---although a user may well
separately invoke, say, a \textsc{gpu} to accelerate
sub-patch computations.
If true, and it requires that you have \Matlab's Parallel
Computing Toolbox, then it will distribute the patches over
multiple \textsc{cpu}s\slash cores. In \Matlab, only one
array dimension can be split in the distribution, so it
chooses the one space dimension~$x,y$ corresponding to the
highest~\verb|\nPatch| (if a tie, then chooses the rightmost
of~$x,y$). A user may correspondingly distribute arrays
with property \verb|patches.codist|, or simply use formulas
invoking the preset distributed arrays \verb|patches.x|, and
\verb|patches.y|. If a user has not yet established a
parallel pool, then a `local' pool is started.
\end{itemize}
\paragraph{Output} The struct \verb|patches| is created and
set with the following components. If no output variable is
provided for \verb|patches|, then make the struct available
as a global variable.\footnote{When using \texttt{spmd}
parallel computing, it is generally best to avoid global
variables, and so instead prefer using an explicit output
variable.}
\begin{matlab}
%}
if nargout==0, global patches, end
patches.version = version;
%{
\end{matlab}
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| or \verb|fun(t,u)| or
\verb|fun(t,u,patches,...)|, that computes the time
derivatives (or steps) on the patchy lattice.
\item \verb|.ordCC| is the specified order of inter-patch
coupling.
\item \verb|.periodic|: either true, for interpolation on
the macro-periodic domain; or false, for general
interpolation by divided differences over non-periodic
domain or unevenly distributed patches.
\item \verb|.stag| is true for interpolation using only odd
neighbouring patches as for staggered grids, and false for
the usual case of all neighbour coupling---not yet
implemented.
\item \verb|.Cwtsr| and \verb|.Cwtsl|, only for
macro-periodic conditions, are the
$\verb|ordCC|\times 2$-array of weights for the inter-patch
interpolation onto the right\slash top and left\slash bottom
edges (respectively) with patch:macroscale ratio as
specified or as derived from~\verb|dx|.
\item \verb|.x| (6D) is $\verb|nSubP(1)| \times1 \times1
\times1 \times \verb|nPatch(1)| \times1$ array of the
regular spatial locations~$x_{iI}$ of the microscale grid
points in every patch.
\item \verb|.y| (6D) is $1 \times \verb|nSubP(2)| \times1
\times1 \times1 \times \verb|nPatch(2)|$ array of the
regular spatial locations~$y_{jJ}$ of the microscale grid
points in every patch.
\item \verb|.ratio| $1\times 2$, only for
macro-periodic conditions, are the size ratios of
every patch.
\item \verb|.nEdge| $1\times 2$, is the width of edge
values set by interpolation at the edge regions of each
patch, in the \(x,y\)-directions respectively.
\item \verb|.le|, \verb|.ri|, \verb|.bo|, \verb|.to|
determine inter-patch coupling of members in an ensemble.
Each a column vector of length~\verb|nEnsem|.
\item \verb|.cs| either
\begin{itemize}
\item \verb|[]| 0D, or
\item if $\verb|nEnsem|=1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times n_c$ 3D array of microscale
heterogeneous coefficients, or
\item if $\verb|nEnsem|>1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times n_c\times m_xm_y$ 4D array of
$m_xm_y$~ensemble of phase-shifts of the microscale
heterogeneous coefficients.
\end{itemize}
\item \verb|.parallel|, logical: true if patches are
distributed over multiple \textsc{cpu}s\slash cores for the
Parallel Computing Toolbox, otherwise false (the default is
to activate the \emph{local} pool).
\item \verb|.codist|, \emph{optional}, describes the
particular parallel distribution of arrays over the active
parallel pool.
\end{itemize}
\subsection{If no arguments, then execute an example}
\label{sec:configPatches2eg}
\begin{matlab}
%}
if nargin==0
disp('With no arguments, simulate example of nonlinear diffusion')
%{
\end{matlab}
The code here shows one way to get started: a user's script
may have the following three steps (``\into'' denotes
function recursion).
\begin{enumerate}\def\itemsep{-1.5ex}
\item configPatches2
\item ode23 integrator \into patchSys2 \into user's PDE
\item process results
\end{enumerate}
Establish global patch data struct to interface with a
function coding a nonlinear `diffusion' \pde: to be solved
on $6\times4$-periodic domain, with $9\times7$ patches,
spectral interpolation~($0$) couples the patches, with
$5\times5$ points forming the micro-grid in each patch, and
a sub-patch micro-grid spacing of~\(0.12\) (relatively large
for visualisation). \cite{Roberts2011a} established that
this scheme is consistent with the \pde\ (as the patch
spacing decreases).
\begin{matlab}
%}
global patches
patches = configPatches2(@nonDiffPDE,[-3 3 -2 2] ...
,'periodic', [9 7], 0, 0.12, 5 ,'EdgyInt',false);
%{
\end{matlab}
Set an initial condition of a perturbed-Gaussian using
auto-replication of the spatial grid.
\begin{matlab}
%}
u0 = exp(-patches.x.^2-patches.y.^2);
u0 = u0.*(0.9+0.1*rand(size(u0)));
%{
\end{matlab}
Initiate a plot of the simulation using only the microscale
values interior to the patches: optionally set $x$~and
$y$-edges to \verb|nan| to leave the gaps between patches.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*hsv)
x = squeeze(patches.x); y = squeeze(patches.y);
if 1, x([1 end],:) = nan; y([1 end],:) = nan; end
%{
\end{matlab}
Start by showing the initial conditions of
\cref{fig:configPatches2ic} while the simulation computes.
\begin{matlab}
%}
u = reshape(permute(squeeze(u0) ...
,[1 3 2 4]), [numel(x) numel(y)]);
hsurf = mesh(x(:),y(:),u');
axis([-3 3 -3 3 -0.03 1]), view(60,40)
legend('time = 0.00','Location','north')
xlabel('space x'), ylabel('space y'), zlabel('u(x,y)')
colormap(hsv)
ifOurCf2eps([mfilename 'ic'])
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:configPatches2ic}initial
field~$u(x,y,t)$ at time $t=0$ of the patch scheme applied
to a nonlinear `diffusion'~\pde: \cref{fig:configPatches2t3}
plots the computed field at time $t=3$.}
\includegraphics[scale=0.9]{configPatches2ic}
\end{figure}
Integrate in time to $t=4$ using standard functions. In
\Matlab\ \verb|ode15s| would be natural as the patch scheme
is naturally stiff, but \verb|ode23| is quicker \cite
[Fig.~4] {Maclean2020a}. Ask for output at non-uniform
times because the diffusion slows.
\begin{matlab}
%}
disp('Wait to simulate nonlinear diffusion h_t=(h^3)_xx+(h^3)_yy')
drawnow
if ~exist('OCTAVE_VERSION','builtin')
[ts,us] = ode23(@patchSys2,linspace(0,2).^2,u0(:));
else % octave version is quite slow for me
lsode_options('absolute tolerance',1e-4);
lsode_options('relative tolerance',1e-4);
[ts,us] = odeOcts(@patchSys2,[0 1],u0(:));
end
%{
\end{matlab}
Animate the computed simulation to end with
\cref{fig:configPatches2t3}. Use \verb|patchEdgeInt2| to
interpolate patch-edge values.
\begin{matlab}
%}
for i = 1:length(ts)
u = patchEdgeInt2(us(i,:));
u = reshape(permute(squeeze(u) ...
,[1 3 2 4]), [numel(x) numel(y)]);
set(hsurf,'ZData', u');
legend(['time = ' num2str(ts(i),'%4.2f')])
pause(0.1)
end
ifOurCf2eps([mfilename 't3'])
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:configPatches2t3}field~$u(x,y,t)$ at
time $t=3$ of the patch scheme applied to a nonlinear
`diffusion'~\pde\ with initial condition in
\cref{fig:configPatches2ic}.}
\includegraphics[scale=0.9]{configPatches2t3}
\end{figure}
Upon finishing execution of the example, exit this function.
\begin{matlab}
%}
return
end%if no arguments
%{
\end{matlab}
\IfFileExists{../Patch/nonDiffPDE.m}{\input{../Patch/nonDiffPDE.m}}{}
\begin{devMan}
\subsection{Parse input arguments and defaults}
\begin{matlab}
%}
p = inputParser;
fnValidation = @(f) isa(f, 'function_handle');%test for fn name
addRequired(p,'fun',fnValidation);
addRequired(p,'Xlim',@isnumeric);
%addRequired(p,'Dom'); % nothing yet decided
addRequired(p,'nPatch',@isnumeric);
addRequired(p,'ordCC',@isnumeric);
addRequired(p,'dx',@isnumeric);
addRequired(p,'nSubP',@isnumeric);
addParameter(p,'nEdge',1,@isnumeric);
addParameter(p,'EdgyInt',false,@islogical);
addParameter(p,'nEnsem',1,@isnumeric);
addParameter(p,'hetCoeffs',[],@isnumeric);
addParameter(p,'parallel',false,@islogical);
%addParameter(p,'nCore',1,@isnumeric); % not yet implemented
parse(p,fun,Xlim,nPatch,ordCC,dx,nSubP,varargin{:});
%{
\end{matlab}
Set the optional parameters.
\begin{matlab}
%}
patches.nEdge = p.Results.nEdge;
if numel(patches.nEdge)==1
patches.nEdge = repmat(patches.nEdge,1,2);
end
patches.EdgyInt = p.Results.EdgyInt;
patches.nEnsem = p.Results.nEnsem;
cs = p.Results.hetCoeffs;
patches.parallel = p.Results.parallel;
%patches.nCore = p.Results.nCore;
%{
\end{matlab}
Initially duplicate parameters for both space dimensions as
needed.
\begin{matlab}
%}
if numel(Xlim)==2, Xlim = repmat(Xlim,1,2); end
if numel(nPatch)==1, nPatch = repmat(nPatch,1,2); end
if numel(dx)==1, dx = repmat(dx,1,2); end
if numel(nSubP)==1, nSubP = repmat(nSubP,1,2); end
%{
\end{matlab}
Check parameters.
\begin{matlab}
%}
assert(Xlim(1)<Xlim(2) ...
,'first pair of Xlim must be ordered increasing')
assert(Xlim(3)<Xlim(4) ...
,'second pair of Xlim must be ordered increasing')
assert((mod(ordCC,2)==0)|all(patches.nEdge==1) ...
,'Cannot yet have nEdge>1 and staggered patch grids')
assert(all(3*patches.nEdge<=nSubP) ...
,'too many edge values requested')
assert(all(rem(nSubP,patches.nEdge)==0) ...
,'nSubP must be integer multiple of nEdge')
if ~patches.EdgyInt, assert(all(rem(nSubP./patches.nEdge,2)==1) ...
,'for non-edgyInt, nSubP./nEdge must be odd integer')
end
if (patches.nEnsem>1)&all(patches.nEdge>1)
warning('not yet tested when both nEnsem and nEdge non-one')
end
%if patches.nCore>1
% warning('nCore>1 not yet tested in this version')
% end
%{
\end{matlab}
For compatibility with pre-2023 functions, if parameter
\verb|Dom| is \verb|Nan|, then we set the \verb|ratio| to
be the value of the so-called \verb|dx| vector.
\begin{matlab}
%}
if ~isstruct(Dom), pre2023=isnan(Dom);
else pre2023=false; end
if pre2023, ratio=dx; dx=nan; end
%{
\end{matlab}
Default macroscale conditions are periodic with evenly
spaced patches.
\begin{matlab}
%}
if isempty(Dom), Dom=struct('type','periodic'); end
if (~isstruct(Dom))&isnan(Dom), Dom=struct('type','periodic'); end
%{
\end{matlab}
If \verb|Dom| is a string, then just set type to that
string, and subsequently set corresponding defaults for
others fields.
\begin{matlab}
%}
if ischar(Dom), Dom=struct('type',Dom); end
%{
\end{matlab}
We allow different macroscale domain conditions in the
different directions. But for the moment do not allow
periodic to be mixed with the others (as the interpolation
mechanism is different code)---hence why we choose
\verb|periodic| be seven characters, whereas the others are
eight characters. The different conditions are coded in
different rows of \verb|Dom.type|, so we duplicate the
string if only one row specified.
\begin{matlab}
%}
if size(Dom.type,1)==1, Dom.type=repmat(Dom.type,2,1); end
%{
\end{matlab}
Check what is and is not specified, and provide default of
zero
(Dirichlet boundaries) if no \verb|bcOffset| specified when
needed. Do so for both directions independently.
\begin{matlab}
%}
patches.periodic=false;
for p=1:2
switch Dom.type(p,:)
case 'periodic'
patches.periodic=true;
if isfield(Dom,'bcOffset')
warning('bcOffset not available for Dom.type = periodic'), end
msg=' not available for Dom.type = periodic';
if isfield(Dom,'X'), warning(['X' msg]), end
if isfield(Dom,'Y'), warning(['Y' msg]), end
case {'equispace','chebyshev'}
if ~isfield(Dom,'bcOffset'), Dom.bcOffset=zeros(2,2); end
% for mixed with usergiven, following should still work
if numel(Dom.bcOffset)==1
Dom.bcOffset=repmat(Dom.bcOffset,2,2); end
if numel(Dom.bcOffset)==2
Dom.bcOffset=repmat(Dom.bcOffset(:)',2,1); end
msg=' not available for Dom.type = equispace or chebyshev';
if (p==1)& isfield(Dom,'X'), warning(['X' msg]), end
if (p==2)& isfield(Dom,'Y'), warning(['Y' msg]), end
case 'usergiven'
% if isfield(Dom,'bcOffset')
% warning('bcOffset not available for usergiven Dom.type'), end
msg=' required for Dom.type = usergiven';
if p==1, assert(isfield(Dom,'X'),['X' msg]), end
if p==2, assert(isfield(Dom,'Y'),['Y' msg]), end
otherwise
error([Dom.type ' is unknown Dom.type'])
end%switch Dom.type
end%for p
%{
\end{matlab}
\subsection{The code to make patches}
First, store the pointer to the time derivative function in
the struct.
\begin{matlab}
%}
patches.fun = fun;
%{
\end{matlab}
Second, store the order of interpolation that is to provide
the values for the inter-patch coupling conditions. Spectral
coupling is \verb|ordCC| of~$0$ or (not yet??)~$-1$.
\todo{Perhaps implement staggered spectral coupling.}
\begin{matlab}
%}
assert((ordCC>=-1) & (floor(ordCC)==ordCC), ...
'ordCC out of allowed range integer>=-1')
%{
\end{matlab}
For odd~\verb|ordCC| do interpolation based upon odd
neighbouring patches as is useful for staggered grids.
\begin{matlab}
%}
patches.stag = mod(ordCC,2);
assert(patches.stag==0,'staggered not yet implemented??')
ordCC = ordCC+patches.stag;
patches.ordCC = ordCC;
%{
\end{matlab}
Check for staggered grid and periodic case.
\begin{matlab}
%}
if patches.stag, assert(all(mod(nPatch,2)==0), ...
'Require an even number of patches for staggered grid')
end
%{
\end{matlab}
\paragraph{Set the macro-distribution of patches}
Third, set the centre of the patches in the macroscale grid
of patches. Loop over the coordinate directions, setting
the distribution into~\verb|Q| and finally assigning to
array of corresponding direction.
\begin{matlab}
%}
for q=1:2
qq=2*q-1;
%{
\end{matlab}
Distribution depends upon \verb|Dom.type|:
\begin{matlab}
%}
switch Dom.type(q,:)
%{
\end{matlab}
%: case periodic
The periodic case is evenly spaced within the spatial domain.
Store the size ratio in \verb|patches|.
\begin{matlab}
%}
case 'periodic'
Q=linspace(Xlim(qq),Xlim(qq+1),nPatch(q)+1);
DQ=Q(2)-Q(1);
Q=Q(1:nPatch(q))+diff(Q)/2;
pEI=patches.EdgyInt; % abbreviation
pnE=patches.nEdge(q);% abbreviation
if pre2023, dx(q) = ratio(q)*DQ/(nSubP(q)-pnE*(1+pEI))*(2-pEI);
else ratio(q) = dx(q)/DQ*(nSubP(q)-pnE*(1+pEI))/(2-pEI);
end
patches.ratio=ratio;
%{
\end{matlab}
%: case equispace
The equi-spaced case is also evenly spaced but with the
extreme edges aligned with the spatial domain boundaries,
modified by the offset.
\begin{matlab}
%}
case 'equispace'
Q=linspace(Xlim(qq)+((nSubP(q)-1)/2-Dom.bcOffset(qq))*dx(q) ...
,Xlim(qq+1)-((nSubP(q)-1)/2-Dom.bcOffset(qq+1))*dx(q) ...
,nPatch(q));
DQ=diff(Q(1:2));
width=(1+patches.EdgyInt)/2*(nSubP(q)-1-patches.EdgyInt)*dx;
if DQ<width*0.999999
warning('too many equispace patches (double overlapping)')
end
%{
\end{matlab}
%: case chebyshev
The Chebyshev case is spaced according to the Chebyshev
distribution in order to reduce macro-interpolation errors,
\(Q_i \propto -\cos(i\pi/N)\), but with the extreme edges
aligned with the spatial domain boundaries, modified by the
offset, and modified by possible `boundary layers'.
\footnote{ However, maybe overlapping patches near a
boundary should be viewed as some sort of spatially analogue
of the `christmas tree' of projective integration and its
integration to a slow manifold. Here maybe the overlapping
patches allow for a `christmas tree' approach to the
boundary layers. Needs to be explored??}
\begin{matlab}
%}
case 'chebyshev'
halfWidth=dx(q)*(nSubP(q)-1)/2;
Q1 = Xlim(1)+halfWidth-Dom.bcOffset(qq)*dx(q);
Q2 = Xlim(2)-halfWidth+Dom.bcOffset(qq+1)*dx(q);
% Q = (Q1+Q2)/2-(Q2-Q1)/2*cos(linspace(0,pi,nPatch));
%{
\end{matlab}
Search for total width of `boundary layers' so that in the
interior the patches are non-overlapping Chebyshev. But
the width for assessing overlap of patches is the following
variable \verb|width|.
\begin{matlab}
%}
pEI=patches.EdgyInt; % abbreviation
pnE=patches.nEdge(q);% abbreviation
width=(1+pEI)/2*(nSubP(q)-pnE*(1+pEI))*dx(q);
for b=0:2:nPatch(q)-2
DQmin=(Q2-Q1-b*width)/2*( 1-cos(pi/(nPatch(q)-b-1)) );
if DQmin>width, break, end
end%for
if DQmin<width*0.999999
warning('too many Chebyshev patches (mid-domain overlap)')
end
%{
\end{matlab}
Assign the centre-patch coordinates.
\begin{matlab}
%}
Q =[ Q1+(0:b/2-1)*width ...
(Q1+Q2)/2-(Q2-Q1-b*width)/2*cos(linspace(0,pi,nPatch(q)-b)) ...
Q2+(1-b/2:0)*width ];
%{
\end{matlab}
%: case usergiven
The user-given case is entirely up to a user to specify, we
just force it to have the correct shape of a row.
\begin{matlab}
%}
case 'usergiven'
if q==1, Q = reshape(Dom.X,1,[]);
else Q = reshape(Dom.Y,1,[]);
end%if
end%switch Dom.type
%{
\end{matlab}
Assign \(Q\)-coordinates to the correct spatial direction.
At this stage they are all rows.
\begin{matlab}
%}
if q==1, X=Q; end
if q==2, Y=Q; end
end%for q
%{
\end{matlab}
\paragraph{Construct the micro-grids}
Fourth, construct the microscale grid in each patch, centred
about the given mid-points~\verb|X,Y|. Reshape the grid to be
6D to suit dimensions (micro,Vars,Ens,macro).
\begin{matlab}
%}
xs = dx(1)*( (1:nSubP(1))-mean(1:nSubP(1)) );
patches.x = reshape( xs'+X ...
,nSubP(1),1,1,1,nPatch(1),1);
ys = dx(2)*( (1:nSubP(2))-mean(1:nSubP(2)) );
patches.y = reshape( ys'+Y ...
,1,nSubP(2),1,1,1,nPatch(2));
%{
\end{matlab}
\paragraph{Pre-compute weights for macro-periodic}
In the case of macro-periodicity, precompute the weightings
to interpolate field values for coupling. \todo{Might sometime
extend to coupling via derivative values.}
\begin{matlab}
%}
if patches.periodic
ratio = reshape(ratio,1,2); % force to be row vector
patches.ratio=ratio;
if ordCC>0
[Cwtsr,Cwtsl] = patchCwts(ratio,ordCC,patches.stag);
patches.Cwtsr = Cwtsr; patches.Cwtsl = Cwtsl;
end%if
end%if patches.periodic
%{
\end{matlab}
\subsection{Set ensemble inter-patch communication}
For \verb|EdgyInt| or centre interpolation respectively,
\begin{itemize}
\item the right-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to left-edge~\verb|le|,
and
\item the left-edge\slash centre realisations
\verb|1:nEnsem| are to interpolate to~\verb|re|.
\end{itemize}
\verb|re| and \verb|li| are `transposes' of each other as
\verb|re(li)=le(ri)| are both \verb|1:nEnsem|. Similarly for
bottom-edge\slash centre interpolation to top-edge
via~\verb|to|, and top-edge\slash centre interpolation to
bottom-edge via~\verb|bo|.
The default is nothing shifty. This setting reduces the
number of if-statements in function \verb|patchEdgeInt2()|.
\begin{matlab}
%}
nE = patches.nEnsem;
patches.le = 1:nE; patches.ri = 1:nE;
patches.bo = 1:nE; patches.to = 1:nE;
%{
\end{matlab}
However, if heterogeneous coefficients are supplied via
\verb|hetCoeffs|, then do some non-trivial replications.
First, get microscale periods, patch size, and replicate
many times in order to subsequently sub-sample: \verb|nSubP|
times should be enough. If \verb|cs| is more then 3D, then
the higher-dimensions are reshaped into the 3rd dimension.
\begin{matlab}
%}
if ~isempty(cs)
[mx,my,nc] = size(cs);
nx = nSubP(1); ny = nSubP(2);
cs = repmat(cs,nSubP);
%{
\end{matlab}
If only one member of the ensemble is required, then
sub-sample to patch size, and store coefficients in
\verb|patches| as is.
\begin{matlab}
%}
if nE==1, patches.cs = cs(1:nx-1,1:ny-1,:); else
%{
\end{matlab}
But for $\verb|nEnsem|>1$ an ensemble of
$m_xm_y$~phase-shifts of the coefficients is constructed
from the over-supply. Here code phase-shifts over the
periods---the phase shifts are like Hankel-matrices.
\begin{matlab}
%}
patches.nEnsem = mx*my;
patches.cs = nan(nx-1,ny-1,nc,mx,my);
for j = 1:my
js = (j:j+ny-2);
for i = 1:mx
is = (i:i+nx-2);
patches.cs(:,:,:,i,j) = cs(is,js,:);
end
end
patches.cs = reshape(patches.cs,nx-1,ny-1,nc,[]);
%{
\end{matlab}
Further, set a cunning left\slash right\slash bottom\slash
top realisation of inter-patch coupling. The aim is to
preserve symmetry in the system when also invoking
\verb|EdgyInt|. What this coupling does without
\verb|EdgyInt| is unknown. Use auto-replication.
\begin{matlab}
%}
le = mod((0:mx-1)+mod(nx-2,mx),mx)+1;
patches.le = reshape( le'+mx*(0:my-1) ,[],1);
ri = mod((0:mx-1)-mod(nx-2,mx),mx)+1;
patches.ri = reshape( ri'+mx*(0:my-1) ,[],1);
bo = mod((0:my-1)+mod(ny-2,my),my)+1;
patches.bo = reshape( (1:mx)'+mx*(bo-1) ,[],1);
to = mod((0:my-1)-mod(ny-2,my),my)+1;
patches.to = reshape( (1:mx)'+mx*(to-1) ,[],1);
%{
\end{matlab}
Issue warning if the ensemble is likely to be affected by
lack of scale separation. \todo{Maybe need to justify this
and the arbitrary threshold more carefully??}
\begin{matlab}
%}
if prod(ratio)*patches.nEnsem>0.9, warning( ...
'Probably poor scale separation in ensemble of coupled phase-shifts')
scaleSeparationParameter = ratio*patches.nEnsem
end
%{
\end{matlab}
End the two if-statements.
\begin{matlab}
%}
end%if-else nEnsem>1
end%if not-empty(cs)
%{
\end{matlab}
\paragraph{If parallel code} then first assume this is not
within an \verb|spmd|-environment, and so we invoke
\verb|spmd...end| (which starts a parallel pool if not
already started). At this point, the global \verb|patches|
is copied for each worker processor and so it becomes
\emph{composite} when we distribute any one of the fields.
Hereafter, {\em all fields in the global variable
\verb|patches| must only be referenced within an
\verb|spmd|-environment.}%
\footnote{If subsequently outside spmd, then one must use
functions like \texttt{getfield(patches\{1\},'a')}.}
\begin{matlab}
%}
if patches.parallel
% theparpool=gcp()
spmd
%{
\end{matlab}
Second, decide which dimension is to be sliced among
parallel workers (for the moment, do not consider slicing
the ensemble). Choose the direction of most patches, biased
towards the last.
\begin{matlab}
%}
[~,pari]=max(nPatch+0.01*(1:2));
patches.codist=codistributor1d(4+pari);
%{
\end{matlab}
\verb|patches.codist.Dimension| is the index that is split
among workers. Then distribute the appropriate coordinate
direction among the workers: the function must be invoked
inside an \verb|spmd|-group in order for this to work---so
we do not need \verb|parallel| in argument list.
\begin{matlab}
%}
switch pari
case 1, patches.x=codistributed(patches.x,patches.codist);
case 2, patches.y=codistributed(patches.y,patches.codist);
otherwise
error('should never have bad index for parallel distribution')
end%switch
end%spmd
%{
\end{matlab}
If not parallel, then clean out \verb|patches.codist| if it exists.
May not need, but safer.
\begin{matlab}
%}
else% not parallel
if isfield(patches,'codist'), rmfield(patches,'codist'); end
end%if-parallel
%{
\end{matlab}
\paragraph{Fin}
\begin{matlab}
%}
end% function
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
SwiftHohenbergPattern.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/SwiftHohenbergPattern.m
| 6,903 |
utf_8
|
39b464ae1e17aa2bb9504ef140cd20eb
|
% Simulate Swift--Hohenberg PDE in 1D on patches as an
% example application of patches in space with pairs of edge
% points needing to be interpolated between patches. AJR,
% 28 Mar 2023
%!TEX root = doc.tex
%{
\section{\texttt{SwiftHohenbergPattern}: patterns of the
Swift--Hohenberg PDE in 1D on patches}
\label{sec:SwiftHohenbergPattern}
\localtableofcontents
\cref{fig:SwiftHohenbergPatternUxt} shows an example
simulation in time generated by the patch scheme applied to
the patterns arising from the Swift--Hohenberg \pde. That
such simulations of patterns makes valid predictions was
established by \cite{Bunder2013b} who proved that the scheme
is accurate when the number of points in a patch is just
more than a multiple of the periodicity of the pattern.
\begin{figure}
\centering \caption{\label{fig:SwiftHohenbergPatternUxt}the
pattern forming field~\(u(x,t)\) in the patch (gap-tooth)
scheme applied to a microscale discretisation of the
Swift--Hohenberg \pde\ (\cref{sec:SwiftHohenbergPattern}).
Physically we see the rapid decay of much microstructure,
but also the meso-time growth of sub-patch-scale patterns,
wavenumber~\(k_0\), that are modulated over the inter-patch
distances and over long times.}
\includegraphics[scale=0.9]{Figs/SwiftHohenbergPatternUxt}
\end{figure}%
Consider a lattice of values~\(u_i(t)\), with lattice
spacing~\(dx\), and governed by a microscale centred
discretisation of the Swift--Hohenberg \pde
\begin{equation}
\partial_tu = -(1+\partial_x^2/k_0^2)^2u+\Ra u-u^3,
\label{eq:SwiftHohenbergPattern}
\end{equation}
with boundary conditions of \(u=u_x=0\) at \(x=0,L\). For
\Ra\ just above critical, say \(\Ra=0.1\), the system
rapidly evolves to spatial quasi-periodic solutions with
period\({} \approx 0.166\) when wavenumber parameter \(k_0 =
38\). On medium times these spatial oscillations grow to
near equilibrium amplitude of~\(\sqrt{\Ra}\), and over very
long times the phases of the oscillations evolve in space to
adapt to the boundaries.
Set the desired microscale periodicity of the emergent pattern.
\begin{matlab}
%}
clear all, close all
%global OurCf2eps, OurCf2eps=true %optional to save plots
Ra = 0.1 % Ra>0 leads to patterns
nGap = 3
%waveLength = 0.496688741721854 /nGap %for nPatch==5
waveLength = 0.497630331753555 /nGap %for nPatch==7
%waveLength = 0.5 /nGap %for periodic case
nPtsPeriod = 10
dx = waveLength/nPtsPeriod
k0 = 2*pi/waveLength
%{
\end{matlab}
Establish global data struct~\verb|patches| for
the Swift--Hohenberg \pde\ on some length domain. Use
seven patches. Quartic (fourth-order) interpolation
\(\verb|ordCC|=4\) provides values for the inter-patch
coupling conditions.
\begin{matlab}
%}
nPatch = 7
nSubP = 2*nPtsPeriod+4
%nSubP = 2*nGap*nPtsPeriod+4 % full-domain
Len = nPatch;
ordCC = 4;
dom.type='equispace';
dom.bcOffset=0.5
patches = configPatches1(@SwiftHohenbergPDE,[0 Len],dom ...
,nPatch,ordCC,dx,nSubP,'EdgyInt',true,'nEdge',2);
xs=squeeze(patches.x);
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:SwiftHohenbergPatternEquilib} an
equilibrium of the Swift--Hohenberg \pde\ on seven patches
in 1D~space. In the sub-patch patterns, there is a small
phase shift in the patterns from patch to patch. And the
amplitude of the pattern has to go to `zero' at the
boundaries. }
\def\extraAxisOptions{small,mark size=1pt,width=12cm,height=4cm}
\input{Figs/SwiftHohenbergPatternEquilib}
\end{figure}
\subsubsection{Find equilibrium with fsolve}
Start the search from some guess.
\begin{matlab}
%}
fprintf('\n**** Find equilibrium with fsolve\n')
u = 0.4*sin(k0*patches.x);
%{
\end{matlab}
But set the pairs of patch-edge values to \verb|Nan| in
order to use \verb|patches.i| to index the interior
sub-patch points as they are the variables.
\begin{matlab}
%}
u([1:2 end-1:end],:) = nan;
patches.i = find(~isnan(u));
%{
\end{matlab}
Seek the equilibrium, and report the norm of the residual,
via the generic patch system wrapper \verb|theRes|
(\cref{sec:theRes}).
\begin{matlab}
%}
tic
[u(patches.i),res] = fsolve(@(v) theRes(v,patches,k0,Ra) ...
,u(patches.i) ,optimoptions('fsolve','Display','off'));
solveTime = toc
normRes = norm(res)
assert(normRes<1e-6,'**** fsolve solution not accurate')
%{
\end{matlab}
\paragraph{Plot the equilibrium} see
\cref{fig:SwiftHohenbergPatternEquilib}.
\begin{matlab}
%}
figure(1),clf
subplot(2,1,1)
plot(xs,squeeze(u),'.-')
xlabel('space $x$'),ylabel('equilibrium $u(x)$')
ifOurCf2tex([mfilename 'Equilib'])%optionally save
%{
\end{matlab}
\subsubsection{Simulate in time}
Set an initial condition, and here integrate forward in time
using a standard method for stiff systems---because of the
simplicity of linear problems this method works quite
efficiently here. Integrate the interface \verb|patchSys1|
(\cref{sec:patchSys1}) to the microscale differential
equations.
\begin{matlab}
%}
fprintf('\n**** Simulate in time\n')
u0 = 0*patches.x+0.1*randn(nSubP,1,1,nPatch);
tic
[ts,us] = ode15s(@patchSys1, [0 40], u0(:) ,[],patches,k0,Ra);
simulateTime = toc
us = reshape(us,length(ts),numel(patches.x(:)),[]);
%{
\end{matlab}
Plot the simulation in \cref{fig:SwiftHohenbergPatternUxt}.
\begin{matlab}
%}
figure(2),clf
xs([1:2 end-1:end],:) = nan;
mesh(ts(1:3:end),xs(:),us(1:3:end,:)'), view(65,60)
colormap(0.7*hsv)
xlabel('time t'), ylabel('space x'), zlabel('u(x,t)')
ifOurCf2eps([mfilename 'Uxt'])
%{
\end{matlab}
Fin.
\subsection{The Swift--Hohenberg PDE and BCs inside patches}
As a microscale discretisation of Swift--Hohenberg \pde\
\(u_t= -(1+\partial_{x}^2/k_0^2)^2u +\Ra u -u^3\), here code
straightforward centred discretisation in space.
\begin{matlab}
%}
function ut=SwiftHohenbergPDE(t,u,patches,k0,Ra)
dx=diff(patches.x(1:2)); % microscale spacing
i=3:size(u,1)-2; % interior points in patches
%{
\end{matlab}
Code Dirichlet boundary conditions of zero function and
derivative, \(u=u_x=0\), at the left-end of the
leftmost-patch, and the right-end of the rightmost-patch.
For slightly simpler coding, squeeze out the two singleton
dimensions.
\begin{matlab}
%}
u = squeeze(u);
u(1:2,1)=0;
u(end-1:end,end)=0;
%{
\end{matlab}
Here code straightforward centred discretisation in space.
\begin{matlab}
%}
ut=nan+u; % preallocate output array
v = u(2:end-1,:)+diff(u,2)/dx^2/k0^2;
ut(i,:) = -( v(2:end-1,:)+diff(v,2)/dx^2/k0^2 ) ...
+Ra*u(i,:) -u(i,:).^3;
end
%{
\end{matlab}
\subsection{\texttt{theRes()}: wrapper function to zero for equilibria}
\label{sec:theRes}
This functions converts a vector of values into the interior
values of the patches, then evaluates the time derivative of
the system at time zero, and returns the vector of
patch-interior time derivatives.
\begin{matlab}
%}
function f=theRes(u,patches,k0,Ra)
v=nan(size(patches.x));
v(patches.i) = u;
f = patchSys1(0,v(:),patches,k0,Ra);
f = f(patches.i);
end%function theRes
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/patchEdgeInt2.m
| 21,894 |
utf_8
|
69c7eba8d39f1ca697e955100def73e9
|
% patchEdgeInt2() provides the interpolation across 2D space
% for 2D patches of simulations of a lattice system such as
% a PDE discretisation. AJR, Nov 2018 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt2()}: sets 2D patch
edge values from 2D macroscale interpolation}
\label{sec:patchEdgeInt2}
Couples 2D patches across 2D space by computing their edge
values via macroscale interpolation. Research
\cite[]{Roberts2011a, Bunder2019d} indicates the patch
centre-values are sensible macroscale variables, and
macroscale interpolation of these determine patch-edge
values. However, for computational homogenisation in
multi-D, interpolating patch next-to-edge values appears
better \cite[]{Bunder2020a}. This function is primarily
used by \verb|patchSys2()| but is also useful for user
graphics. \footnote{Script \texttt{patchEdgeInt2test.m}
verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global
struct~\verb|patches|.
\begin{matlab}
%}
function u = patchEdgeInt2(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP1| \cdot \verb|nSubP2| \cdot \verb|nPatch1|
\cdot \verb|nPatch2|$ multiscale spatial grid on the
$\verb|nPatch1| \cdot \verb|nPatch2|$ array of patches.
\item \verb|patches| a struct set by \verb|configPatches2()|
which includes the following information.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP1| \times1 \times1 \times1
\times \verb|nPatch1| \times1 $ array of the spatial
locations~$x_{iI}$ of the microscale grid points in every
patch. Currently it \emph{must} be an equi-spaced lattice on
the microscale index~$i$, but may be variable spaced in
macroscale index~$I$.
\item \verb|.y| is similarly $1 \times \verb|nSubP2| \times1
\times1 \times1 \times \verb|nPatch2|$ array of the spatial
locations~$y_{jJ}$ of the microscale grid points in every
patch. Currently it \emph{must} be an equi-spaced lattice on
the microscale index~$j$, but may be variable spaced in
macroscale index~$J$.
\item \verb|.ordCC| is order of interpolation, currently
only $\{0,2,4,\ldots\}$
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left, right, top and bottom boundaries so interpolation is
via divided differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation. Currently must be zero.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation in both the
$x,y$-directions---when invoking a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation: true, from opposite-edge
next-to-edge values (often preserves symmetry); false, from
centre cross-patch values (near original scheme).
\item \verb|.nEdge|, two elements, the width of edge
values set by interpolation at the \(x,y\)-edge regions,
respectively, of each patch (default is one for both
\(x,y\)-edges).
\item \verb|.nEnsem| the number of realisations in the
ensemble.
\item \verb|.parallel| whether serial or parallel.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 6D array, $\verb|nSubP1| \cdot
\verb|nSubP2| \cdot \verb|nVars| \cdot \verb|nEnsem| \cdot
\verb|nPatch1| \cdot \verb|nPatch2|$, of the fields with
edge values set by interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[~,ny,~,~,~,Ny] = size(patches.y);
[nx,~,~,~,Nx,~] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round(numel(u)/numel(patches.x)/numel(patches.y)/nEnsem);
assert(numel(u) == nx*ny*Nx*Ny*nVars*nEnsem ...
,'patchEdgeInt2: input u has wrong size for parameters')
u = reshape(u,[nx ny nVars nEnsem Nx Ny ]);
%{
\end{matlab}
For the moment assume the physical domain is either
macroscale periodic or macroscale rectangle so that the
coupling formulas are simplest. These index vectors point
to patches and, if periodic, their four immediate neighbours.
\begin{matlab}
%}
I=1:Nx; Ip=mod(I,Nx)+1; Im=mod(I-2,Nx)+1;
J=1:Ny; Jp=mod(J,Ny)+1; Jm=mod(J-2,Ny)+1;
%{
\end{matlab}
\paragraph{Implement multiple width edges by folding}
Subsample~\(x,y\) coordinates, noting it is only differences
that count \emph{and} the microgrid~\(x,y\) spacing must be
uniform.
\begin{matlab}
%}
%x = patches.x;
%if patches.nEdge(1)>1
% m = patches.nEdge(1);
% x = x(1:m:nx,:,:,:,:,:);
% nx = nx/m;
% u = reshape(u,m,nx,ny,nVars,nEnsem,Nx,Ny);
% nVars = nVars*m;
% u = reshape( permute(u,[2:3 1 4:7]) ...
% ,nx,ny,nVars,nEnsem,Nx,Ny);
%end%if patches.nEdge(1)
%y = patches.y;
%if patches.nEdge(2)>1
% m = patches.nEdge(2);
% y = y(:,1:m:ny,:,:,:,:);
% ny = ny/m;
% u = reshape(u,nx,m,ny,nVars,nEnsem,Nx,Ny);
% nVars = nVars*m;
% u = reshape( permute(u,[1 3 2 4:7]) ...
% ,nx,ny,nVars,nEnsem,Nx,Ny);
%end%if patches.nEdge(2)
x = patches.x;
y = patches.y;
if mean(patches.nEdge)>1
mx = patches.nEdge(1);
my = patches.nEdge(2);
x = x(1:mx:nx,:,:,:,:,:);
y = y(:,1:my:ny,:,:,:,:);
nx = nx/mx;
ny = ny/my;
u = reshape(u,mx,nx,my,ny,nVars,nEnsem,Nx,Ny);
nVars = nVars*mx*my;
u = reshape( permute(u,[2 4 1 3 5:8]) ...
,nx,ny,nVars,nEnsem,Nx,Ny);
end%if patches.nEdge
%{
\end{matlab}
The centre of each patch (as \verb|nx| and~\verb|ny| are
odd for centre-patch interpolation) is at indices
\begin{matlab}
%}
i0 = round((nx+1)/2);
j0 = round((ny+1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches.
\begin{matlab}
%}
rx = patches.ratio(1);
ry = patches.ratio(2);
%{
\end{matlab}
\subsubsection{Lagrange interpolation gives patch-edge values}
Compute centred differences of the mid-patch values for the
macro-interpolation, of all fields. Here the domain is
macro-periodic.
\begin{matlab}
%}
ordCC = patches.ordCC;
if ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in corner values. Start with
\(x\)-direction, and give most documentation for that case
as the \(y\)-direction is essentially the same.
\paragraph{\(x\)-normal edge values} The patch-edge values
are either interpolated from the next-to-edge values, or
from the centre-cross values (not the patch-centre value
itself as that seems to have worse properties in general).
Have not yet implemented core averages.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u([2 nx-1],2:(ny-1),:,:,I,J);
else % interpolate centre-cross values
U = u(i0,2:(ny-1),:,:,I,J);
end;%if patches.EdgyInt
%{
\end{matlab}
Just in case any last array dimension(s) are one, we force a
padding of the sizes, then adjoin the extra dimension for
the subsequent array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,6-length(szUO)) ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in these arrays. When parallel, in order
to preserve the distributed array structure we use an index
at the end for the differences.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 7D
else dmu = zeros(szUO,patches.codist); % 7D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
% dmux(:,:,:,:,I,:,1) = (Ux(:,:,:,:,Ip,:)+Ux(:,:,:,:,Im,:))/2; % \mu
% dmux(:,:,:,:,I,:,2) = (Ux(:,:,:,:,Ip,:)-Ux(:,:,:,:,Im,:)); % \delta
% Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
% dmuy(:,:,:,:,:,J,1) = (Ux(:,:,:,:,:,Jp)+Ux(:,:,:,:,:,Jm))/2; % \mu
% dmuy(:,:,:,:,:,J,2) = (Ux(:,:,:,:,:,Jp)-Ux(:,:,:,:,:,Jm)); % \delta
% Jp = Jp(Jp); Jm = Jm(Jm); % increase shifts to \pm2
else %disp('starting standard interpolation')
dmu(:,:,:,:,I,:,1) = (U(:,:,:,:,Ip,:) ...
-U(:,:,:,:,Im,:))/2; %\mu\delta
dmu(:,:,:,:,I,:,2) = (U(:,:,:,:,Ip,:) ...
-2*U(:,:,:,:,I,:) +U(:,:,:,:,Im,:)); %\delta^2
end% if patches.stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,I,:,k) = dmu(:,:,:,:,Ip,:,k-2) ...
-2*dmu(:,:,:,:,I,:,k-2) +dmu(:,:,:,:,Im,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet edge values for
each patch \cite[]{Roberts06d, Bunder2013b}, using weights
computed in \verb|configPatches2()|. Here interpolate to
specified order.
For the case where next-to-edge values interpolate to the
opposite edge-values: when we have an ensemble of
configurations, different configurations might be coupled to
each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to| and \verb|patches.bo|.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two edges
u(nx,2:(ny-1),:,patches.ri,I,:) ...
= U(1,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,1),-6).*dmu(1,:,:,:,:,:,:) ,7);
u(1 ,2:(ny-1),:,patches.le,I,:,:) ...
= U(k,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,1),-6).*dmu(k,:,:,:,:,:,:) ,7);
%{
\end{matlab}
\paragraph{\(y\)-normal edge values} Interpolate from either
the next-to-edge values, or the centre-cross-line values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,[2 ny-1],:,:,I,J);
else % interpolate centre-cross values
U = u(:,j0,:,:,I,J);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,6-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 7D
else dmu = zeros(szUO,patches.codist); % 7D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,J,1) = (U(:,:,:,:,:,Jp) ...
-U(:,:,:,:,:,Jm))/2; %\mu\delta
dmu(:,:,:,:,:,J,2) = (U(:,:,:,:,:,Jp) ...
-2*U(:,:,:,:,:,J) +U(:,:,:,:,:,Jm)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,J,k) = dmu(:,:,:,:,:,Jp,k-2) ...
-2*dmu(:,:,:,:,:,J,k-2) +dmu(:,:,:,:,:,Jm,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches2()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k = 1+patches.EdgyInt; % use centre or two edges
u(:,ny,:,patches.to,:,J) ...
= U(:,1,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,2),-6).*dmu(:,1,:,:,:,:,:) ,7);
u(:,1 ,:,patches.bo,:,J) ...
= U(:,k,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,2),-6).*dmu(:,k,:,:,:,:,:) ,7);
%{
\end{matlab}
\subsubsection{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
We interpolate in terms of the patch index, $j$~say, not
directly in space. As the macroscale fields are $N$-periodic
in the patch index~$I$, the macroscale Fourier transform
writes the centre-patch values as $U_I=\sum_{k}C_ke^{ik2\pi
I/N}$. Then the edge-patch values $U_{I\pm r}
=\sum_{k}C_ke^{ik2\pi/N(I\pm r)} =\sum_{k}C'_ke^{ik2\pi
I/N}$ where $C'_k=C_ke^{ikr2\pi/N}$. For $N$~patches we
resolve `wavenumbers' $|k|<N/2$, so set row vector
$\verb|ks|=k2\pi/N$ for `wavenumbers' $\mathcode`\,="213B
k=(0,1, \ldots, k_{\max}, -k_{\max}, \ldots, -1)$ for
odd~$N$, and $\mathcode`\,="213B k=(0,1, \ldots, k_{\max},
\pm(k_{\max}+1) -k_{\max}, \ldots, -1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches2|
tests there are an even number of patches). Then the
patch-ratio is effectively halved. The patch edges are near
the middle of the gaps and swapped.
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
error('staggered grid not yet implemented??')
v=nan(size(u)); % currently to restore the shape of u
u=cat(3,u(:,1:2:nPatch,:),u(:,2:2:nPatch,:));
stagShift=reshape(0.5*[ones(nVars,1);-ones(nVars,1)],1,1,[]);
iV=[nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r=r/2; % ratio effectively halved
nPatch=nPatch/2; % halve the number of patches
nVars=nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Interpolate the two directions in succession, in this way we
naturally fill-in edge-corner values. Start with
\(x\)-direction, and give most documentation for that case
as the other is essentially the same. Need these indices of
patch interior.
\begin{matlab}
%}
ix = 2:nx-1; iy = 2:ny-1;
%{
\end{matlab}
\paragraph{\(x\)-normal edge values} Now set wavenumbers
into a vector at the correct dimension. In the case of
even~$N$ these compute the $+$-case for the highest
wavenumber zig-zag mode, $\mathcode`\,="213B k=(0,1, \ldots,
k_{\max}, +(k_{\max}+1) -k_{\max}, \ldots, -1)$.
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
kr = shiftdim( rx*2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ,-3);
%{
\end{matlab}
Compute the Fourier transform of the centre-cross values.
Unless doing patch-edgy interpolation when FT the
next-to-edge values. If there are an even number of points,
then if complex, treat as positive wavenumber, but if real,
treat as cosine. When using an ensemble of configurations,
different configurations might be coupled to each other, as
specified by \verb|patches.le|, \verb|patches.ri|,
\verb|patches.to| and \verb|patches.bo|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(i0,iy,:,:,:,:) ,[],5);
Cp = Cm;
else
Cm = fft( u( 2,iy ,:,patches.le,:,:) ,[],5);
Cp = fft( u(nx-1,iy ,:,patches.ri,:,:) ,[],5);
end%if ~patches.EdgyInt
%{
\end{matlab}
Now invert the Fourier transforms to complete interpolation.
Enforce reality when appropriate.
\begin{matlab}
%}
u(nx,iy,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],5) );
u( 1,iy,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],5) );
%{
\end{matlab}
\paragraph{\(y\)-normal edge values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Ny-1)/2);
kr = shiftdim( ry*2*pi/Ny*(mod((0:Ny-1)+kMax,Ny)-kMax) ,-4);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-lines for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,j0,:,:,:,:) ,[],6);
Cp = Cm;
else
Cm = fft( u(:,2 ,:,patches.bo,:,:) ,[],6);
Cp = fft( u(:,ny-1 ,:,patches.to,:,:) ,[],6);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,ny,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],6) );
u(:, 1,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],6) );
%{
\end{matlab}
\begin{matlab}
%}
end% if ordCC>0 else, so spectral
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|px| and~\verb|py|
(potentially different in the different directions!), and
hence size of the (forward) divided difference tables
in~\verb|F|~(7D) for interpolating to left/right, and
top/bottom edges. Because of the product-form of the patch
grid, and because we are doing \emph{only} either edgy
interpolation or cross-patch interpolation (\emph{not} just
the centre patch value), the interpolations are all 1D
interpolations.
\begin{matlab}
%}
if patches.ordCC<1
px = Nx-1; py = Ny-1;
else px = min(patches.ordCC,Nx-1);
py = min(patches.ordCC,Ny-1);
end
ix=2:nx-1; iy=2:ny-1; % indices of edge 'interior' (ix n/a)
%{
\end{matlab}
\subsubsection{\(x\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-edge values are because their
values are to interpolate to the opposite edge of each
patch. \todo{Have no plans to implement core averaging as
yet.}
\begin{matlab}
%}
F = nan(patches.EdgyInt+1,ny-2,nVars,nEnsem,Nx,Ny,px+1);
if patches.EdgyInt % interpolate next-to-edge values
F(:,:,:,:,:,:,1) = u([nx-1 2],iy,:,:,:,:);
X = x([nx-1 2],:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,1) = u(i0,iy,:,:,:,:);
X = x(i0,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
\paragraph{Form tables of divided differences} Compute
tables of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable, and
across ensemble, and for left/right edges. Recursively find
all divided differences.
\begin{matlab}
%}
for q = 1:px
i = 1:Nx-q;
F(:,:,:,:,i,:,q+1) ...
= (F(:,:,:,:,i+1 ,:,q)-F(:,:,:,:,i,:,q)) ...
./(X(:,:,:,:,i+q,:) -X(:,:,:,:,i,:));
end
%{
\end{matlab}
\paragraph{Interpolate with divided differences} Now
interpolate to find the edge-values on left/right edges
at~\verb|Xedge| for every interior~\verb|Y|.
\begin{matlab}
%}
Xedge = x([1 nx],:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|i| are those of the left edge of
each interpolation stencil, because the table is of forward
differences. This alternative: the case of order~\(p_x\)
and~\(p_y\) interpolation across the domain, asymmetric near
the boundaries of the rectangular domain.
\begin{matlab}
%}
i = max(1,min(1:Nx,Nx-ceil(px/2))-floor(px/2));
Uedge = F(:,:,:,:,i,:,px+1);
for q = px:-1:1
Uedge = F(:,:,:,:,i,:,q)+(Xedge-X(:,:,:,:,i+q-1,:)).*Uedge;
end
%{
\end{matlab}
Finally, insert edge values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,iy,:,patches.le,:,:) = Uedge(1,:,:,:,:,:);
u(nx,iy,:,patches.ri,:,:) = Uedge(2,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(y\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,patches.EdgyInt+1,nVars,nEnsem,Nx,Ny,py+1);
if patches.EdgyInt % interpolate next-to-edge values
F(:,:,:,:,:,:,1) = u(:,[ny-1 2],:,:,:,:);
Y = y(:,[ny-1 2],:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,1) = u(:,j0,:,:,:,:);
Y = y(:,j0,:,:,:,:);
end;
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:py
j = 1:Ny-q;
F(:,:,:,:,:,j,q+1) ...
= (F(:,:,:,:,:,j+1 ,q)-F(:,:,:,:,:,j,q)) ...
./(Y(:,:,:,:,:,j+q) -Y(:,:,:,:,:,j));
end
%{
\end{matlab}
Interpolate to find the edge-values on top/bottom
edges~\verb|Yedge| for every~\(x\).
\begin{matlab}
%}
Yedge = y(:,[1 ny],:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|j| are those of the bottom edge
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
j = max(1,min(1:Ny,Ny-ceil(py/2))-floor(py/2));
Uedge = F(:,:,:,:,:,j,py+1);
for q = py:-1:1
Uedge = F(:,:,:,:,:,j,q)+(Yedge-Y(:,:,:,:,:,j+q-1)).*Uedge;
end
%{
\end{matlab}
Finally, insert edge values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,1 ,:,patches.bo,:,:) = Uedge(:,1,:,:,:,:);
u(:,ny,:,patches.to,:,:) = Uedge(:,2,:,:,:,:);
%{
\end{matlab}
\subsubsection{Optional NaNs for safety}
We want a user to set outer edge values on the extreme
patches according to the microscale boundary conditions that
hold at the extremes of the domain. Consequently, unless testing, override
their computed interpolation values with~\verb|NaN|.
\begin{matlab}
%}
if isfield(patches,'intTest')&&patches.intTest
else % usual case
u( 1,:,:,:, 1,:) = nan;
u(nx,:,:,:,Nx,:) = nan;
u(:, 1,:,:,:, 1) = nan;
u(:,ny,:,:,:,Ny) = nan;
end%if
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic else
%{
\end{matlab}
\paragraph{Unfold multiple edges} No need to restore~\(x,y\).
\begin{matlab}
%}
if mean(patches.nEdge)>1
nVars = nVars/(mx*my);
u = reshape( u ,nx,ny,mx,my,nVars,nEnsem,Nx,Ny);
nx = nx*mx;
ny = ny*my;
u = reshape( permute(u,[3 1 4 2 5:8]) ...
,nx,ny,nVars,nEnsem,Nx,Ny);
end%if patches.nEdge
%{
\end{matlab}
Fin, returning the 6D array of field values with
interpolated edges.
\begin{matlab}
%}
end% function patchEdgeInt2
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
SwiftHohenbergHetero.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/SwiftHohenbergHetero.m
| 13,923 |
utf_8
|
24872db870e64f9f9566f80b37600307
|
% Simulate a heterogeneous version of Swift--Hohenberg PDE
% in 1D on patches as an example application with pairs of
% edge points needing to be interpolated between patches in
% space. AJR, 28 Mar 2023
%!TEX root = doc.tex
%{
\section{\texttt{SwiftHohenbergHetero}: patterns of a
heterogeneous Swift--Hohenberg PDE in 1D on patches}
\label{sec:SwiftHohenbergHetero}
\localtableofcontents
\cref{fig:SwiftHohenbergHeteroU} shows an example simulation
in time generated by the patch scheme applied to the
patterns arising from a heterogeneous version of the
Swift--Hohenberg \pde. That such simulations of patterns
makes valid predictions was established by
\cite{Bunder2013b} who proved that the scheme is accurate
when the number of points in a patch is tied to a multiple
of the periodicity of the pattern.
\begin{figure}
\centering \caption{\label{fig:SwiftHohenbergHeteroU} the
field~\(u(x,t)\) in the patch (gap-tooth) scheme applied to
microscale heterogeneous Swift--Hohenberg \pde\
(\cref{sec:SwiftHohenbergHetero}). The heterogeneous
coefficients are approximately uniform over~\([0.9,1.1]\).
This heterogeneity has no noticeable affect on the
simulation.}
\includegraphics[scale=0.85]{r26479SwiftHohenbergHeteroUxt}
\end{figure}%
Consider a lattice of values~\(u_i(t)\), with lattice
spacing~\(dx\), arising from a microscale discretisation of
the pattern forming, heterogeneous, Swift--Hohenberg \pde
\begin{equation}
\partial_t u=-D[c_1(x)Du] +\Ra u-u^3,
\quad D:=1+\partial_x[c_2(x)\partial_x\cdot]/k_0^2,
\label{eq:SwiftHohenbergHetero}
\end{equation}
where \(c_\ell(x)\) have period~\(2\pi/k_0\).
Coefficients~\(c_\ell\) are chosen iid random, nearly
uniform, with mean near one. With mean one, the
periodicity of~\(c_\ell\) approximately matches the
periodicity of the resultant spatial pattern.
The current patch scheme coding preserves symmetry in the
case of periodic patches (for every order of interpolation).
For equispace and chebyshev options, the coupling currently
fails symmetry.
Consider the spectrum in the symmetric cases of periodic
patches (based upon only the cases \(N=5,7\)). There are
\(2N\)~small eigenvalues, separated by a gap from the rest.
In the homogeneous case, these occur as \(N\)~pairs. With
small heterogeneity, they appear to split into
\(N-1\)~pairs, and two distinct. With stronger heterogeneity
(say~\(0.5\)), they \emph{often} appear to also split into
two clusters, each of~\(N\) eigenvalues, with one
small-valued cluster, and one meso-valued cluster---curious.
Further analysis with sparse approximation of the invariant
spaces suggests the following:
\begin{itemize}
\item for homogeneous, the \(2N\)~modes are local
oscillations in each patch, with two modes each
corresponding to phase shifts of the possible oscillations;
\item for heterogeneous \begin{itemize}
\item \(N\)~eigenmodes appear to be one phase `locking' to
the heterogeneity; and
\item \(N\)~eigenmodes appear to be other phase `locking' to
the heterogeneity. Unless it is something to do with the
coupling, but then it only appears with heterogeneity.
\end{itemize}
\end{itemize}
Consider the spectrum with BCs of \(u=u_{xx}=0\) at ends.
Non-symmetric so some eigenvalues are complex! For small or
zero heterogeneity find \(2N-2\) eigenvalues are small.
Effectively, two modes in each of \(N-2\) interior patches,
and one mode each in the two end patches. With increasing
heterogeneity (say above~\(0.3\)), the gap decreases as a
couple (or some) of the small eigenvalues become larger in
magnitude.
Consider the spectrum with BCs of \(u=u_{x}=0\) at ends.
Non-symmetric so some eigenvalues are complex! For small or
zero heterogeneity find \(2N-4\) eigenvalues are small.
Effectively, two modes in each of \(N-2\) interior patches.
With increasing heterogeneity (say above~\(0.4\)), half
\((N-2)\) of the small eigenvalues become larger in
magnitude (presumably some phase `locking' to the
heterogeneity): effectively forms two clusters of modes.
Set the desired microscale periodicity of the patterns,
here~\(0.062\), and on the microscale lattice of
spacing~\(0.0062\), correspondingly choose random microscale
material coefficients. The wavenumber of this microscale
patterns is \(k_0\approx 101\).
\begin{matlab}
%}
clear all
%global OurCf2eps, OurCf2eps=true %optional to save plots
basename = ['r' num2str(floor(1e5*rem(now,1))) mfilename]
Ra = 0.1 % Ra>0 leads to patterns
nGap = 8 % controls size of gap between patches
waveLength = 0.496688741721854 /nGap %for nPatch==5
%waveLength = 0.497630331753555 /nGap %for nPatch==7
%waveLength = 0.5 /nGap %for periodic case
nPtsPeriod = 10
dx = waveLength/nPtsPeriod
k0 = 2*pi/waveLength
%{
\end{matlab}
Create some random heterogeneous coefficients.
\begin{matlab}
%}
heteroVar = 0.99*[1 1] % must be <2
cl = 1./(1-heteroVar/2+heteroVar.*rand(nPtsPeriod,2));
cRange = quantile(cl,0:0.5:1)
%{
\end{matlab}
Establish global data struct~\verb|patches| for
heterogeneous Swift--Hohenberg \pde\ with, on average, one
patch per units length. Use seven patches to start with.
Quartic (fourth-order) interpolation \(\verb|ordCC|=4\)
provides values for the inter-patch coupling conditions.
Or use as high-order as possible with \(\verb|ordCC|=0\).
\begin{matlab}
%}
nPatch = 5
nSubP = 2*nPtsPeriod+4 % +2 for not-edgyInt
%nSubP = 2*nGap*nPtsPeriod+4 % approx full-domain
Len = nPatch;
ordCC = 0;
dom.type='equispace';
dom.bcOffset=0.5
patches = configPatches1(@heteroSwiftHohenbergPDE,[0 Len],dom ...
,nPatch,ordCC,dx,nSubP,'EdgyInt',true,'nEdge',2 ...
,'hetCoeffs',cl);
xs=squeeze(patches.x);
%{
\end{matlab}
\subsubsection{Explore the Jacobian}
Finds that with periodic patches, everything is symmetric.
However, for equispace or chebyshev, the patch coupling is
not symmetric---is this to be expected?
\begin{matlab}
%}
fprintf('\n**** Explore the Jacobian\n')
u0 = 0*patches.x;
u0([1:2 end-1:end],:) = nan;
patches.i = find(~isnan(u0));
nVars = numel(patches.i)
Jac = nan(nVars);
for j=1:nVars
Jac(:,j)=theRes((1:nVars)==j,patches,k0,0,0);
end
%{
\end{matlab}
Check on the symmetry of the Jacobian
\begin{matlab}
%}
nonSymmetric = norm(Jac-Jac')
Jac(abs(Jac)<1e-12)=0;
antiJac = Jac-Jac';
antiJac(abs(antiJac)<1e-12)=0;
figure(6),clf
spy(Jac,'.'),hold on, spy(antiJac,'rx'),hold off
if nonSymmetric>5e-9, warning('failed symmetry'),
else Jac = (Jac+Jac')/2; %tweak to symmetry
end
%{
\end{matlab}
Compute eigenvalues and eigenvectors.
\begin{matlab}
%}
figure(5),clf
[evec,mEval] = eig(-Jac ,'vector');
[~,j]=sort(real(mEval));
mEval=mEval(j); evec=evec(:,j);
loglog(real(mEval),'.')
ylabel('$-\Re\lambda$')
ifOurCf2tex([basename 'Eval'])%optionally save
%{
\end{matlab}
\begin{SCfigure}
\centering
\caption{\label{fig:SwiftHohenbergHeteroEval} eigenvalues of
the patch scheme on the heterogeneous Swift--Hohenberg \pde\
(linearised). With \(N=5\) patches and \bc{}s of
\(u=u_x=0\) at \(x\in\{0,5\}\), there are \(2(N-2)=6\) small
eigenvalues, \(|\lambda|<0.001\), corresponding to six slow
modes in the interior.}
\def\extraAxisOptions{mark size=1pt}
\input{Figs/r26479SwiftHohenbergHeteroEval}
\end{SCfigure}
Explore sparse approximations of all the slowest together
(lots of iterations required), or separately of the two
clusters of the slowest (few iterations needed). First
ascertain whether one or two clusters of small eigenvalues.
\begin{matlab}
%}
logGaps=diff(log10(real(mEval)));
[~,j]=sort(-logGaps);
%someLogGaps=[logGaps(j(1:5)) j(1:5)]
if logGaps(j(2))<0.4*logGaps(j(1)), nSlow=j(1)
else nSlow=min( sort(j(1:2)) , 3*nPatch)
end
log10Gap=logGaps(nSlow)
smallEvals=-mEval(1:nSlow(end)+2)
%{
\end{matlab}
Second, make eigenvectors all real, sparsely approximate
cluster modes via an algorithm developed from
\cite{ZhenfangHu2014}, and plot.
\cref{fig:SwiftHohenbergHeteroEvec} shows that each pair of
basis vectors are phase-shifted by~\(90^\circ\).
\begin{matlab}
%}
js=find(imag(mEval)>0);
evec(:,js)=imag(evec(:,js));
evec=real(evec);
if numel(nSlow)==1, S = spcart(evec(:,1:nSlow));
else S = spcart(evec(:,1:nSlow(1)));
S = [S spcart(evec(:,nSlow(1)+1:nSlow(2))) ];
end;
figure(3),clf
vStep=ceil(max(abs(S(:)))*10+1)/10
for j=1:nSlow(end)
u0(patches.i)=S(:,j);
plot(xs,vStep*(j-1)+squeeze(u0),'.-'),hold on
end
hold off, xlabel('space $x$')
ifOurCf2tex([basename 'Evec'])%optionally save
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:SwiftHohenbergHeteroEvec} sparse
approximations of the eigenvectors of the six slow modes of
\cref{fig:SwiftHohenbergHeteroEval}. Plotted are sparse
basis vectors for the invariant space spanned by the six
slow eigenvectors: each basis vector shifted vertically to
separate. Thus a fair approximation is that there are
effectively two modes for each of the \(N-2=3\) interior
patches.}
\def\extraAxisOptions{small, mark size=1pt, width=13cm, height=7cm}
\input{Figs/r26479SwiftHohenbergHeteroEvec}
\end{figure}
Reorganise the eigenvectors to maybe clarify.
\begin{matlab}
%}
[i,j]=find(abs(S)>vStep/2);
j=find([1;diff(j)]);
[i,k]=sort(i(j));
figure(4)
for p=1:2
clf,subplot(2,1,1)
for j=p:2:numel(k)
u0(patches.i)=S(:,k(j));
plot(xs,squeeze(u0),'.-'),hold on
end% for j
hold off, xlabel('space $x$')
ifOurCf2tex([basename 'Evec' num2str(p)])%optionally save
end%for p
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:SwiftHohenbergHeteroEvec2} sparse basis
approximations for the invariant subspace of the six slow
modes of \cref{fig:SwiftHohenbergHeteroEval}. A replot of
\cref{fig:SwiftHohenbergHeteroEvec} but with three of the
basis vectors superimposed in each of the two panels.}
\def\extraAxisOptions{small, mark size=1pt, width=13cm, height=3cm}
\input{Figs/r26479SwiftHohenbergHeteroEvec1}
\input{Figs/r26479SwiftHohenbergHeteroEvec2}
\end{figure}
\subsubsection{Find an equilibrium with fsolve}
Start the search from some guess.
\begin{matlab}
%}
fprintf('\n**** Find equilibrium with fsolve\n')
u = 0.4*sin(2*pi/waveLength*patches.x);
%{
\end{matlab}
But set the pairs of patch-edge values to \verb|Nan| in
order to use \verb|patches.i| to index the interior
sub-patch points as they are the variables.
\begin{matlab}
%}
u([1:2 end-1:end],:) = nan;
patches.i = find(~isnan(u));
%{
\end{matlab}
Seek the equilibrium, and report the norm of the residual,
via the generic patch system wrapper \verb|theRes|
(\cref{sec:theResSWhetero}).
\begin{matlab}
%}
tic
[u(patches.i),res] = fsolve(@(v) theRes(v,patches,k0,Ra,1) ...
,u(patches.i) ,optimoptions('fsolve','Display','off'));
solveTime = toc
normRes = norm(res)
if normRes>1e-7, warning('residual large: bad equilibrium'),end
%{
\end{matlab}
\paragraph{Plot the equilibrium} see
\cref{fig:SwiftHohenbergHeteroEquilib}.
\begin{matlab}
%}
figure(1),clf
subplot(2,1,1)
plot(xs,squeeze(u),'.-')
xlabel('space $x$'),ylabel('equilibrium $u(x)$')
ifOurCf2tex([basename 'Equilib'])%optionally save
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:SwiftHohenbergHeteroEquilib} an
equilibrium of the heterogeneous Swift--Hohenberg \pde\
determined by the patch scheme}
\def\extraAxisOptions{small, mark size=1pt, width=13cm, height=4cm}
\input{Figs/r26479SwiftHohenbergHeteroEquilib}
\end{figure}
\subsubsection{Simulate in time}
Set an initial condition, and here integrate forward in time
using a standard method for stiff systems---because of the
simplicity of linear problems this method works quite
efficiently here. Integrate the interface \verb|patchSys1|
(\cref{sec:patchSys1}) to the microscale differential
equations.
\begin{matlab}
%}
fprintf('\n**** Simulate in time\n')
u0 = 0*sin(2*pi/waveLength*patches.x)+0.1*randn(nSubP,1,1,nPatch);
tic
[ts,us] = ode15s(@patchSys1, [0 40], u0(:) ,[],patches,k0,Ra,1);
simulateTime = toc
us = reshape(us,length(ts),numel(patches.x(:)),[]);
%{
\end{matlab}
Plot the simulation in \cref{fig:SwiftHohenbergHeteroU}.
\begin{matlab}
%}
figure(2),clf
xs([1:2 end-1:end],:) = nan;
mesh(ts(1:3:end),xs(:),us(1:3:end,:)'), view(65,60)
colormap(0.7*hsv)
xlabel('time t'), ylabel('space x'), zlabel('u(x,t)')
ifOurCf2eps([basename 'Uxt'])
%{
\end{matlab}
Fin.
\subsection{Heterogeneous SwiftHohenberg PDE+BCs inside patches}
As a microscale discretisation of Swift--Hohenberg \pde\
\(u_t= -D[c_1(x)Du] +\Ra u -u^3\), where heterogeneous
operator \(D = 1 +\partial_x( c_2(x) \partial_x )/k_0^2\).
\begin{matlab}
%}
function ut=heteroSwiftHohenbergPDE(t,u,patches,k0,Ra,cubic)
dx=diff(patches.x(1:2)); % microscale spacing
i=3:size(u,1)-2; % interior points in patches
%{
\end{matlab}
Code a couple of different boundary conditions of zero
function and derivative(s) at left-end of left-patch, and
right-end of right-patch. For slightly simpler coding,
squeeze out the two singleton dimensions.
\begin{matlab}
%}
u = squeeze(u);
if ~patches.periodic
switch 1
case 1 % these are u=u_x=0
u(1:2,1)=0;
u(end-1:end,end)=0;
case 2 % these are u=u_{xx}=0
u(1:2,1) = [-u(3,1); 0];
u(end-1:end,end) = [0; -u(end-2,end)];
end% case
end%if
%{
\end{matlab}
Here code straightforward centred discretisation in space.
\begin{matlab}
%}
ut = nan+u; % preallocate output array
v = u(2:end-1,:)+diff(patches.cs(: ,2).*diff(u))/dx^2/k0^2;
v = v.*patches.cs(2:end,1);
v = v(2:end-1,:)+diff(patches.cs(2:end-1,2).*diff(v))/dx^2/k0^2;
ut(i,:) = -v +Ra*u(i,:) -cubic*u(i,:).^3;
end
%{
\end{matlab}
\subsection{\texttt{theRes()}: a wrapper function}
\label{sec:theResSWhetero}
This functions converts a vector of values into the interior
values of the patches, then evaluates the time derivative of
the system at time zero, and returns the vector of
patch-interior time derivatives.
\begin{matlab}
%}
function f=theRes(u,patches,k0,Ra,cubic)
v=nan(size(patches.x));
v(patches.i) = u;
f = patchSys1(0,v(:),patches,k0,Ra,cubic);
f = f(patches.i);
end%function theRes
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchSys2.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/patchSys2.m
| 3,739 |
utf_8
|
89dfc4cb2288733f30c09a385da6fe21
|
% patchSys2() Provides an interface to time integrators
% for the dynamics on patches in 2D coupled across space.
% The system must be a lattice system such as PDE
% discretisations. AJR, Nov 2018 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchSys2()}: interface 2D space to time integrators}
\label{sec:patchSys2}
To simulate in time with 2D spatial patches we often need to
interface a users time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function provides an interface. Communicate
patch-design variables (\cref{sec:configPatches2}) either
via the global struct~\verb|patches| or via an optional
third argument. \verb|patches| is required for the parallel
computing of \verb|spmd|, or if parameters are to be passed
though to the user microscale function.
\begin{matlab}
%}
function dudt = patchSys2(t,u,patches,varargin)
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP(1)| \times \verb|nSubP(2)| \times
\verb|nPatch(1)| \times \verb|nPatch(2)|$ grid.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches2()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches,...)| that computes the time
derivatives on the patchy lattice. The array~\verb|u| has
size $\verb|nSubP(1)| \times \verb|nSubP(2)| \times
\verb|nVars| \times \verb|nEsem| \times \verb|nPatch(1)|
\times \verb|nPatch(2)|$. Time derivatives must be computed
into the same sized array, although herein the patch
edge-values are overwritten by zeros.
\item \verb|.x| is $\verb|nSubP(1)| \times1 \times1 \times1
\verb|nPatch(1)| \times1$ array of the spatial
locations~$x_{i}$ of the microscale $(i,j)$-grid points
in every patch. Currently it \emph{must} be an equi-spaced
lattice on both macro- and micro-scales.
\item \verb|.y| is similarly $1 \times \verb|nSubP(2)|
\times1 \times1 \times1 \times \verb|nPatch(2)|$ array of
the spatial locations~$y_{j}$ of the microscale
$(i,j)$-grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on both macro- and
micro-scales.
\end{itemize}
\item \verb|varargin|, optional, is arbitrary list of
parameters to be passed onto the users time-derivative
function as specified in configPatches2.
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector\slash array of of time
derivatives, but with patch edge-values set to zero. It is
of total length $\verb|prod(nSubP)| \cdot \verb|nVars|
\cdot \verb|nEnsem| \cdot \verb|prod(nPatch)|$ and the same
dimensions as~\verb|u|.
\end{itemize}
\begin{devMan}
Reshape the fields~\verb|u| as a 6D-array, and sets the edge
values from macroscale interpolation of centre-patch values.
\cref{sec:patchEdgeInt2} describes \verb|patchEdgeInt2()|.
\begin{matlab}
%}
sizeu = size(u);
u = patchEdgeInt2(u,patches);
%{
\end{matlab}
Ask the user function for the time derivatives computed in
the array, overwrite its edge values with the dummy value of
zero (as \verb|ode15s| chokes on NaNs), then return to the
user\slash integrator as same sized array as input.
\begin{matlab}
%}
dudt = patches.fun(t,u,patches,varargin{:});
m = patches.nEdge(1);
dudt([1:m end-m+1:end],:,:) = 0;
m = patches.nEdge(2);
dudt(:,[1:m end-m+1:end],:) = 0;
dudt = reshape(dudt,sizeu);
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/patchEdgeInt1.m
| 16,444 |
utf_8
|
4d5890cdcc086ffde04fad57d210c2f8
|
% patchEdgeInt1() provides the interpolation across 1D space
% for 1D patches of simulations of a lattice system such as
% PDE discretisations. AJR & JB, Sep 2018 -- 23 Mar 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt1()}: sets patch-edge values
from interpolation over the 1D macroscale}
\label{sec:patchEdgeInt1}
Couples 1D patches across 1D space by computing their edge
values from macroscale interpolation of either the mid-patch
value \cite[]{Roberts00a, Roberts06d}, or the patch-core
average \cite[]{Bunder2013b}, or the opposite next-to-edge
values \cite[]{Bunder2020a}---this last alternative often
maintains symmetry. This function is primarily used by
\verb|patchSys1()| but is also useful for user graphics.
When using core averages (not fully implemented), assumes
the averages are sensible macroscale variables: then patch
edge values are determined by macroscale interpolation of
the core averages \citep{Bunder2013b}. \footnote{Script
\texttt{patchEdgeInt1test.m} verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global struct
\verb|patches|.
\begin{matlab}
%}
function u=patchEdgeInt1(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|nSubP| \cdot \verb|nVars|\cdot \verb|nEnsem|\cdot
\verb|nPatch|$ where there are $\verb|nVars|\cdot
\verb|nEnsem|$ field values at each of the points in the
$\verb|nSubP| \times \verb|nPatch|$ multiscale spatial grid.
\item \verb|patches| a struct largely set by
\verb|configPatches1()|, and which includes the following.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP| \times1 \times1 \times
\verb|nPatch|$ array of the spatial locations~$x_{iI}$ of
the microscale grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on the microscale
index~$i$, but may be variable spaced in macroscale
index~$I$.
\item \verb|.ordCC| is order of interpolation, integer~$\geq
-1$.
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left and right boundaries so interpolation is via divided
differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation, and zero for ordinary grid.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation---when invoking
a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation:
true, from opposite-edge next-to-edge values (often
preserves symmetry);
false, from centre-patch values (original scheme).
\item \verb|.nEdge|, for each patch, the number of edge
values set by interpolation at the edge regions of each
patch (default is one).
\item \verb|.nEnsem| the number of realisations in the
ensemble.
\item \verb|.parallel| whether serial or parallel.
\item \verb|.nCore| \todo{introduced sometime but not fully
implemented yet, because prefer ensemble}
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 4D array, $\verb|nSubP| \times
\verb|nVars| \times \verb|nEnsem| \times \verb|nPatch|$, of
the fields with edge values set by interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[nx,~,~,Nx] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round(numel(u)/numel(patches.x)/nEnsem);
assert(numel(u) == nx*nVars*nEnsem*Nx ...
,'patchEdgeInt1: input u has wrong size for parameters')
u = reshape(u,nx,nVars,nEnsem,Nx);
%{
\end{matlab}
If the user has not defined the patch core, then we assume
it to be a single point in the middle of the patch, unless
we are interpolating from next-to-edge values.
These index vectors point to patches and their two
immediate neighbours, for periodic domain.
\begin{matlab}
%}
I = 1:Nx; Ip = mod(I,Nx)+1; Im = mod(I-2,Nx)+1;
%{
\end{matlab}
\paragraph{Implement multiple width edges by folding}
Subsample~\(x\) coordinates, noting it is only differences
that count \emph{and} the microgrid~\(x\) spacing must be
uniform.
\begin{matlab}
%}
x = patches.x;
if patches.nEdge>1
nEdge = patches.nEdge;
x = x(1:nEdge:nx,:,:,:);
nx = nx/nEdge;
u = reshape(u,nEdge,nx,nVars,nEnsem,Nx);
nVars = nVars*nEdge;
u = reshape( permute(u,[2 1 3:5]) ,nx,nVars,nEnsem,Nx);
end%if patches.nEdge
%{
\end{matlab}
Calculate centre of each patch and the surrounding core
(\verb|nx| and \verb|nCore| are both odd).
\begin{matlab}
%}
i0 = round((nx+1)/2);
c = round((patches.nCore-1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches, then use finite width
stencils or spectral.
\begin{matlab}
%}
r = patches.ratio(1);
if patches.ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
\paragraph{Lagrange interpolation gives patch-edge values}
Consequently, compute centred differences of the patch
core/edge averages/values for the macro-interpolation of all
fields. Here the domain is macro-periodic.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-edge values
Ux = u([2 nx-1],:,:,I);
else % interpolate mid-patch values/sums
Ux = sum( u((i0-c):(i0+c),:,:,I) ,1);
end;
%{
\end{matlab}
Just in case any last array dimension(s) are one, we force a
padding of the sizes, then adjoin the extra dimension for
the subsequent array of differences.
\begin{matlab}
%}
szUxO=size(Ux);
szUxO=[szUxO ones(1,4-length(szUxO)) patches.ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences in these arrays. When parallel, in
order to preserve the distributed array structure we use an
index at the end for the differences.
\begin{matlab}
%}
if patches.parallel
dmu = zeros(szUxO,patches.codist); % 5D
else
dmu = zeros(szUxO); % 5D
end
%{
\end{matlab}
First compute differences, either $\mu$ and $\delta$, or
$\mu\delta$ and $\delta^2$ in space.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
dmu(:,:,:,I,1) = (Ux(:,:,:,Ip)+Ux(:,:,:,Im))/2; % \mu
dmu(:,:,:,I,2) = (Ux(:,:,:,Ip)-Ux(:,:,:,Im)); % \delta
Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
else % standard
dmu(:,:,:,I,1) = (Ux(:,:,:,Ip)-Ux(:,:,:,Im))/2; % \mu\delta
dmu(:,:,:,I,2) = (Ux(:,:,:,Ip)-2*Ux(:,:,:,I) ...
+Ux(:,:,:,Im)); % \delta^2
end%if patches.stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:patches.ordCC
dmu(:,:,:,:,k) = dmu(:,:,:,Ip,k-2) ...
-2*dmu(:,:,:,I,k-2) +dmu(:,:,:,Im,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet edge values for
each patch \cite[]{Roberts06d, Bunder2013b}, using weights
computed in \verb|configPatches1()|. Here interpolate to
specified order.
For the case where single-point values interpolate to
patch-edge values: when we have an ensemble of
configurations, different realisations are coupled to each
other as specified by \verb|patches.le| and
\verb|patches.ri|.
\begin{matlab}
%}
if patches.nCore==1
k=1+patches.EdgyInt; % use centre/core or two edges
u(nx,:,patches.ri,I) = Ux(1,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr,-4).*dmu(1,:,:,:,:) ,5);
u(1 ,:,patches.le,I) = Ux(k,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl,-4).*dmu(k,:,:,:,:) ,5);
%{
\end{matlab}
For a non-trivial core then more needs doing: the core (one
or more) of each patch interpolates to the edge action
regions. When more than one in the core, the edge is set
depending upon near edge values so the average near the edge
is correct.
\begin{matlab}
%}
else% patches.nCore>1
error('not yet considered, july--dec 2020 ??')
u(nx,:,:,I) = Ux(:,:,I)*(1-patches.stag) ...
+ reshape(-sum(u((nx-patches.nCore+1):(nx-1),:,:,I),1) ...
+ sum( patches.Cwtsr.*dmu ),Nx,nVars);
u(1,:,:,I) = Ux(:,:,I)*(1-patches.stag) ...
+ reshape(-sum(u(2:patches.nCore,:,:,I),1) ...
+ sum( patches.Cwtsl.*dmu ),Nx,nVars);
end%if patches.nCore
%{
\end{matlab}
\paragraph{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
As the macroscale fields are $N$-periodic, the macroscale
Fourier transform writes the centre-patch values as $U_j =
\sum_{k}C_ke^{ik2\pi j/N}$. Then the edge-patch values
$U_{j\pm r} =\sum_{k}C_ke^{ik2\pi/N(j\pm r)}
=\sum_{k}C'_ke^{ik2\pi j/N}$ where $C'_k =
C_ke^{ikr2\pi/N}$. For \verb|Nx|~patches we resolve
`wavenumbers' $|k|<\verb|Nx|/2$, so set row vector
$\verb|ks| = k2\pi/N$ for `wavenumbers'
$\mathcode`\,="213B k = (0,1, \ldots, k_{\max}, -k_{\max},
\ldots, -1)$ for odd~$N$, and $\mathcode`\,="213B k =
(0,1, \ldots, k_{\max}, (k_{\max}+1), -k_{\max}, \ldots,
-1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches1()|
tests that there are an even number of patches). Then the
patch-ratio is effectively halved. The patch edges are near
the middle of the gaps and swapped. \todo{Have not yet
tested whether works for Edgy Interpolation.} \todo{Have
not yet implemented multiple edge values for a staggered
grid as I am uncertain whether it makes any sense. }
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
v = nan(size(u)); % currently to restore the shape of u
u = [u(:,:,:,1:2:Nx) u(:,:,:,2:2:Nx)];
stagShift = 0.5*[ones(1,nVars) -ones(1,nVars)];
iV = [nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r = r/2; % ratio effectively halved
Nx = Nx/2; % halve the number of patches
nVars = nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Now set wavenumbers (when \verb|Nx| is even then highest
wavenumber is~$\pi$).
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
ks = shiftdim( ...
2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ...
,-2);
%{
\end{matlab}
Compute the Fourier transform across patches of the patch
centre or next-to-edge values for all the fields. If there
are an even number of points, then if complex, treat as
positive wavenumber, but if real, treat as cosine. When
using an ensemble of configurations, different
configurations might be coupled to each other, as specified
by \verb|patches.le| and \verb|patches.ri|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cleft = fft(u(i0 ,:,:,:),[],4);
Cright = Cleft;
else
Cleft = fft(u(2 ,:,:,:),[],4);
Cright= fft(u(nx-1,:,:,:),[],4);
end
%{
\end{matlab}
The inverse Fourier transform gives the edge values via a
shift a fraction~$r$ to the next macroscale grid point.
\begin{matlab}
%}
u(nx,iV,patches.ri,:) = uclean( ifft( ...
Cleft.*exp(1i*ks.*(stagShift+r)) ,[],4));
u(1 ,iV,patches.le,:) = uclean( ifft( ...
Cright.*exp(1i*ks.*(stagShift-r)) ,[],4));
%{
\end{matlab}
Restore staggered grid when appropriate. This dimensional
shifting appears to work.
Is there a better way to do this?
\begin{matlab}
%}
if patches.stag
nVars = nVars/2;
u=reshape(u,nx,nVars,2,nEnsem,Nx);
Nx = 2*Nx;
v(:,:,:,1:2:Nx) = u(:,:,1,:,:);
v(:,:,:,2:2:Nx) = u(:,:,2,:,:);
u = v;
end%if patches.stag
end%if patches.ordCC
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|p|, and hence
size of the (forward) divided difference table in~\verb|F|.
\begin{matlab}
%}
if patches.ordCC<1, patches.ordCC = Nx-1; end
p = min(patches.ordCC,Nx-1);
F = nan(patches.EdgyInt+1,nVars,nEnsem,Nx,p+1);
%{
\end{matlab}
Set function values in first `column' of the table for every
variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-edge values are because their
values are to interpolate to the opposite edge of each
patch.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-edge values
F(:,:,:,:,1) = u([nx-1 2],:,:,I);
X(:,:,:,:) = x([nx-1 2],:,:,I);
else % interpolate mid-patch values/sums
F(:,:,:,:,1) = sum( u((i0-c):(i0+c),:,:,I) ,1);
X(:,:,:,:) = x(i0,:,:,I);
end;
%{
\end{matlab}
Compute table of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable and
across ensemble.
\begin{matlab}
%}
for q = 1:p
i = 1:Nx-q;
F(:,:,:,i,q+1) = (F(:,:,:,i+1,q)-F(:,:,:,i,q)) ...
./(X(:,:,:,i+q) -X(:,:,:,i));
end
%{
\end{matlab}
Now interpolate to the edge-values at locations~\verb|Xedge|.
\begin{matlab}
%}
Xedge = x([1 nx],:,:,:);
%{
\end{matlab}
Code Horner's evaluation of the interpolation polynomials.
Indices~\verb|i| are those of the left end of each
interpolation stencil because the table is of forward
differences.\footnote{For EdgyInt, perhaps interpret odd
order interpolation in such a way that first-order
interpolations reduces to appropriate linear interpolation
so that as patches abut the scheme is `full-domain'. May
mean left-edge and right-edge have different indices.
Explore sometime??} First alternative: the case of
order~\(p\) interpolation across the domain, asymmetric near
the boundary. Use this first alternative for now.
\begin{matlab}
%}
if true
i = max(1,min(1:Nx,Nx-ceil(p/2))-floor(p/2));
Uedge = F(:,:,:,i,p+1);
for q = p:-1:1
Uedge = F(:,:,:,i,q)+(Xedge-X(:,:,:,i+q-1)).*Uedge;
end
%{
\end{matlab}
Second alternative: lower the degree of interpolation near
the boundary to maintain the band-width of the
interpolation. Such symmetry might be essential for multi-D.
\footnote{The aim is to preserve symmetry?? Does it?? As of
Jan 2023 it only partially does---fails near boundaries, and
maybe fails with uneven spacing.}
\begin{matlab}
%}
else%if false
i = max(1,I-floor(p/2));
%{
\end{matlab}
For the tapering order of interpolation, form the interior
mask~\verb|Q| (logical) that signifies which interpolations
are to be done at order~\verb|q|. This logical mask spreads
by two as each order~\verb|q| decreases.
\begin{matlab}
%}
Q = (I-1>=floor(p/2)) & (Nx-I>=p/2);
Imid = floor(Nx/2);
%{
\end{matlab}
Initialise to highest divide difference, surrounded by zeros.
\begin{matlab}
%}
Uedge = zeros(patches.EdgyInt+1,nVars,nEnsem,Nx);
Uedge(:,:,:,Q) = F(:,:,:,i(Q),p+1);
%{
\end{matlab}
Complete Horner evaluation of the relevant polynomials.
\begin{matlab}
%}
for q = p:-1:1
Q = [Q(2:Imid) true(1,2) Q(Imid+1:end-1)]; % spread mask
Uedge(:,:,:,Q) = F(:,:,:,i(Q),q) ...
+(Xedge(:,:,:,Q)-X(:,:,:,i(Q)+q-1)).*Uedge(:,:,:,Q);
end%for q
end%if
%{
\end{matlab}
Finally, insert edge values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,:,patches.le,I) = Uedge(1,:,:,I);
u(nx,:,patches.ri,I) = Uedge(2,:,:,I);
%{
\end{matlab}
We want a user to set the extreme patch edge values
according to the microscale boundary conditions that hold at
the extremes of the domain. Consequently, unless testing,
override their computed interpolation values
with~\verb|NaN|.
\begin{matlab}
%}
if isfield(patches,'intTest')&&patches.intTest
else % usual case
u( 1,:,:, 1) = nan;
u(nx,:,:,Nx) = nan;
end%if
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic
%{
\end{matlab}
\paragraph{Unfold multiple edges} No need to restore~\(x\).
\begin{matlab}
%}
if patches.nEdge>1
nVars = nVars/nEdge;
u = reshape( u ,nx,nEdge,nVars,nEnsem,Nx);
nx = nx*nEdge;
u = reshape( permute(u,[2 1 3:5]) ,nx,nVars,nEnsem,Nx);
end%if patches.nEdge
%{
\end{matlab}
Fin, returning the 4D array of field values.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchSys3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/patchSys3.m
| 4,266 |
utf_8
|
5fe96a5fc1710aa27ba6225006093653
|
% patchSys3() provides an interface to time integrators
% for the dynamics on patches in 3D coupled across space.
% The system must be a lattice system such as PDE
% discretisations. AJR, Aug 2020 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchSys3()}: interface 3D space to time integrators}
\label{sec:patchSys3}
To simulate in time with 3D spatial patches we often need to
interface a users time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function provides an interface. Communicate
patch-design variables (\cref{sec:configPatches3}) either
via the global struct~\verb|patches| or via an optional
third argument. \verb|patches| is required for the parallel
computing of \verb|spmd|, or if parameters are to be passed
though to the user microscale function.
\begin{matlab}
%}
function dudt = patchSys3(t,u,patches,varargin)
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP(1)| \times \verb|nSubP(2)| \times
\verb|nSubP(3)| \times \verb|nPatch(1)| \times
\verb|nPatch(2)| \times \verb|nPatch(3)|$ spatial grid.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches3()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches,...)| that computes the time
derivatives on the patchy lattice. The array~\verb|u| has
size $\verb|nSubP(1)| \times \verb|nSubP(2)| \times
\verb|nSubP(3)| \times \verb|nVars| \times \verb|nEsem|
\times \verb|nPatch(1)| \times \verb|nPatch(2)| \times
\verb|nPatch(3)|$. Time derivatives must be computed into
the same sized array, although herein the patch edge-values
are overwritten by zeros.
\item \verb|.x| is $\verb|nSubP(1)| \times1 \times1 \times1
\times1 \verb|nPatch(1)| \times1 \times1$ array of the
spatial locations~$x_{i}$ of the microscale
$(i,j,k)$-grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on both macro- and
microscales.
\item \verb|.y| is similarly $1 \times \verb|nSubP(2)|
\times1 \times1 \times1 \times1 \times \verb|nPatch(2)|
\times1$ array of the spatial locations~$y_{j}$ of the
microscale $(i,j,k)$-grid points in every patch.
Currently it \emph{must} be an equi-spaced lattice on both
macro- and microscales.
\item \verb|.z| is similarly $1 \times1 \times
\verb|nSubP(3)| \times1 \times1 \times1 \times1 \times
\verb|nPatch(3)|$ array of the spatial locations~$z_{k}$
of the microscale $(i,j,k)$-grid points in every patch.
Currently it \emph{must} be an equi-spaced lattice on both
macro- and microscales.
\end{itemize}
\item \verb|varargin|, optional, is arbitrary list of
parameters to be passed onto the users time-derivative
function as specified in configPatches3.
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector\slash array of of time
derivatives, but with patch edge-values set to zero. It is
of total length $\verb|prod(nSubP)| \cdot \verb|nVars|
\cdot \verb|nEnsem| \cdot \verb|prod(nPatch)|$ and the same
dimensions as~\verb|u|.
\end{itemize}
\begin{devMan}
Sets the edge-face values from macroscale interpolation of
centre-patch values, and if necessary, reshapes the
fields~\verb|u| as a 8D-array. \cref{sec:patchEdgeInt3}
describes \verb|patchEdgeInt3()|.
\begin{matlab}
%}
sizeu = size(u);
u = patchEdgeInt3(u,patches);
%{
\end{matlab}
Ask the user function for the time derivatives computed in
the array, overwrite its edge\slash face values with the
dummy value of zero (as \verb|ode15s| chokes on NaNs), then
return to the user\slash integrator as same sized array as
input.
\begin{matlab}
%}
dudt = patches.fun(t,u,patches,varargin{:});
m = patches.nEdge(1);
dudt([1:m end-m+1:end],:,:,:) = 0;
m = patches.nEdge(2);
dudt(:,[1:m end-m+1:end],:,:) = 0;
m = patches.nEdge(3);
dudt(:,:,[1:m end-m+1:end],:) = 0;
dudt = reshape(dudt,sizeu);
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
heteroDispersiveWave3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/heteroDispersiveWave3.m
| 6,842 |
utf_8
|
2c0f537ee293e1547eb9cea5e368629a
|
% Simulate in 3D on patches the heterogeneous dispersive
% waves in a fourth-order wave PDE. AJR, 16 Apr 2023
%!TEX root = doc.tex
%{
\section{\texttt{heteroDispersiveWave3}: heterogeneous
Dispersive Waves from 4th order PDE}
\label{sec:heteroDispersiveWave3}
This uses small spatial patches to simulate heterogeneous
dispersive waves in 3D. The wave equation
for~\(u(x,y,z,t)\) is the fourth-order in space \pde
\begin{equation*}
u_{tt}=-\delsq(C\delsq u)
\end{equation*}
for microscale variations in scalar~\(C(x,y,z)\).
Initialise some Matlab aspects.
\begin{matlab}
%}
clear all
cMap=jet(64); cMap=0.8*cMap(7:end-7,:); % set colormap
basename = [num2str(floor(1e5*rem(now,1))) mfilename]
%global OurCf2eps, OurCf2eps=true %optional to save plots
%{
\end{matlab}
Set random heterogeneous coefficients of period two in each
of the three directions. Crudely normalise by the harmonic
mean so the macro-wave time scale is roughly one.
\begin{matlab}
%}
mPeriod = [2 2 2];
cHetr = exp(0.9*randn(mPeriod));
cHetr = cHetr*mean(1./cHetr(:))
%{
\end{matlab}
Establish global patch data struct to interface with a
function coding a fourth-order heterogeneous wave \pde: to
be solved on $[-\pi,\pi]^3$-periodic domain, with
$5^3$~patches, spectral interpolation~($0$) couples the
patches, each patch with micro-grid spacing~$0.22$
(relatively large for visualisation), and with $6^3$~points
forming each patch. (Six because two edge layers on each of
two faces, and two interior points for the \pde.)
\begin{matlab}
%}
global patches
patches = configPatches3(@heteroDispWave3,[-pi pi] ...
,'periodic', 5, 0, 0.22, mPeriod+4 ,'EdgyInt',true ...
,'hetCoeffs',cHetr ,'nEdge',2);
%{
\end{matlab}
Set a wave initial state using auto-replication of the
spatial grid, and as \cref{fig:heteroDispersiveWave3ic}
shows. This wave propagates diagonally across space.
Concatenate the two \(u,v\)-fields to be the two components
of the fourth
dimension.
\begin{matlab}
%}
u0 = 0.5+0.5*sin(patches.x+patches.y+patches.z);
v0 = -0.5*cos(patches.x+patches.y+patches.z)*3;
uv0 = cat(4,u0,v0);
%{
\end{matlab}
\begin{figure}\centering
\caption{\label{fig:heteroDispersiveWave3ic} initial
field~$u(x,y,z,t)$ at time $t=0$ of the patch scheme applied
to a heterogeneous dispersive wave~\pde:
\cref{fig:heteroDispersiveWave3fin} plots the computed field
at time $t=6$.}
\includegraphics[scale=0.9]{24168heteroDispersiveWave3ic}
\end{figure}
Integrate in time to $t=6$ using standard functions. In
Matlab \verb|ode15s| would be natural as the patch scheme is
naturally stiff, but \verb|ode23| is much quicker
\cite[Fig.~4]{Maclean2020a}.
\begin{matlab}
%}
disp('Simulate heterogeneous wave u_tt=delsq[C*delsq(u)]')
tic
[ts,us] = ode23(@patchSys3,linspace(0,6),uv0(:));
simulateTime=toc
%{
\end{matlab}
Animate the computed simulation to end with
\cref{fig:heteroDispersiveWave3fin}. Use
\verb|patchEdgeInt3| to obtain patch-face values in order to
most easily reconstruct the array data structure.
Replicate $x$, $y$, and~$z$ arrays to get individual
spatial coordinates of every data point. Then, optionally,
set faces to~\verb|nan| so the plot just shows
patch-interior data.
\begin{matlab}
%}
%%
figure(1), clf, colormap(cMap)
xs = patches.x+0*patches.y+0*patches.z;
ys = patches.y+0*patches.x+0*patches.z;
zs = patches.z+0*patches.y+0*patches.x;
if 1, xs([1:2 end-1:end],:,:,:)=nan;
xs(:,[1:2 end-1:end],:,:)=nan;
xs(:,:,[1:2 end-1:end],:)=nan;
end;%option
j=find(~isnan(xs));
%{
\end{matlab}
In the scatter plot, \verb|col()| maps the $u$-data values
to the colour of the dots.
\begin{matlab}
%}
col = @(u) sign(u).*abs(u);
%{
\end{matlab}
Loop to plot at each and every time step.
\begin{matlab}
%}
for i = 1:length(ts)
uv = patchEdgeInt3(us(i,:));
u = uv(:,:,:,1,:);
for p=1:2
subplot(1,2,p)
if (i==1)
scat(p) = scatter3(xs(j),ys(j),zs(j),'.');
axis equal, caxis(col([0 1])), view(45-4*p,42)
xlabel('x'), ylabel('y'), zlabel('z')
end
title(['view cross-eyed: time = ' num2str(ts(i),'%4.2f')])
set( scat(p),'CData',col(u(j)) );
end
%{
\end{matlab}
Optionally save the initial condition to graphic file for
\cref{fig:heteroDispersiveWave3ic}, and optionally save the
last plot.
\begin{matlab}
%}
if i==1,
ifOurCf2eps([basename 'ic'])
disp('Type space character to animate simulation')
pause
else pause(0.1)
end
end% i-loop over all times
ifOurCf2eps([basename 'fin'])
%{
\end{matlab}
\begin{figure}\centering
\caption{\label{fig:heteroDispersiveWave3fin}
field~$u(x,y,z,t)$ at time $t=6$ of the patch scheme applied
to the heterogeneous dispersive wave~\pde\ with initial
condition in \cref{fig:heteroDispersiveWave3ic}.}
\includegraphics[scale=0.9]{24168heteroDispersiveWave3fin}
\end{figure}
\subsection{\texttt{heteroDispWave3()}: PDE function of
4th-order heterogeneous dispersive waves}
\label{sec:heteroDispWave3}
This function codes the lattice heterogeneous waves inside
the patches. The wave \pde\ for \(u(x,y,z,t)\) and
`velocity'~\(v(x,y,z,t)\) is
\begin{equation*}
u_t=v,\quad v_t=-\delsq(C\delsq u)
\end{equation*}
for microscale variations in scalar~\(C(x,y,z)\). For 8D
input arrays~\verb|u|, \verb|x|, \verb|y|, and~\verb|z| (via
edge-value interpolation of \verb|patchSys3|,
\cref{sec:patchSys3}), computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|. The
3D array of heterogeneous coefficients,~$C_{ijk}$,
$c^y_{ijk}$ and~$c^z_{ijk}$, have been stored
in~\verb|patches.cs| (3D).
Supply patch information as a third argument (required by
parallel computation), or otherwise by a global variable.
\begin{matlab}
%}
function ut = heteroDispWave3(t,u,patches)
if nargin<3, global patches, end
%{
\end{matlab}
Micro-grid space steps.
\begin{matlab}
%}
dx = diff(patches.x(2:3));
dy = diff(patches.y(2:3));
dz = diff(patches.z(2:3));
%{
\end{matlab}
First, compute \(C\delsq u\) into say~\verb|u|, using
indices for all but extreme micro-grid points. We use a
single colon to represent the last four array dimensions
because the result arrays are already dimensioned.
\begin{matlab}
%}
I = 2:size(u,1)-1; J = 2:size(u,2)-1; K = 2:size(u,3)-1;
u(I,J,K,1,:) = patches.cs(I,J,K,1,:).*( diff(u(:,J,K,1,:),2,1)/dx^2 ...
+diff(u(I,:,K,1,:),2,2)/dy^2 +diff(u(I,J,:,1,:),2,3)/dz^2 );
%{
\end{matlab}
Reserve storage, set lowercase indices to non-edge interior,
and then assign interior patch values to the heterogeneous
diffusion time derivatives.
\begin{matlab}
%}
ut = nan+u; % preallocate output array
i = I(2:end-1); j = J(2:end-1); k = K(2:end-1);
ut(i,j,k,1,:) = u(i,j,k,2,:); % du/dt=v
% dv/dt=delta^2 of above C*delta^2
ut(i,j,k,2,:) = -( diff(u(I,j,k,1,:),2,1)/dx^2 ...
+diff(u(i,J,k,1,:),2,2)/dy^2 +diff(u(i,j,K,1,:),2,3)/dz^2 );
end% function
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
configPatches3.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/configPatches3.m
| 33,983 |
utf_8
|
b4291a4d1d004f1936b796a38893502e
|
% configPatches3() creates a data struct of the design of 3D
% patches for later use by the patch functions such as
% patchSys3(). AJR, Aug 2020 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{configPatches3()}: configures spatial
patches in 3D}
\label{sec:configPatches3}
\localtableofcontents
Makes the struct~\verb|patches| for use by the patch\slash
gap-tooth time derivative\slash step function
\verb|patchSys3()|, and possibly other patch functions.
\cref{sec:configPatches3eg,sec:homoDiffEdgy3} list examples
of its use.
\begin{matlab}
%}
function patches = configPatches3(fun,Xlim,Dom ...
,nPatch,ordCC,dx,nSubP,varargin)
version = '2023-04-12';
%{
\end{matlab}
\paragraph{Input}
If invoked with no input arguments, then executes an example
of simulating a heterogeneous wave \pde---see
\cref{sec:configPatches3eg} for an example code.
\begin{itemize}
\item \verb|fun| is the name of the user function,
\verb|fun(t,u,patches)| or \verb|fun(t,u)| or
\verb|fun(t,u,patches,...)|, that computes time-derivatives
(or time-steps) of quantities on the 3D micro-grid within
all the 3D~patches.
\item \verb|Xlim| array/vector giving the rectangular-cuboid
macro-space domain of the computation: namely
$[\verb|Xlim(1)|, \verb|Xlim(2)|] \times [\verb|Xlim(3)|,
\verb|Xlim(4)| \times [\verb|Xlim(5)|, \verb|Xlim(6)|]$. If
\verb|Xlim| has two elements, then the domain is the cubic
domain of the same interval in all three directions.
\item \verb|Dom| sets the type of macroscale conditions for
the patches, and reflects the type of microscale boundary
conditions of the problem. If \verb|Dom| is \verb|NaN| or
\verb|[]|, then the field~\verb|u| is triply macro-periodic
in the 3D spatial domain, and resolved on equi-spaced
patches. If \verb|Dom| is a character string, then that
specifies the \verb|.type| of the following structure, with
\verb|.bcOffset| set to the default zero. Otherwise
\verb|Dom| is a structure with the following components.
\begin{itemize}
\item \verb|.type|, string, of either \verb|'periodic'| (the
default), \verb|'equispace'|, \verb|'chebyshev'|,
\verb|'usergiven'|. For all cases except \verb|'periodic'|,
users \emph{must} code into \verb|fun| the micro-grid
boundary conditions that apply at the left\slash right\slash
bottom\slash top\slash back\slash front faces of the
leftmost\slash rightmost\slash bottommost\slash
topmost\slash backmost\slash frontmost patches,
respectively.
\item \verb|.bcOffset|, optional one, three or six element
vector/array, in the cases of \verb|'equispace'| or
\verb|'chebyshev'| the patches are placed so the left\slash
right macroscale boundaries are aligned to the left\slash
right faces of the corresponding extreme patches, but offset
by \verb|bcOffset| of the sub-patch micro-grid spacing. For
example, use \verb|bcOffset=0| when the micro-code applies
Dirichlet boundary values on the extreme face micro-grid
points, whereas use \verb|bcOffset=0.5| when the microcode
applies Neumann boundary conditions halfway between the
extreme face micro-grid points. Similarly for the top,
bottom, back, and front faces.
If \verb|.bcOffset| is a scalar, then apply the same offset
to all boundaries. If three elements, then apply the first
offset to both \(x\)-boundaries, the second offset to both
\(y\)-boundaries, and the third offset to both
\(z\)-boundaries. If six elements, then apply the first two
offsets to the respective \(x\)-boundaries, the middle two
offsets to the respective \(y\)-boundaries, and the last two
offsets to the respective \(z\)-boundaries.
\item \verb|.X|, optional vector/array with \verb|nPatch(1)|
elements, in the case \verb|'usergiven'| it specifies the
\(x\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\item \verb|.Y|, optional vector/array with \verb|nPatch(2)|
elements, in the case \verb|'usergiven'| it specifies the
\(y\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\item \verb|.Z|, optional vector/array with \verb|nPatch(3)|
elements, in the case \verb|'usergiven'| it specifies the
\(z\)-locations of the centres of the patches---the user is
responsible the locations makes sense.
\end{itemize}
\item \verb|nPatch| sets the number of equi-spaced spatial
patches: if scalar, then use the same number of patches in
all three directions, otherwise \verb|nPatch(1:3)| gives the
number~($\geq1$) of patches in each direction.
\item \verb|ordCC| is the `order' of interpolation for
inter-patch coupling across empty space of the macroscale
patch values to the face-values of the patches: currently
must be~$0,2,4,\ldots$; where $0$~gives spectral
interpolation.
\item \verb|dx| (real---scalar or three elements) is usually
the sub-patch micro-grid spacing in~\(x\), \(y\) and~\(z\).
If scalar, then use the same \verb|dx| in all three
directions, otherwise \verb|dx(1:3)| gives the spacing in
each of the three directions.
However, if \verb|Dom| is~\verb|NaN| (as for pre-2023), then
\verb|dx| actually is \verb|ratio| (scalar or three elements),
namely the ratio of (depending upon \verb|EdgyInt|) either
the half-width or full-width of a patch to the equi-spacing
of the patch mid-points---adjusted a little when $\verb|nEdge|>1$. So
either $\verb|ratio|=\tfrac12$ means the patches abut and
$\verb|ratio|=1$ is overlapping patches as in holistic
discretisation, or $\verb|ratio|=1$ means the patches abut.
Small~\verb|ratio| should greatly reduce computational time.
\item \verb|nSubP| is the number of equi-spaced microscale
lattice points in each patch: if scalar, then use the same
number in all three directions, otherwise \verb|nSubP(1:3)|
gives the number in each direction. If not using
\verb|EdgyInt|, then $\verb|nSubP./nEdge|$ must be odd integer(s) so that there
is/are centre-patch lattice planes. So for the defaults
of $\verb|nEdge|=1$ and not \verb|EdgyInt|, then
\verb|nSubP| must be odd.
\item \verb|'nEdge'|, \emph{optional} (integer---scalar or three element), default=1, the width of face values set by interpolation at the
face regions of each patch. If two elements, then respectively the width in \(x,y\)-directions. The default is one (suitable
for microscale lattices with only nearest neighbour
interactions).
\item \verb|'EdgyInt'|, true/false, \emph{optional},
default=false. If true, then interpolate to left\slash
right\slash top\slash bottom\slash front\slash back
face-values from right\slash left\slash bottom\slash
top\slash back\slash front next-to-face values. If false or
omitted, then interpolate from centre-patch planes.
\item \verb|'nEnsem'|, \emph{optional-experimental},
default one, but if more, then an ensemble over this number
of realisations.
\item \verb|'hetCoeffs'|, \emph{optional}, default empty.
Supply a 3D or 4D array of microscale heterogeneous
coefficients to be used by the given microscale \verb|fun|
in each patch. Say the given array~\verb|cs| is of size
$m_x\times m_y\times m_z\times n_c$, where $n_c$~is the
number of different arrays of coefficients. For example, in
heterogeneous diffusion, $n_c=3$ for the diffusivities in
the \emph{three} different spatial directions (or $n_c=6$
for the diffusivity tensor). The coefficients are to be the
same for each and every patch. However, macroscale
variations are catered for by the $n_c$~coefficients being
$n_c$~parameters in some macroscale formula.
\begin{itemize}
\item If $\verb|nEnsem|=1$, then the array of coefficients
is just tiled across the patch size to fill up each patch,
starting from the $(1,1,1)$-point in each patch. Best accuracy
usually obtained when the periodicity of the coefficients
is a factor of \verb|nSubP-2*nEdge| for \verb|EdgyInt|, or
a factor of \verb|(nSubP-nEdge)/2| for not \verb|EdgyInt|.
\item If $\verb|nEnsem|>1$ (value immaterial), then reset
$\verb|nEnsem|:=m_x\cdot m_y\cdot m_z$ and construct an
ensemble of all $m_x\cdot m_y\cdot m_z$ phase-shifts of
the coefficients. In this scenario, the inter-patch
coupling couples different members in the ensemble. When
\verb|EdgyInt| is true, and when the coefficients are
diffusivities\slash elasticities in $x,y,z$-directions,
respectively, then this coupling cunningly preserves
symmetry.
\end{itemize}
\item \verb|'parallel'|, true/false, \emph{optional},
default=false. If false, then all patch computations are on
the user's main \textsc{cpu}---although a user may well
separately invoke, say, a \textsc{gpu} to accelerate
sub-patch computations.
If true, and it requires that you have \Matlab's Parallel
Computing Toolbox, then it will distribute the patches over
multiple \textsc{cpu}s\slash cores. In \Matlab, only one
array dimension can be split in the distribution, so it
chooses the one space dimension~$x,y,z$ corresponding to
the highest~\verb|nPatch| (if a tie, then chooses the
rightmost of~$x,y,z$). A user may correspondingly
distribute arrays with property \verb|patches.codist|, or
simply use formulas invoking the preset distributed arrays
\verb|patches.x|, \verb|patches.y|, and \verb|patches.z|. If
a user has not yet established a parallel pool, then a
`local' pool is started.
\end{itemize}
\paragraph{Output} The struct \verb|patches| is created and
set with the following components. If no output variable is
provided for \verb|patches|, then make the struct available
as a global variable.\footnote{When using \texttt{spmd}
parallel computing, it is generally best to avoid global
variables, and so instead prefer using an explicit output
variable.}
\begin{matlab}
%}
if nargout==0, global patches, end
patches.version = version;
%{
\end{matlab}
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches)| or \verb|fun(t,u)| or
\verb|fun(t,u,patches,...)| that computes the time
derivatives (or steps) on the patchy lattice.
\item \verb|.ordCC| is the specified order of inter-patch
coupling.
\item \verb|.periodic|: either true, for interpolation on
the macro-periodic domain; or false, for general
interpolation by divided differences over non-periodic
domain or unevenly distributed patches.
\item \verb|.stag| is true for interpolation using only odd
neighbouring patches as for staggered grids, and false for
the usual case of all neighbour coupling---not yet
implemented.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the
$\verb|ordCC|\times 3$-array of weights for the inter-patch
interpolation onto the right\slash top\slash front and
left\slash bottom\slash back faces (respectively) with
patch:macroscale ratio as specified or as derived
from~\verb|dx|.
\item \verb|.x| (8D) is $\verb|nSubP(1)| \times1 \times1
\times1 \times1 \times \verb|nPatch(1)| \times1 \times1$
array of the regular spatial locations~$x_{iI}$ of the
microscale grid points in every patch.
\item \verb|.y| (8D) is $1 \times \verb|nSubP(2)| \times1
\times1 \times1 \times1 \times \verb|nPatch(2)| \times1$
array of the regular spatial locations~$y_{jJ}$ of the
microscale grid points in every patch.
\item \verb|.z| (8D) is $1 \times1 \times \verb|nSubP(3)|
\times1 \times1 \times1 \times1 \times \verb|nPatch(3)|$
array of the regular spatial locations~$z_{kK}$ of the
microscale grid points in every patch.
\item \verb|.ratio| $1\times 3$, only for macro-periodic
conditions, are the size ratios of every patch.
\item \verb|.nEdge| $1\times 3$, is the width of face
values set by interpolation at the face regions of each
patch, in the \(x,y,z\)-directions respectively.
\item \verb|.le|, \verb|.ri|, \verb|.bo|, \verb|.to|,
\verb|.ba|, \verb|.fr| determine inter-patch coupling of
members in an ensemble. Each a column vector of
length~\verb|nEnsem|.
\item \verb|.cs| either
\begin{itemize}
\item \verb|[]| 0D, or
\item if $\verb|nEnsem|=1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times (\verb|nSubP(3)|-1)\times n_c$ 4D
array of microscale heterogeneous coefficients, or
\item if $\verb|nEnsem|>1$, $(\verb|nSubP(1)|-1)\times
(\verb|nSubP(2)|-1)\times (\verb|nSubP(3)|-1)\times
n_c\times m_xm_ym_z$ 5D array of $m_xm_ym_z$~ensemble of
phase-shifts of the microscale heterogeneous coefficients.
\end{itemize}
\item \verb|.parallel|, logical: true if patches are
distributed over multiple \textsc{cpu}s\slash cores for the
Parallel Computing Toolbox, otherwise false (the default is
to activate the \emph{local} pool).
\item \verb|.codist|, \emph{optional}, describes the
particular parallel distribution of arrays over the active
parallel pool.
\end{itemize}
\subsection{If no arguments, then execute an example}
\label{sec:configPatches3eg}
\begin{matlab}
%}
if nargin==0
disp('With no arguments, simulate example of heterogeneous wave')
%{
\end{matlab}
The code here shows one way to get started: a user's script
may have the following three steps (``\into'' denotes function
recursion).
\begin{enumerate}\def\itemsep{-1.5ex}
\item configPatches3
\item ode23 integrator \into patchSys3 \into user's PDE
\item process results
\end{enumerate}
Set random heterogeneous
coefficients of period two in each of the three
directions. Crudely normalise by the harmonic mean so the
macro-wave time scale is roughly one.
\begin{matlab}
%}
mPeriod = [2 2 2];
cHetr = exp(0.9*randn([mPeriod 3]));
cHetr = cHetr*mean(1./cHetr(:))
%{
\end{matlab}
Establish global patch data struct to interface with a
function coding a nonlinear `diffusion' \pde: to be solved
on $[-\pi,\pi]^3$-periodic domain, with $5^3$~patches,
spectral interpolation~($0$) couples the patches, each patch
with micro-grid spacing~$0.22$ (relatively large for
visualisation), and with $4^3$~points forming each patch.
\begin{matlab}
%}
global patches
patches = configPatches3(@heteroWave3,[-pi pi] ...
,'periodic' , 5, 0, 0.22, mPeriod+2 ,'EdgyInt',true ...
,'hetCoeffs',cHetr);
%{
\end{matlab}
Set a wave initial state using auto-replication of the
spatial grid, and as \cref{fig:configPatches3ic} shows. This
wave propagates diagonally across space. Concatenate the two
\(u,v\)-fields to be the two components of the fourth
dimension.
\begin{matlab}
%}
u0 = 0.5+0.5*sin(patches.x+patches.y+patches.z);
v0 = -0.5*cos(patches.x+patches.y+patches.z)*sqrt(3);
uv0 = cat(4,u0,v0);
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:configPatches3ic}initial
field~$u(x,y,z,t)$ at time $t=0$ of the patch scheme
applied to a heterogeneous wave~\pde:
\cref{fig:configPatches3fin} plots the computed field at
time $t=6$.}
\includegraphics[scale=0.9]{configPatches3ic}
\end{figure}
Integrate in time to $t=6$ using standard functions. In
Matlab \verb|ode15s| would be natural as the patch scheme is
naturally stiff, but \verb|ode23| is much quicker
\cite[Fig.~4]{Maclean2020a}.
\begin{matlab}
%}
disp('Simulate heterogeneous wave u_tt=div[C*grad(u)]')
if ~exist('OCTAVE_VERSION','builtin')
[ts,us] = ode23(@patchSys3,linspace(0,6),uv0(:));
else %disp('octave version is very slow for me')
lsode_options('absolute tolerance',1e-4);
lsode_options('relative tolerance',1e-4);
[ts,us] = odeOcts(@patchSys3,[0 1 2],uv0(:));
end
%{
\end{matlab}
Animate the computed simulation to end with
\cref{fig:configPatches3fin}. Use \verb|patchEdgeInt3| to
obtain patch-face values in order to most easily reconstruct
the array data structure.
Replicate $x$, $y$, and~$z$ arrays to get individual
spatial coordinates of every data point. Then, optionally,
set faces to~\verb|nan| so the plot just shows
patch-interior data.
\begin{matlab}
%}
figure(1), clf, colormap(0.8*jet)
xs = patches.x+0*patches.y+0*patches.z;
ys = patches.y+0*patches.x+0*patches.z;
zs = patches.z+0*patches.y+0*patches.x;
if 1, xs([1 end],:,:,:)=nan;
xs(:,[1 end],:,:)=nan;
xs(:,:,[1 end],:)=nan;
end;%option
j=find(~isnan(xs));
%{
\end{matlab}
In the scatter plot, these functions \verb|pix()| and
\verb|col()| map the $u$-data values to the size of the
dots and to the colour of the dots, respectively.
\begin{matlab}
%}
pix = @(u) 15*abs(u)+7;
col = @(u) sign(u).*abs(u);
%{
\end{matlab}
Loop to plot at each and every time step.
\begin{matlab}
%}
for i = 1:length(ts)
uv = patchEdgeInt3(us(i,:));
u = uv(:,:,:,1,:);
for p=1:2
subplot(1,2,p)
if (i==1)| exist('OCTAVE_VERSION','builtin')
scat(p) = scatter3(xs(j),ys(j),zs(j),'filled');
axis equal, caxis(col([0 1])), view(45-5*p,25)
xlabel('x'), ylabel('y'), zlabel('z')
title('view stereo pair cross-eyed')
end % in matlab just update values
set(scat(p),'CData',col(u(j)) ...
,'SizeData',pix((8+xs(j)-ys(j)+zs(j))/6+0*u(j)));
legend(['time = ' num2str(ts(i),'%4.2f')],'Location','north')
end
%{
\end{matlab}
Optionally save the initial condition to graphic file for
\cref{fig:configPatches2ic}, and optionally save the last
plot.
\begin{matlab}
%}
if i==1,
ifOurCf2eps([mfilename 'ic'])
disp('Type space character to animate simulation')
pause
else pause(0.05)
end
end% i-loop over all times
ifOurCf2eps([mfilename 'fin'])
%{
\end{matlab}
\begin{figure}
\centering
\caption{\label{fig:configPatches3fin}field~$u(x,y,z,t)$
at time $t=6$ of the patch scheme applied to the
heterogeneous wave~\pde\ with initial condition in
\cref{fig:configPatches3ic}.}
\includegraphics[scale=0.9]{configPatches3fin}
\end{figure}
Upon finishing execution of the example, exit this function.
\begin{matlab}
%}
return
end%if no arguments
%{
\end{matlab}
\IfFileExists{../Patch/heteroWave3.m}{\input{../Patch/heteroWave3.m}}{}
\begin{devMan}
\subsection{Parse input arguments and defaults}
\begin{matlab}
%}
p = inputParser;
fnValidation = @(f) isa(f, 'function_handle'); %test for fn name
addRequired(p,'fun',fnValidation);
addRequired(p,'Xlim',@isnumeric);
%addRequired(p,'Dom'); % too flexible
addRequired(p,'nPatch',@isnumeric);
addRequired(p,'ordCC',@isnumeric);
addRequired(p,'dx',@isnumeric);
addRequired(p,'nSubP',@isnumeric);
addParameter(p,'nEdge',1,@isnumeric);
addParameter(p,'EdgyInt',false,@islogical);
addParameter(p,'nEnsem',1,@isnumeric);
addParameter(p,'hetCoeffs',[],@isnumeric);
addParameter(p,'parallel',false,@islogical);
%addParameter(p,'nCore',1,@isnumeric); % not yet implemented
parse(p,fun,Xlim,nPatch,ordCC,dx,nSubP,varargin{:});
%{
\end{matlab}
Set the optional parameters.
\begin{matlab}
%}
patches.nEdge = p.Results.nEdge;
if numel(patches.nEdge)==1
patches.nEdge = repmat(patches.nEdge,1,3);
end
patches.EdgyInt = p.Results.EdgyInt;
patches.nEnsem = p.Results.nEnsem;
cs = p.Results.hetCoeffs;
patches.parallel = p.Results.parallel;
%patches.nCore = p.Results.nCore;
%{
\end{matlab}
Initially duplicate parameters for three space dimensions as
needed.
\begin{matlab}
%}
if numel(Xlim)==2, Xlim = repmat(Xlim,1,3); end
if numel(nPatch)==1, nPatch = repmat(nPatch,1,3); end
if numel(dx)==1, dx = repmat(dx,1,3); end
if numel(nSubP)==1, nSubP = repmat(nSubP,1,3); end
%{
\end{matlab}
Check parameters.
\begin{matlab}
%}
assert(Xlim(1)<Xlim(2) ...
,'first pair of Xlim must be ordered increasing')
assert(Xlim(3)<Xlim(4) ...
,'second pair of Xlim must be ordered increasing')
assert(Xlim(5)<Xlim(6) ...
,'third pair of Xlim must be ordered increasing')
assert((mod(ordCC,2)==0)|all(patches.nEdge==1) ...
,'Cannot yet have nEdge>1 and staggered patch grids')
assert(all(3*patches.nEdge<=nSubP) ...
,'too many edge values requested')
assert(all(rem(nSubP,patches.nEdge)==0) ...
,'nSubP must be integer multiple of nEdge')
if ~patches.EdgyInt, assert(all(rem(nSubP./patches.nEdge,2)==1) ...
,'for non-edgyInt, nSubP./nEdge must be odd integer')
end
if (patches.nEnsem>1)&all(patches.nEdge>1)
warning('not yet tested when both nEnsem and nEdge non-one')
end
%if patches.nCore>1
% warning('nCore>1 not yet tested in this version')
% end
%{
\end{matlab}
For compatibility with pre-2023 functions, if parameter
\verb|Dom| is \verb|Nan|, then we set the \verb|ratio| to
be the value of the so-called \verb|dx| vector.
\begin{matlab}
%}
if ~isstruct(Dom), pre2023=isnan(Dom);
else pre2023=false; end
if pre2023, ratio=dx; dx=nan; end
%{
\end{matlab}
Default macroscale conditions are periodic with evenly
spaced patches.
\begin{matlab}
%}
if isempty(Dom), Dom=struct('type','periodic'); end
if (~isstruct(Dom))&isnan(Dom), Dom=struct('type','periodic'); end
%{
\end{matlab}
If \verb|Dom| is a string, then just set type to that
string, and subsequently set corresponding defaults for
others fields.
\begin{matlab}
%}
if ischar(Dom), Dom=struct('type',Dom); end
%{
\end{matlab}
We allow different macroscale domain conditions in the
different directions. But for the moment do not allow
periodic to be mixed with the others (as the interpolation
mechanism is different code)---hence why we choose
\verb|periodic| be seven characters, whereas the others are
eight characters. The different conditions are coded in
different rows of \verb|Dom.type|, so we duplicate the
string if only one row specified.
\begin{matlab}
%}
if size(Dom.type,1)==1, Dom.type=repmat(Dom.type,3,1); end
%{
\end{matlab}
Check what is and is not specified, and provide default of
Dirichlet boundaries if no \verb|bcOffset| specified when
needed. Do so for all three directions independently.
\begin{matlab}
%}
patches.periodic=false;
for p=1:3
switch Dom.type(p,:)
case 'periodic'
patches.periodic=true;
if isfield(Dom,'bcOffset')
warning('bcOffset not available for Dom.type = periodic'), end
msg=' not available for Dom.type = periodic';
if isfield(Dom,'X'), warning(['X' msg]), end
if isfield(Dom,'Y'), warning(['Y' msg]), end
if isfield(Dom,'Z'), warning(['Z' msg]), end
case {'equispace','chebyshev'}
if ~isfield(Dom,'bcOffset'), Dom.bcOffset=zeros(2,3); end
% for mixed with usergiven, following should still work
if numel(Dom.bcOffset)==1
Dom.bcOffset=repmat(Dom.bcOffset,2,3); end
if numel(Dom.bcOffset)==3
Dom.bcOffset=repmat(Dom.bcOffset(:)',2,1); end
msg=' not available for Dom.type = equispace or chebyshev';
if (p==1)& isfield(Dom,'X'), warning(['X' msg]), end
if (p==2)& isfield(Dom,'Y'), warning(['Y' msg]), end
if (p==3)& isfield(Dom,'Z'), warning(['Z' msg]), end
case 'usergiven'
% if isfield(Dom,'bcOffset')
% warning('bcOffset not available for usergiven Dom.type'), end
msg=' required for Dom.type = usergiven';
if p==1, assert(isfield(Dom,'X'),['X' msg]), end
if p==2, assert(isfield(Dom,'Y'),['Y' msg]), end
if p==3, assert(isfield(Dom,'Z'),['Z' msg]), end
otherwise
error([Dom.type ' is unknown Dom.type'])
end%switch Dom.type
end%for p
%{
\end{matlab}
\subsection{The code to make patches}
First, store the pointer to the time derivative function in
the struct.
\begin{matlab}
%}
patches.fun = fun;
%{
\end{matlab}
Second, store the order of interpolation that is to provide
the values for the inter-patch coupling conditions. Spectral
coupling is \verb|ordCC| of~$0$ or (not yet??)~$-1$.
\begin{matlab}
%}
assert((ordCC>=-1) & (floor(ordCC)==ordCC), ...
'ordCC out of allowed range integer>=-1')
%{
\end{matlab}
For odd~\verb|ordCC| do interpolation based upon odd
neighbouring patches as is useful for staggered grids.
\begin{matlab}
%}
patches.stag = mod(ordCC,2);
assert(patches.stag==0,'staggered not yet implemented??')
ordCC = ordCC+patches.stag;
patches.ordCC = ordCC;
%{
\end{matlab}
Check for staggered grid and periodic case.
\begin{matlab}
%}
if patches.stag, assert(all(mod(nPatch,2)==0), ...
'Require an even number of patches for staggered grid')
end
%{
\end{matlab}
\paragraph{Set the macro-distribution of patches}
Third, set the centre of the patches in the macroscale grid
of patches. Loop over the coordinate directions, setting
the distribution into~\verb|Q| and finally assigning to
array of corresponding direction.
\begin{matlab}
%}
for q=1:3
qq=2*q-1;
%{
\end{matlab}
Distribution depends upon \verb|Dom.type|:
\begin{matlab}
%}
switch Dom.type(q,:)
%{
\end{matlab}
%: case periodic
The periodic case is evenly spaced within the spatial
domain. Store the size ratio in \verb|patches|.
\begin{matlab}
%}
case 'periodic'
Q=linspace(Xlim(qq),Xlim(qq+1),nPatch(q)+1);
DQ=Q(2)-Q(1);
Q=Q(1:nPatch(q))+diff(Q)/2;
pEI=patches.EdgyInt;% abbreviation
pnE=patches.nEdge(q);% abbreviation
if pre2023, dx(q) = ratio(q)*DQ/(nSubP(q)-pnE*(1+pEI))*(2-pEI);
else ratio(q) = dx(q)/DQ*(nSubP(q)-pnE*(1+pEI))/(2-pEI);
end
patches.ratio=ratio;
%{
\end{matlab}
%: case equispace
The equi-spaced case is also evenly spaced but with the
extreme edges aligned with the spatial domain boundaries,
modified by the offset.
\begin{matlab}
%}
case 'equispace'
Q=linspace(Xlim(qq)+((nSubP(q)-1)/2-Dom.bcOffset(qq))*dx(q) ...
,Xlim(qq+1)-((nSubP(q)-1)/2-Dom.bcOffset(qq+1))*dx(q) ...
,nPatch(q));
DQ=diff(Q(1:2));
width=(1+patches.EdgyInt)/2*(nSubP(q)-1-patches.EdgyInt)*dx;
if DQ<width*0.999999
warning('too many equispace patches (double overlapping)')
end
%{
\end{matlab}
%: case chebyshev
The Chebyshev case is spaced according to the Chebyshev
distribution in order to reduce macro-interpolation errors,
\(Q_i \propto -\cos(i\pi/N)\), but with the extreme edges
aligned with the spatial domain boundaries, modified by the
offset, and modified by possible `boundary layers'.
\footnote{ However, maybe overlapping patches near a
boundary should be viewed as some sort of spatially analogue
of the `christmas tree' of projective integration and its
integration to a slow manifold. Here maybe the overlapping
patches allow for a `christmas tree' approach to the
boundary layers. Needs to be explored??}
\begin{matlab}
%}
case 'chebyshev'
halfWidth=dx(q)*(nSubP(q)-1)/2;
Q1 = Xlim(1)+halfWidth-Dom.bcOffset(qq)*dx(q);
Q2 = Xlim(2)-halfWidth+Dom.bcOffset(qq+1)*dx(q);
% Q = (Q1+Q2)/2-(Q2-Q1)/2*cos(linspace(0,pi,nPatch));
%{
\end{matlab}
Search for total width of `boundary layers' so that in the
interior the patches are non-overlapping Chebyshev. But
the width for assessing overlap of patches is the following
variable \verb|width|.
\begin{matlab}
%}
pEI=patches.EdgyInt; % abbreviation
pnE=patches.nEdge(q);% abbreviation
width=(1+pEI)/2*(nSubP(q)-pnE*(1+pEI))*dx(q);
for b=0:2:nPatch(q)-2
DQmin=(Q2-Q1-b*width)/2*( 1-cos(pi/(nPatch(q)-b-1)) );
if DQmin>width, break, end
end%for
if DQmin<width*0.999999
warning('too many Chebyshev patches (mid-domain overlap)')
end%if
%{
\end{matlab}
Assign the centre-patch coordinates.
\begin{matlab}
%}
Q =[ Q1+(0:b/2-1)*width ...
(Q1+Q2)/2-(Q2-Q1-b*width)/2*cos(linspace(0,pi,nPatch(q)-b)) ...
Q2+(1-b/2:0)*width ];
%{
\end{matlab}
%: case usergiven
The user-given case is entirely up to a user to specify, we
just ensure it has the correct shape of a row.
\begin{matlab}
%}
case 'usergiven'
if q==1, Q = reshape(Dom.X,1,[]); end
if q==2, Q = reshape(Dom.Y,1,[]); end
if q==3, Q = reshape(Dom.Z,1,[]); end
end%switch Dom.type
%{
\end{matlab}
Assign \(Q\)-coordinates to the correct spatial direction.
At this stage they are all rows.
\begin{matlab}
%}
if q==1, X=Q; end
if q==2, Y=Q; end
if q==3, Z=Q; end
end%for q
%{
\end{matlab}
\paragraph{Construct the micro-grids}
Fourth, construct the microscale grid in each patch, centred
about the given mid-points~\verb|X,Y,Z|. Reshape the grid to be
8D to suit dimensions (micro,Vars,Ens,macro).
\begin{matlab}
%}
xs = dx(1)*( (1:nSubP(1))-mean(1:nSubP(1)) );
patches.x = reshape( xs'+X ...
,nSubP(1),1,1,1,1,nPatch(1),1,1);
ys = dx(2)*( (1:nSubP(2))-mean(1:nSubP(2)) );
patches.y = reshape( ys'+Y ...
,1,nSubP(2),1,1,1,1,nPatch(2),1);
zs = dx(3)*( (1:nSubP(3))-mean(1:nSubP(3)) );
patches.z = reshape( zs'+Z ...
,1,1,nSubP(3),1,1,1,1,nPatch(3));
%{
\end{matlab}
\paragraph{Pre-compute weights for macro-periodic} In the
case of macro-periodicity, precompute the weightings to
interpolate field values for coupling. \todo{Might sometime
extend to coupling via derivative values.}
\begin{matlab}
%}
if patches.periodic
ratio = reshape(ratio,1,3); % force to be row vector
patches.ratio = ratio;
if ordCC>0
[Cwtsr,Cwtsl] = patchCwts(ratio,ordCC,patches.stag);
patches.Cwtsr = Cwtsr; patches.Cwtsl = Cwtsl;
end%if
end%if patches.periodic
%{
\end{matlab}
\subsection{Set ensemble inter-patch communication}
For \verb|EdgyInt| or centre interpolation respectively,
\begin{itemize}
\item the right-face\slash centre realisations
\verb|1:nEnsem| are to interpolate to left-face~\verb|le|,
and
\item the left-face\slash centre realisations
\verb|1:nEnsem| are to interpolate to~\verb|re|.
\end{itemize}
\verb|re| and \verb|li| are `transposes' of each other as
\verb|re(li)=le(ri)| are both \verb|1:nEnsem|. Similarly for
bottom-face\slash centre interpolation to top-face
via~\verb|to|, top-face\slash centre interpolation to
bottom-face via~\verb|bo|, back-face\slash centre
interpolation to front-face via~\verb|fr|, and
front-face\slash centre interpolation to back-face
via~\verb|ba|.
The default is nothing shifty. This setting reduces the
number of if-statements in function \verb|patchEdgeInt3()|.
\begin{matlab}
%}
nE = patches.nEnsem;
patches.le = 1:nE; patches.ri = 1:nE;
patches.bo = 1:nE; patches.to = 1:nE;
patches.ba = 1:nE; patches.fr = 1:nE;
%{
\end{matlab}
However, if heterogeneous coefficients are supplied via
\verb|hetCoeffs|, then do some non-trivial replications.
First, get microscale periods, patch size, and replicate
many times in order to subsequently sub-sample: \verb|nSubP|
times should be enough. If \verb|cs| is more then 4D, then
the higher-dimensions are reshaped into the 4th dimension.
\begin{matlab}
%}
if ~isempty(cs)
[mx,my,mz,nc] = size(cs);
nx = nSubP(1); ny = nSubP(2); nz = nSubP(3);
cs = repmat(cs,nSubP);
%{
\end{matlab}
If only one member of the ensemble is required, then
sub-sample to patch size, and store coefficients in
\verb|patches| as is.
\begin{matlab}
%}
if nE==1, patches.cs = cs(1:nx-1,1:ny-1,1:nz-1,:); else
%{
\end{matlab}
But for $\verb|nEnsem|>1$ an ensemble of
$m_xm_ym_z$~phase-shifts of the coefficients is
constructed from the over-supply. Here code phase-shifts
over the periods---the phase shifts are like
Hankel-matrices.
\begin{matlab}
%}
patches.nEnsem = mx*my*mz;
patches.cs = nan(nx-1,ny-1,nz-1,nc,mx,my,mz);
for k = 1:mz
ks = (k:k+nz-2);
for j = 1:my
js = (j:j+ny-2);
for i = 1:mx
is = (i:i+nx-2);
patches.cs(:,:,:,:,i,j,k) = cs(is,js,ks,:);
end
end
end
patches.cs = reshape(patches.cs,nx-1,ny-1,nz-1,nc,[]);
%{
\end{matlab}
Further, set a cunning left\slash right\slash bottom\slash
top\slash front\slash back realisation of inter-patch
coupling. The aim is to preserve symmetry in the system
when also invoking \verb|EdgyInt|. What this coupling does
without \verb|EdgyInt| is unknown. Use auto-replication.
\begin{matlab}
%}
mmx=(0:mx-1)'; mmy=0:my-1; mmz=shiftdim(0:mz-1,-1);
le = mod(mmx+mod(nx-2,mx),mx)+1;
patches.le = reshape( le+mx*(mmy+my*mmz) ,[],1);
ri = mod(mmx-mod(nx-2,mx),mx)+1;
patches.ri = reshape( ri+mx*(mmy+my*mmz) ,[],1);
bo = mod(mmy+mod(ny-2,my),my)+1;
patches.bo = reshape( 1+mmx+mx*(bo-1+my*mmz) ,[],1);
to = mod(mmy-mod(ny-2,my),my)+1;
patches.to = reshape( 1+mmx+mx*(to-1+my*mmz) ,[],1);
ba = mod(mmz+mod(nz-2,mz),mz)+1;
patches.ba = reshape( 1+mmx+mx*(mmy+my*(ba-1)) ,[],1);
fr = mod(mmz-mod(nz-2,mz),mz)+1;
patches.fr = reshape( 1+mmx+mx*(mmy+my*(fr-1)) ,[],1);
%{
\end{matlab}
Issue warning if the ensemble is likely to be affected by
lack of scale separation. \todo{Need to justify this and
the arbitrary threshold more carefully??}
\begin{matlab}
%}
if prod(ratio)*patches.nEnsem>0.9, warning( ...
'Probably poor scale separation in ensemble of coupled phase-shifts')
scaleSeparationParameter = ratio*patches.nEnsem
end
%{
\end{matlab}
End the two if-statements.
\begin{matlab}
%}
end%if-else nEnsem>1
end%if not-empty(cs)
%{
\end{matlab}
\paragraph{If parallel code} then first assume this is not
within an \verb|spmd|-environment, and so we invoke
\verb|spmd...end| (which starts a parallel pool if not
already started). At this point, the global \verb|patches|
is copied for each worker processor and so it becomes
\emph{composite} when we distribute any one of the fields.
Hereafter, {\em all fields in the global variable
\verb|patches| must only be referenced within an
\verb|spmd|-environment.}%
\footnote{If subsequently outside spmd, then one must use
functions like \texttt{getfield(patches\{1\},'a')}.}
\begin{matlab}
%}
if patches.parallel
spmd
%{
\end{matlab}
Second, decide which dimension is to be sliced among
parallel workers (for the moment, do not consider slicing
the ensemble). Choose the direction of most patches, biased
towards the last.
\begin{matlab}
%}
[~,pari]=max(nPatch+0.01*(1:3));
patches.codist=codistributor1d(5+pari);
%{
\end{matlab}
\verb|patches.codist.Dimension| is the index that is split
among workers. Then distribute the appropriate coordinate
direction among the workers: the function must be invoked
inside an \verb|spmd|-group in order for this to work---so
we do not need \verb|parallel| in argument list.
\begin{matlab}
%}
switch pari
case 1, patches.x=codistributed(patches.x,patches.codist);
case 2, patches.y=codistributed(patches.y,patches.codist);
case 3, patches.z=codistributed(patches.z,patches.codist);
otherwise
error('should never have bad index for parallel distribution')
end%switch
end%spmd
%{
\end{matlab}
If not parallel, then clean out \verb|patches.codist| if it exists.
May not need, but safer.
\begin{matlab}
%}
else% not parallel
if isfield(patches,'codist'), rmfield(patches,'codist'); end
end%if-parallel
%{
\end{matlab}
\paragraph{Fin}
\begin{matlab}
%}
end% function
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
quasiLogAxes.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/quasiLogAxes.m
| 7,770 |
utf_8
|
3c6cea4c5e176ba4f43466f34876e111
|
% quasiLogAxes() transforms selected axes of the given plot
% to a quasi-log axes (via asinh), including possibly
% transforming color axis. AJR, 25 Sep 2021 -- 18 Apr 2023
%!TEX root = doc.tex
%{
\section{\texttt{quasiLogAxes()}: transforms some axes of a
plot to quasi-log}
\label{sec:quasiLogAxes}
This function rescales some coordinates and labels the axes
of the given 2D or 3D~plot. The original aim was to
effectively show the complex spectrum of multiscale systems
such as the patch scheme. The eigenvalues are over a wide
range of magnitudes, but are signed. So we use a nonlinear
asinh transformation of the axes, and then label the axes
with reasonable ticks. The nonlinear rescaling is useful in
other scenarios also.
\begin{matlab}
%}
function quasiLogAxes(handle,xScale,yScale,zScale,cScale)
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|handle|: handle to your plot to transform, for
example, obtained by \verb|handle=plot(...)|
\item \verb|xScale| (optional, default~inf): if inf, then no
transformation is done in the `x'-coordinate. Otherwise, when
\verb|xScale| is not inf, transforms the plot \(x\)-coordinates
with the \(\text{asinh}()\) function so that
\begin{itemize}
\item for \(|x|\lesssim x_{\text{scale}}\) the x-axis scaling
is approximately linear, whereas
\item for \(|x|\gtrsim x_{\text{scale}}\) the x-axis scaling
is approximately signed-logarithmic.
\end{itemize}
\item \verb|yScale| (optional, default~inf): corresponds to
\verb|xScale| for the second axis scaling.
\item \verb|zScale| (optional, default~inf): corresponds to
\verb|xScale| for a third axis scaling if it exists.
\item \verb|cScale| (optional, default~inf): corresponds to
\verb|xScale| but for a colormap, and colorbar scaling if
one exists.
\end{itemize}
\paragraph{Output} None, just the transformed plot.
\paragraph{Example}
If invoked with no arguments, then execute an example.
\begin{matlab}
%}
if nargin==0
% generate some data
n=99; fast=(rand(n,1)<0.8);
z = -rand(n,1).*(1+1e3*fast)+1i*randn(n,1).*(5+1e2*fast);
% plot data and transform axes
handle = plot(real(z),imag(z),'.');
xlabel('real-part'), ylabel('imag-part')
quasiLogAxes(handle,1,10);
return
end% example
%{
\end{matlab}
Default values for scaling, \verb|inf| denotes no
transformation of that axis.
\begin{matlab}
%}
if nargin<5, cScale=inf; end
if nargin<4, zScale=inf; end
if nargin<3, yScale=inf; end
if nargin<2, xScale=inf; end
%{
\end{matlab}
\begin{devMan}
Get current limits of the plot to use if the user has set
them already. And also get the pointer to the axes and to
the figure of the plot.
\begin{matlab}
%}
xlim0=xlim; ylim0=ylim; zlim0=zlim; clim0=caxis;
theAxes = get(handle(1),'parent');
theFig = get(theAxes,'parent');
%{
\end{matlab}
Find overall factors so the data is nonlinearly mapped to
order oneish---so that then pgfplots et al.\ do not think
there is an overall scaling factor on the axes.
\begin{matlab}
%}
xFac=1e-99; yFac=xFac; zFac=xFac; cFac=xFac;
for k=1:length(handle)
if ~isinf(xScale)
temp = asinh(handle(k).XData/xScale);
xFac = max(xFac, max(abs(temp(:)),[],'omitnan') );
end
if ~isinf(yScale)
temp = asinh(handle(k).YData/yScale);
yFac = max(yFac, max(abs(temp(:)),[],'omitnan') );
end
if ~isinf(zScale)
temp = asinh(handle(k).ZData/zScale);
zFac = max(zFac, max(abs(temp(:)),[],'omitnan') );
end
if ~isinf(cScale)
temp = asinh(handle(k).CData/cScale);
cFac = max(cFac, max(abs(temp(:)),[],'omitnan') );
end
end%for
xFac=9/xFac; yFac=9/yFac; zFac=9/zFac; cFac=9/cFac;
%{
\end{matlab}
Scale the plot data in the plot \verb|handle|. Give an
error if it appears that the plot-data has already been
transformed. Color data has to be transformed first
because usually there is automatic flow from z-data to c-data.
\begin{matlab}
%}
for k=1:length(handle)
assert(~strcmp(handle(k).UserData,'quasiLogAxes'), ...
'Replot graph---it appears plot data is already transformed')
if ~isinf(cScale)
handle(k).CData = cFac*asinh(handle(k).CData/cScale);
clim1=[min(handle(k).CData(:)) max(handle(k).CData(:))];
end
if ~isinf(xScale)
handle(k).XData = xFac*asinh(handle(k).XData/xScale);
xlim1=[min(handle(k).XData(:)) max(handle(k).XData(:))];
end
if ~isinf(yScale)
handle(k).YData = yFac*asinh(handle(k).YData/yScale);
ylim1=[min(handle(k).YData(:)) max(handle(k).YData(:))];
end
if ~isinf(zScale)
handle(k).ZData = zFac*asinh(handle(k).ZData/zScale);
zlim1=[min(handle(k).ZData(:)) max(handle(k).ZData(:))];
end
handle(k).UserData = 'quasiLogAxes';
end%for
%{
\end{matlab}
Set 4\%~padding around all margins of transformed
data---crude but serviceable. Unless the axis had already
been manually set, in which case use the transformed set
limits.
\begin{matlab}
%}
if ~isinf(xScale),
if xlim('mode')=="manual"
xlim1=xFac*asinh(xlim0/xScale);
else xlim1=xlim1+0.04*diff(xlim1)*[-1 1];
end, end
if ~isinf(yScale),
if ylim('mode')=="manual"
ylim1=yFac*asinh(ylim0/yScale);
else ylim1=ylim1+0.04*diff(ylim1)*[-1 1];
end, end
if ~isinf(zScale),
if zlim('mode')=="manual"
zlim1=zFac*asinh(zlim0/zScale);
else zlim1=zlim1+0.04*diff(zlim1)*[-1 1];
end, end
if ~isinf(cScale),
if theAxes.CLimMode=="manual"
clim1=cFac*asinh(clim0/cScale);
else clim1=clim1+ 0*diff(clim1)*[-1 1];
end, end
%{
\end{matlab}
\paragraph{Scale axes, and tick marks on axes}
\begin{matlab}
%}
if ~isinf(xScale)
xlim(xlim1);
tickingQuasiLogAxes(theAxes,'X',xlim1,xScale,xFac)
end%if
if ~isinf(yScale)
ylim(ylim1);
tickingQuasiLogAxes(theAxes,'Y',ylim1,yScale,yFac)
end%if
if ~isinf(zScale)
zlim(zlim1);
tickingQuasiLogAxes(theAxes,'Z',zlim1,zScale,zFac)
end%if
%{
\end{matlab}
But for color, only tick when we find a colorbar.
\begin{matlab}
%}
if ~isinf(cScale)
caxis(clim1);
for p=1:numel(theFig.Children)
ca = theFig.Children(p);
if class(ca) == "matlab.graphics.illustration.ColorBar"
tickingQuasiLogAxes(ca,'C',clim1,cScale,cFac)
break
end
end
end%if
%{
\end{matlab}
Turn the grid on by default.
\begin{matlab}
%}
grid on
end%function
%{
\end{matlab}
\subsection{\texttt{tickingQuasiLogAxes()}: typeset ticks
and labels on an axis}
\begin{matlab}
%}
function tickingQuasiLogAxes(ca,Q,qlim1,qScale,qFac)
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|ca|: pointer to axes/colorbar dataset.
\item \verb|Q|: character, either \texttt{X,Y,Z,C}.
\item \verb|qlim1|: the scaled limits of the axis.
\item \verb|qScale|: the scaling parameter for the axis.
\item \verb|qFac|: the scaling factor for the axis.
\end{itemize}
\paragraph{Output} None, just the ticked and labelled axes.
Get the order of magnitude of the horizontal data.
\begin{matlab}
%}
qmax=max(abs(qlim1));
qmag=floor(log10(qScale*sinh(qmax/qFac)));
%{
\end{matlab}
Form a range of ticks, geometrically spaced, trim off the
small values that would be too dense near zero (omit those
within 6\% of \verb|qmax|).
\begin{matlab}
%}
ticks=10.^(qmag+(-7:0));
j=find(ticks>qScale*sinh(0.06*qmax/qFac));
nj=length(j);
if nj<3, ticks=[1;2;5]*ticks(j);
elseif nj<5, ticks=[1;3]*ticks(j);
else ticks=ticks(j);
end
ticks=sort([0;ticks(:);-ticks(:)]);
%{
\end{matlab}
Set the ticks in place according to the transformation.
\begin{matlab}
%}
if Q=='C', p='s'; Q=''; else p=''; end
set(ca,[Q 'Tick' p],qFac*asinh(ticks/qScale) ...
,[Q 'TickLabel' p],cellstr(num2str(ticks,4)))
if Q=='X', set(ca,[Q 'TickLabelRotation'],40), end
end%function qScaling
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
SwiftHohenberg2dPattern.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/SwiftHohenberg2dPattern.m
| 7,080 |
utf_8
|
07fe674e7f52283bfae0d9831267a22f
|
% Simulate Swift--Hohenberg PDE in 2D on patches as an
% example application of patches in 2D space with pairs of
% edge points needing to be interpolated between patches.
% AJR, 13 Apr 2023
%!TEX root = doc.tex
%{
\section{\texttt{SwiftHohenberg2dPattern}: patterns of the
Swift--Hohenberg PDE in 2D on patches}
\label{sec:SwiftHohenberg2dPattern}
\localtableofcontents
\cref{fig:SwiftHohenberg2dPattern2,fig:SwiftHohenberg2dPattern3%
,fig:SwiftHohenberg2dPattern4,fig:SwiftHohenberg2dPattern5%
,fig:SwiftHohenberg2dPattern6,fig:SwiftHohenberg2dPattern7}
show an example simulation in time generated by the patch
scheme applied to the patterns arising from the 2D
Swift--Hohenberg \pde.
Consider a lattice of values~\(u_i(t)\), with lattice
spacing~\(dx\), and governed by a microscale centred
discretisation of the Swift--Hohenberg \pde
\begin{equation}
\partial_tu = -(1+\delsq/k_0^2)^2u+\Ra u-u^3,
\label{eq:SwiftHohenberg2dPattern}
\end{equation}
with various boundary conditions at \(x,y=0,L\). For \Ra\
just above critical, say \(\Ra=0.1\), the system rapidly
evolves to spatial quasi-periodic solutions with period\({}
\approx 0.24\) when wavenumber parameter \(k_0 = 26\).
These spatial oscillations are here resolved on a micro-grid
of spacing~\(0.042\). On medium times these spatial
oscillations grow to near equilibrium amplitude
of~\(\sqrt{\Ra}\), and over very long times the phases of
the oscillations evolve in space to adapt to the boundaries.
Set the desired microscale periodicity, and correspondingly
choose random microscale diffusion coefficients (with
subscripts shifted by a half).
\begin{matlab}
%}
clear all
cMap=jet(64); cMap=0.8*cMap(7:end-7,:); % set colormap
basename = ['r' num2str(floor(1e5*rem(now,1))) mfilename]
%global OurCf2eps, OurCf2eps=true %optional to save plots
Ra = 0.2 % Ra>0 leads to patterns
nGapFac = 2
waveLength = 0.5/nGapFac
nPtsPeriod = 6
dx = waveLength/nPtsPeriod
k0 = 2.1*pi/waveLength
%{
\end{matlab}
The above factor~\(2.1\) is close to \(3/\sqrt2=2.1213\) for
which \((\pm1,\pm2)\) modes have same linear growth-rate
as~\((\pm2,0)\) modes.
Establish global data struct~\verb|patches| for the
Swift--Hohenberg \pde\ on some square domain. For
simplicity, use five patches in each direction. Quartic
(fourth-order) interpolation \(\verb|ordCC|=4\) provides
values for the inter-patch coupling conditions. Set
\verb|bcOffset| for different boundary conditions around the
square domain.
\begin{matlab}
%}
nPatch = 5
nSubP = 2*nPtsPeriod+4
Len = nPatch;
ordCC = 4;
dom.type='equispace';
dom.bcOffset=[0.5 0.5;1.0 1.5]
patches = configPatches2(@SwiftHohenbergPDE,[0 Len],dom ...
,nPatch,ordCC,dx,nSubP,'EdgyInt',true,'nEdge',2);
xs=squeeze(patches.x);
ys=squeeze(patches.y);
%{
\end{matlab}
\subsubsection{Simulate in time}
Set an initial condition, and here integrate forward in time
using a standard method for stiff systems. Integrate the
interface \verb|patchSys2| (\cref{sec:patchSys2}) to the
microscale differential equations (despite the extreme
stiffness, \verb|ode23| is ten times quicker than
\verb|ode15s|). Because pattern evolution is eventually
phase-diffusion, here sample the pattern at quadratically
varying times.
\begin{matlab}
%}
fprintf('\n**** Simulate in time\n')
u0 = 0.3*( -1+2*rand(size(patches.x+patches.y)) );
Ts=400*linspace(0,1,97).^2;
tic
[ts,us] = ode23(@patchSys2, Ts, u0(:),[],patches,k0,Ra);
simulateTime = toc
us = reshape(us',nSubP,nSubP,nPatch,nPatch,[]);
%{
\end{matlab}
\foreach \p in {2,...,7}{%
\begin{SCfigure}\centering
\caption{\label{fig:SwiftHohenberg2dPattern\p} pattern field
\(u(x,y,t)\) in the patch scheme applied to a microscale
discretisation of the 2D Swift--Hohenberg \pde. \ifcase\p\or
\or%2
At this early time much of the random sub-patch microstrucre
has decayed leaving some random marginal modes starting to
grow.
\or%3
By now the local sub-patch patterns have reached a
quasi-equilibrium amplitude.
\or%4
Patterns within the patches are evolving to the preferred
rolls, but with weak coupling to other patches.
\or%5
Can see different effects arising at different types of
boundaries.
\else \ldots
\fi}
\includegraphics[scale=0.9]{r26336SwiftHohenberg2dPattern\p}
\end{SCfigure}
}%end foreach
Plot the simulation such as that shown in
\cref{fig:SwiftHohenberg2dPattern2,fig:SwiftHohenberg2dPattern3%
,fig:SwiftHohenberg2dPattern4,fig:SwiftHohenberg2dPattern5%
,fig:SwiftHohenberg2dPattern6,fig:SwiftHohenberg2dPattern7}
First, reshape the data, omitting edge values.
\begin{matlab}
%}
xs([1:2 end-1:end],:) = nan;
ys([1:2 end-1:end],:) = nan;
us = reshape( permute(us,[1 3 2 4 5]) ...
,nSubP*nPatch,nSubP*nPatch,[]);
uRange=[min(us(:)) max(us(:))];
%{
\end{matlab}
Second, plot six examples of the evolving pattern,
equi-spaced in time-index.
\begin{matlab}
%}
plots = round( 1+linspace(0,1,7)*(numel(ts)-1) )
for p=2:numel(plots)
figure(p),clf
mesh(xs(:),ys(:),us(:,:,plots(p))')
axis equal, view(0,90)
caxis(uRange), colormap(cMap), colorbar
xlabel('space $x$'), ylabel('space $y$'), zlabel('$u(x,y,t)$')
title(['time = ' num2str(ts(plots(p)),3)])
ifOurCf2eps([basename num2str(p)],[12 11])
end%for p
%{
\end{matlab}
Third, plot animation in time: starts after a key press.
\begin{matlab}
%}
%%
figure(1),clf
cf=mesh(xs(:),ys(:),us(:,:,1)');
axis equal, view(0,90)
caxis(uRange), colormap(cMap), colorbar
xlabel('space x'), ylabel('space y'), zlabel('$u(x,y,t)$')
title(['time = ' num2str(ts(1),3)])
ca=gca;
disp('Press any key to start animation'),pause
for p=2:numel(ts)
cf.ZData=us(:,:,p)';
cf.CData=us(:,:,p)';
ca.Title.String=['time = ' num2str(ts(p),3)];
pause(0.1)
end
%{
\end{matlab}
Fin.
\subsection{The Swift--Hohenberg PDE and BCs inside patches}
As a microscale discretisation of Swift--Hohenberg \pde\
\(u_t= -(1+\delsq/k_0^2)^2u +\Ra u -u^3\), here code
straightforward centred discretisation in space.
\begin{matlab}
%}
function ut=SwiftHohenbergPDE(t,u,patches,k0,Ra)
dx=diff(patches.x(1:2)); % microscale spacing
dy=diff(patches.y(1:2)); % microscale spacing
i=3:size(u,1)-2; % interior points in patches
j=3:size(u,2)-2; % interior points in patches
%{
\end{matlab}
Code various boundary conditions. For slightly simpler
coding, squeeze out the two singleton dimensions.
\begin{matlab}
%}
u = squeeze(u);
u(1:2,:,1,:)=0; % u=u_x=0 at x=0
u(:,1:2,:,1)=0; % u=u_y=0 at y=0
u(end-1,:,end,:)=0; % u=0 at x=L
u(end ,:,end,:)=-u(end-2,:,end,:); % u_x=0 at x=L
u(:,end-1,:,end)=-u(:,end-2,:,end); % u_y=0 at y=L
u(:,end ,:,end)=-u(:,end-3,:,end); % u_yyy=0 at y=L
%{
\end{matlab}
Here code straightforward centred discretisation in space.
\begin{matlab}
%}
ut=nan+u; % preallocate output array
v = u(2:end-1,2:end-1,:,:) ...
+( diff(u(:,2:end-1,:,:),2,1)/dx^2 ...
+diff(u(2:end-1,:,:,:),2,2)/dy^2 )/k0^2;
ut(i,j,:,:) = -( v(2:end-1,2:end-1,:,:) ...
+( diff(v(:,2:end-1,:,:),2,1)/dx^2 ...
+diff(v(2:end-1,:,:,:),2,2)/dy^2 )/k0^2 ) ...
+Ra*u(i,j,:,:) -u(i,j,:,:).^3;
end
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchSys1.m
|
.m
|
EquationFreeGit-master/SandpitPlay/MultiEdgeValues/patchSys1.m
| 3,219 |
utf_8
|
a1fb92a0c8cf097956420a725b7f4cef
|
% patchSys1() provides an interface to time integrators for
% the dynamics on patches coupled across space. The system
% must be a lattice system such as PDE discretisations.
% AJR, Nov 2017 -- 31 Mar 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchSys1()}: interface 1D space to time integrators}
\label{sec:patchSys1}
To simulate in time with 1D spatial patches we often need to
interface a user's time derivative function with time
integration routines such as \verb|ode23| or~\verb|PIRK2|.
This function provides an interface. Communicate
patch-design variables (\cref{sec:configPatches1}) either
via the global struct~\verb|patches| or via an optional
third argument. \verb|patches| is required for the parallel
computing of \verb|spmd|, or if parameters are to be passed
though to the user microscale function.
\begin{matlab}
%}
function dudt=patchSys1(t,u,patches,varargin)
if nargin<3, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|nSubP| \cdot \verb|nVars| \cdot \verb|nEnsem| \cdot
\verb|nPatch|$ where there are $\verb|nVars| \cdot
\verb|nEnsem|$ field values at each of the points in the
$\verb|nSubP|\times \verb|nPatch|$ grid.
\item \verb|t| is the current time to be passed to the
user's time derivative function.
\item \verb|patches| a struct set by \verb|configPatches1()|
with the following information used here.
\begin{itemize}
\item \verb|.fun| is the name of the user's function
\verb|fun(t,u,patches,...)| that computes the time
derivatives on the patchy lattice. The array~\verb|u| has
size $\verb|nSubP| \times \verb|nVars| \times \verb|nEnsem|
\times \verb|nPatch|$. Time derivatives should be computed
into the same sized array, then herein the patch edge values
are overwritten by zeros.
\item \verb|.x| is $\verb|nSubP| \times1 \times1 \times
\verb|nPatch|$ array of the spatial locations~$x_{i}$ of
the microscale grid points in every patch. Currently it
\emph{must} be an equi-spaced lattice on the microscale.
\end{itemize}
\item \verb|varargin|, optional, is arbitrary number of
parameters to be passed onto the users time-derivative
function as specified in configPatches1.
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|dudt| is a vector\slash array of of time
derivatives, but with patch edge-values set to zero. It is
of total length $\verb|nSubP| \cdot \verb|nVars| \cdot
\verb|nEnsem| \cdot \verb|nPatch|$ and the same dimensions
as~\verb|u|.
\end{itemize}
\begin{devMan}
Reshape the fields~\verb|u| as a 4D-array, and sets the edge
values from macroscale interpolation of centre-patch values.
\cref{sec:patchEdgeInt1} describes \verb|patchEdgeInt1()|.
\begin{matlab}
%}
sizeu = size(u);
u = patchEdgeInt1(u,patches);
%{
\end{matlab}
Ask the user function for the time derivatives computed in
the array, overwrite its edge values with the dummy value of
zero (as \verb|ode15s| chokes on NaNs), then return to the
user\slash integrator as same sized array as input.
\begin{matlab}
%}
dudt=patches.fun(t,u,patches,varargin{:});
n=patches.nEdge;
dudt([1:n end-n+1:end],:,:,:) = 0;
dudt=reshape(dudt,sizeu);
%{
\end{matlab}
Fin.
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
rk2int.m
|
.m
|
EquationFreeGit-master/SandpitPlay/RKInt/rk2int.m
| 2,266 |
utf_8
|
74c1245d7cd40c8ace1329480e507287
|
%rk2int() is a simple example of Runge--Kutta, 2nd order,
%integration of a given deterministic ODE.
%AJR, 29 Mar 2017
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{rk2int()}}
\label{sec:rk2int}
\localtableofcontents
This is a simple example of Runge--Kutta, 2nd order,
integration of a given deterministic \ode.
\begin{matlab}
%}
function [xs,errs] = rk2int(fun,ts,x0)
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|fun()| is a function such as
\verb|dxdt=fun(t,x)| that computes the right-hand side of
the \ode\ \(d\xv/dt=\fv(\xv,t)\) where \xv~is a column
vector, say in \(\RR^n\) for \(n\geq1\)\,, \(t\)~is a
scalar, and the result~\fv\ is a column vector in~\(\RR^n\).
\item \verb|x0| is an \(\RR^n\) vector of initial values at
the time \verb|ts(1)|.
\item \verb|ts| is a vector of times to compute the
approximate solution, say in~\(\RR^\ell\) for
\(\ell\geq2\)\,.
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|xs|, array in \(\RR^{\ell\times n}\) of
approximate solution row vector at the specified times.
\item \verb|errs|, column vector in \(\RR^{\ell}\) of error
estimate for the step from \(t_{k-1}\) to~\(t_k\).
\end{itemize}
Compute the time-steps and create storage for outputs.
\begin{matlab}
%}
dt = diff(ts);
xs = nan(numel(x0),numel(ts));
errs = nan(numel(ts),1);
%{
\end{matlab}
Initialise first result to the given initial condition, and
evaluate the initial time derivative into~\verb|f1|.
\begin{matlab}
%}
xs(:,1) = x0(:);
errs(1) = 0;
f1 = fun(ts(1),xs(:,1));
%{
\end{matlab}
Compute the time-steps from~\(t_k\) to~\(t_{k+1}\), copying
the derivative~\verb|f1| at the end of the last time-step to
be the derivative at the start of this one.
\begin{matlab}
%}
for k = 1:numel(dt)
f0 = f1;
%{
\end{matlab}
Simple second-order accurate time-step.
\begin{matlab}
%}
xh = xs(:,k)+f0*dt(k)/2;
fh = fun(ts(k)+dt(k)/2,xh);
xs(:,k+1) = xs(:,k)+fh*dt(k);
f1 = fun(ts(k+1),xs(:,k+1));
%{
\end{matlab}
Use the time derivative at~\(t_{k+1}\) to estimate an error
by storing the difference with what Simpson's rule would
estimate.
\begin{matlab}
%}
errs(k+1) = norm(f0-2*fh+f1)*dt(k)/6;
end
xs = xs.';
%{
\end{matlab}
End of the function with results returned in~\verb|xs|
and~\verb|errs|.
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
homoDiffBdryEquil3.m
|
.m
|
EquationFreeGit-master/Patch/homoDiffBdryEquil3.m
| 6,974 |
utf_8
|
7cecd10e3fe6ae3ac7058761acf6df6a
|
% Finds equilibrium of forced heterogeneous diffusion in 3D
% cube on 3D patches as an example application. Boundary
% conditions are Neumann on the right face of the cube, and
% Dirichlet on the other faces. The microscale is of known
% period so we interpolate next-to-edge values to get
% opposite edge values. AJR, 1 Feb 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{homoDiffBdryEquil3}: equilibrium via
computational homogenisation of a 3D heterogeneous diffusion
on small patches}
\label{sec:homoDiffBdryEquil3}
Find the equilibrium of a forced heterogeneous diffusion in
3D space on 3D patches as an example application. Boundary
conditions are Neumann on the right face of the cube, and
Dirichlet on the other faces. \cref{fig:homoDiffBdryEquil3}
shows five isosurfaces of the 3D solution field.
\begin{figure}\centering
\caption{\label{fig:homoDiffBdryEquil3}% Equilibrium of the
macroscale of the random heterogeneous diffusion in 3D with
boundary conditions of zero on all faces except for the
Neumann condition on \(x=1\)
(\cref{sec:homoDiffBdryEquil3}). The small patches are
equispaced in space. }
\includegraphics[scale=0.8]{Figs/homoDiffBdryEquil3.png}
\end{figure}
Clear variables, and establish globals.
\begin{matlab}
%}
clear all
global patches
%global OurCf2eps, OurCf2eps=true %option to save plots
%{
\end{matlab}
Set random heterogeneous diffusivities of random
(small) period in each of the three directions. Crudely
normalise by the harmonic mean so the decay time scale is
roughly one.
\begin{matlab}
%}
mPeriod = randi([2 3],1,3)
cDiff = exp(0.3*randn([mPeriod 3]));
cDiff = cDiff*mean(1./cDiff(:))
%{
\end{matlab}
Configure the patch scheme with some arbitrary choices of
cubic domain, patches, and micro-grid spacing~\(0.05\).
Use high order interpolation as few patches in each
direction. Configure for Dirichlet boundaries except for
Neumann on the right \(x\)-face.
\begin{matlab}
%}
nSubP = mPeriod+2;
nPatch = 5;
Dom.type = 'equispace';
Dom.bcOffset = zeros(2,3); Dom.bcOffset(2) = 0.5;
configPatches3(@microDiffBdry3, [-1 1], Dom ...
, nPatch, 0, 0.05, nSubP, 'EdgyInt',true ...
,'hetCoeffs',cDiff );
%{
\end{matlab}
Set forcing, and store in global patches for access by the
microcode
\begin{matlab}
%}
patches.fu = 10*exp(-patches.x.^2-patches.y.^2-patches.z.^2);
patches.fu = patches.fu.*(1+rand(size(patches.fu)));
%{
\end{matlab}
\paragraph{Solve for steady state}
Set initial guess of zero, with \verb|NaN| to indicate
patch-edge values. Index~\verb|i| are the indices of
patch-interior points, store in global patches for access by
\verb|theRes|, and the number of unknowns is then its
number of elements.
\begin{matlab}
%}
u0 = zeros([nSubP,1,1,nPatch,nPatch,nPatch]);
u0([1 end],:,:,:) = nan;
u0(:,[1 end],:,:) = nan;
u0(:,:,[1 end],:) = nan;
patches.i = find(~isnan(u0));
nVariables = numel(patches.i)
%{
\end{matlab}
Solve by iteration. Use \verb|fsolve| for simplicity and
robustness (optionally \verb|optimoptions| to omit trace
information), via the generic patch system wrapper
\verb|theRes| (\cref{sec:theRes}).
\begin{matlab}
%}
disp('Solving system, takes 10--40 secs'),tic
uSoln = fsolve(@theRes,u0(patches.i) ...
,optimoptions('fsolve','Display','off'));
solveTime = toc
normResidual = norm(theRes(uSoln))
normSoln = norm(uSoln)
%{
\end{matlab}
Store the solution into the patches, and give magnitudes.
\begin{matlab}
%}
u0(patches.i) = uSoln;
u0 = patchEdgeInt3(u0);
%{
\end{matlab}
\paragraph{Plot isosurfaces of the solution}
\begin{matlab}
%}
figure(1), clf
rgb=get(gca,'defaultAxesColorOrder');
%{
\end{matlab}
Reshape spatial coordinates of patches.
\begin{matlab}
%}
x = patches.x(:); y = patches.y(:); z = patches.z(:);
%{
\end{matlab}
Draw isosurfaces. Get the solution with interpolated
faces, form into a 6D array, and reshape and transpose~\(x\)
and~\(y\) to suit the isosurface function.
\begin{matlab}
%}
u = reshape( permute(squeeze(u0),[2 5 1 4 3 6]) ...
, [numel(y) numel(x) numel(z)]);
maxu=max(u(:)), minu=min(u(:))
%{
\end{matlab}
Optionally cut-out the front corner so we can see inside.
\begin{matlab}
%}
u( (x'>0) & (y<0) & (shiftdim(z,-2)>0) ) = nan;
%{
\end{matlab}
Draw some isosurfaces.
\begin{matlab}
%}
clf;
for iso=5:-1:1
isov=(iso-0.5)/5*(maxu-minu)+minu;
hsurf(iso) = patch(isosurface(x,y,z,u,isov));
isonormals(x,y,z,u,hsurf(iso))
set(hsurf(iso) ,'FaceColor',rgb(iso,:) ...
,'EdgeColor','none' ,'FaceAlpha',iso/5);
hold on
end
hold off
axis equal, axis([-1 1 -1 1 -1 1]), view(35,25)
xlabel('$x$'), ylabel('$y$'), zlabel('$z$')
camlight, lighting gouraud
ifOurCf2eps(mfilename) %optionally save plot
if exist('OurCf2eps') && OurCf2eps, print('-dpng',['Figs/' mfilename]), end
%{
\end{matlab}
\subsection{\texttt{microDiffBdry3()}: 3D forced
heterogeneous diffusion with boundaries}
\label{sec:microDiffBdry3}
This function codes the lattice forced heterogeneous
diffusion inside the 3D patches. For 8D input
array~\verb|u| (via edge-value interpolation of
\verb|patchEdgeInt3|, such as by \verb|patchSys3|,
\cref{sec:patchSys3}), computes the time derivative at each
point in the interior of a patch, output in~\verb|ut|. The
three 3D array of diffusivities,~$c^x_{ijk}$, $c^y_{ijk}$
and~$c^z_{ijk}$, have previously been stored
in~\verb|patches.cs| (4D).
Supply patch information as a third argument (required by
parallel computation), or otherwise by a global variable.
\begin{matlab}
%}
function ut = microDiffBdry3(t,u,patches)
if nargin<3, global patches, end
%{
\end{matlab}
Microscale space-steps.
\begin{matlab}
%}
dx = diff(patches.x(2:3)); % x micro-scale step
dy = diff(patches.y(2:3)); % y micro-scale step
dz = diff(patches.z(2:3)); % z micro-scale step
i = 2:size(u,1)-1; % x interior points in a patch
j = 2:size(u,2)-1; % y interior points in a patch
k = 2:size(u,3)-1; % y interior points in a patch
%{
\end{matlab}
Code microscale boundary conditions of say Neumann on right,
and Dirichlet on left, top, bottom, front, and back (viewed
along the \(z\)-axis).
\begin{matlab}
%}
u( 1 ,:,:,:,:, 1 ,:,:)=0; %left face of leftmost patch
u(end,:,:,:,:,end,:,:)=u(end-1,:,:,:,:,end,:,:); %right face of rightmost
u(:, 1 ,:,:,:,:, 1 ,:)=0; %bottom face of bottommost
u(:,end,:,:,:,:,end,:)=0; %top face of topmost
u(:,:, 1 ,:,:,:,:, 1 )=0; %front face of frontmost
u(:,:,end,:,:,:,:,end)=0; %back face of backmost
%{
\end{matlab}
Reserve storage and then assign interior patch values to the
heterogeneous diffusion time derivatives. Using \verb|nan+u|
appears quicker than \verb|nan(size(u),patches.codist)|
\begin{matlab}
%}
ut = nan+u; % reserve storage
ut(i,j,k,:) ...
= diff(patches.cs(:,j,k,1).*diff(u(:,j,k,:),1,1),1,1)/dx^2 ...
+diff(patches.cs(i,:,k,2).*diff(u(i,:,k,:),1,2),1,2)/dy^2 ...
+diff(patches.cs(i,j,:,3).*diff(u(i,j,:,:),1,3),1,3)/dz^2 ...
+patches.fu(i,j,k);
end% function
%{
\end{matlab}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
patchEdgeInt3.m
|
.m
|
EquationFreeGit-master/Patch/patchEdgeInt3.m
| 28,529 |
utf_8
|
994388f67e0cb617d206311ba65f6db3
|
% patchEdgeInt3() provides the interpolation across 3D space
% for 3D patches of simulations of a smooth lattice system
% such as PDE discretisations. AJR, Aug 2020 -- 12 Apr 2023
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{patchEdgeInt3()}: sets 3D patch
face values from 3D macroscale interpolation}
\label{sec:patchEdgeInt3}
Couples 3D patches across 3D space by computing their face
values via macroscale interpolation. Assumes patch face
values are determined by macroscale interpolation of the
patch centre-plane values \cite[]{Roberts2011a,
Bunder2019d}, or patch next-to-face values which appears
better \cite[]{Bunder2020a}. This function is primarily
used by \verb|patchSys3()| but is also useful for user
graphics. \footnote{Script \texttt{patchEdgeInt3test.m}
verifies this code.}
Communicate patch-design variables via a second argument
(optional, except required for parallel computing of
\verb|spmd|), or otherwise via the global
struct~\verb|patches|.
\begin{matlab}
%}
function u = patchEdgeInt3(u,patches)
if nargin<2, global patches, end
%{
\end{matlab}
\paragraph{Input}
\begin{itemize}
\item \verb|u| is a vector\slash array of length
$\verb|prod(nSubP)| \cdot \verb|nVars| \cdot \verb|nEnsem|
\cdot \verb|prod(nPatch)|$ where there are $\verb|nVars|
\cdot \verb|nEnsem|$ field values at each of the points in
the $\verb|nSubP1| \cdot \verb|nSubP2| \cdot \verb|nSubP3|
\cdot \verb|nPatch1| \cdot \verb|nPatch2| \cdot
\verb|nPatch3|$ multiscale spatial grid on the
$\verb|nPatch1| \cdot \verb|nPatch2| \cdot \verb|nPatch3|$
array of patches.
\item \verb|patches| a struct set by \verb|configPatches3()|
which includes the following information.
\begin{itemize}
\item \verb|.x| is $\verb|nSubP1| \times1 \times1 \times1
\times1 \times \verb|nPatch1| \times1 \times1 $ array of the
spatial locations~$x_{iI}$ of the microscale grid points in
every patch. Currently it \emph{must} be an equi-spaced
lattice on the microscale index~$i$, but may be variable
spaced in macroscale index~$I$.
\item \verb|.y| is similarly $1\times \verb|nSubP2| \times1
\times1 \times1 \times1 \times \verb|nPatch2| \times1$ array
of the spatial locations~$y_{jJ}$ of the microscale grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on the microscale index~$j$, but may be
variable spaced in macroscale index~$J$.
\item \verb|.z| is similarly $1 \times1 \times \verb|nSubP3|
\times1 \times1 \times1 \times1 \times \verb|nPatch3|$ array
of the spatial locations~$z_{kK}$ of the microscale grid
points in every patch. Currently it \emph{must} be an
equi-spaced lattice on the microscale index~$k$, but may be
variable spaced in macroscale index~$K$.
\item \verb|.ordCC| is order of interpolation, currently
only $\{0,2,4,\ldots\}$
\item \verb|.periodic| indicates whether macroscale is
periodic domain, or alternatively that the macroscale has
left, right, top, bottom, front and back boundaries so
interpolation is via divided differences.
\item \verb|.stag| in $\{0,1\}$ is one for staggered grid
(alternating) interpolation. Currently must be zero.
\item \verb|.Cwtsr| and \verb|.Cwtsl| are the coupling
coefficients for finite width interpolation in each of the
$x,y,z$-directions---when invoking a periodic domain.
\item \verb|.EdgyInt|, true/false, for determining
patch-edge values by interpolation: true, from opposite-edge
next-to-edge values (often preserves symmetry); false, from
centre cross-patch values (near original scheme).
\item \verb|.nEdge|, three elements, the width of edge
values set by interpolation at the \(x,y,z\)-face regions,
respectively, of each patch (default is one all
\(x,y,z\)-faces).
\item \verb|.nEnsem| the number of realisations in the
ensemble.
\item \verb|.parallel| whether serial or parallel.
\end{itemize}
\end{itemize}
\paragraph{Output}
\begin{itemize}
\item \verb|u| is 8D array, $\verb|nSubP1| \cdot
\verb|nSubP2| \cdot \verb|nSubP3| \cdot \verb|nVars| \cdot
\verb|nEnsem| \cdot \verb|nPatch1| \cdot \verb|nPatch2|
\cdot \verb|nPatch3|$, of the fields with face values set by
interpolation.
\end{itemize}
\begin{devMan}
Test for reality of the field values, and define a function
accordingly. Could be problematic if some variables are
real and some are complex, or if variables are of quite
different sizes.
\begin{matlab}
%}
if max(abs(imag(u(:))))<1e-9*max(abs(u(:)))
uclean=@(u) real(u);
else uclean=@(u) u;
end
%{
\end{matlab}
Determine the sizes of things. Any error arising in the
reshape indicates~\verb|u| has the wrong size.
\begin{matlab}
%}
[~,~,nz,~,~,~,~,Nz] = size(patches.z);
[~,ny,~,~,~,~,Ny,~] = size(patches.y);
[nx,~,~,~,~,Nx,~,~] = size(patches.x);
nEnsem = patches.nEnsem;
nVars = round( numel(u)/numel(patches.x) ...
/numel(patches.y)/numel(patches.z)/nEnsem );
assert(numel(u) == nx*ny*nz*Nx*Ny*Nz*nVars*nEnsem ...
,'patchEdgeInt3: input u has wrong size for parameters')
u = reshape(u,[nx ny nz nVars nEnsem Nx Ny Nz]);
%{
\end{matlab}
For the moment assume the physical domain is either
macroscale periodic or macroscale rectangle so that the
coupling formulas are simplest. These index vectors point
to patches and, if periodic, their six immediate neighbours.
\begin{matlab}
%}
I=1:Nx; Ip=mod(I,Nx)+1; Im=mod(I-2,Nx)+1;
J=1:Ny; Jp=mod(J,Ny)+1; Jm=mod(J-2,Ny)+1;
K=1:Nz; Kp=mod(K,Nz)+1; Km=mod(K-2,Nz)+1;
%{
\end{matlab}
\paragraph{Implement multiple width edges by folding}
Subsample~\(x,y,z\) coordinates, noting it is only differences
that count \emph{and} the microgrid~\(x,y,z\) spacing must be
uniform.
\begin{matlab}
%}
%x = patches.x;
%if patches.nEdge(1)>1
% m = patches.nEdge(1);
% x = x(1:m:nx,:,:,:,:,:,:,:);
% nx = nx/m;
% u = reshape(u,m,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
% nVars = nVars*m;
% u = reshape( permute(u,[2:4 1 5:9]) ...
% ,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
%end%if patches.nEdge(1)
%y = patches.y;
%if patches.nEdge(2)>1
% m = patches.nEdge(2);
% y = y(:,1:m:ny,:,:,:,:,:,:);
% ny = ny/m;
% u = reshape(u,nx,m,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
% nVars = nVars*m;
% u = reshape( permute(u,[1 3:4 2 5:9]) ...
% ,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
%end%if patches.nEdge(2)
%z = patches.z;
%if patches.nEdge(3)>1
% m = patches.nEdge(3);
% z = z(:,:,1:m:nz,:,:,:,:,:);
% nz = nz/m;
% u = reshape(u,nx,ny,m,nz,nVars,nEnsem,Nx,Ny,Nz);
% nVars = nVars*m;
% u = reshape( permute(u,[1:2 4 3 5:9]) ...
% ,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
%end%if patches.nEdge(3)
x = patches.x;
y = patches.y;
z = patches.z;
if mean(patches.nEdge)>1
mx = patches.nEdge(1);
my = patches.nEdge(2);
mz = patches.nEdge(3);
x = x(1:mx:nx,:,:,:,:,:,:,:);
y = y(:,1:my:ny,:,:,:,:,:,:);
z = z(:,:,1:mz:nz,:,:,:,:,:);
nx = nx/mx;
ny = ny/my;
nz = nz/mz;
u = reshape(u,mx,nx,my,ny,mz,nz,nVars,nEnsem,Nx,Ny,Nz);
nVars = nVars*mx*my*mz;
u = reshape( permute(u,[2:2:6 1:2:5 7:11]) ...
,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
end%if patches.nEdge
%{
\end{matlab}
The centre of each patch (as \verb|nx|, \verb|ny| and
\verb|nz| are odd for centre-patch interpolation) is at
indices
\begin{matlab}
%}
i0 = round((nx+1)/2);
j0 = round((ny+1)/2);
k0 = round((nz+1)/2);
%{
\end{matlab}
\subsection{Periodic macroscale interpolation schemes}
\begin{matlab}
%}
if patches.periodic
%{
\end{matlab}
Get the size ratios of the patches in each direction.
\begin{matlab}
%}
rx = patches.ratio(1);
ry = patches.ratio(2);
rz = patches.ratio(3);
%{
\end{matlab}
\subsubsection{Lagrange interpolation gives patch-face values}
Compute centred differences of the mid-patch values for the
macro-interpolation, of all fields. Here the domain is
macro-periodic.
\begin{matlab}
%}
ordCC = patches.ordCC;
if ordCC>0 % then finite-width polynomial interpolation
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in face-edge and corner values. Start with
\(x\)-direction, and give most documentation for that case
as the others are essentially the same.
\paragraph{\(x\)-normal face values} The patch-edge values
are either interpolated from the next-to-edge-face values,
or from the centre-cross-plane values (not the patch-centre
value itself as that seems to have worse properties in
general). Have not yet implemented core averages.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u([2 nx-1],2:(ny-1),2:(nz-1),:,:,I,J,K);
else % interpolate centre-cross values
U = u(i0,2:(ny-1),2:(nz-1),:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Just in case any last array dimension(s) are one, we force a
padding of the sizes, then adjoin the extra dimension for
the subsequent array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Use finite difference formulas for the interpolation, so
store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in these arrays. When parallel, in order
to preserve the distributed array structure we use an index
at the end for the differences.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
% dmux(:,:,:,:,:,I,:,:,1) = (Ux(:,:,:,:,:,Ip,:,:) +Ux(:,:,:,:,:,Im,:,:))/2; % \mu
% dmux(:,:,:,:,:,I,:,:,2) = (Ux(:,:,:,:,:,Ip,:,:) -Ux(:,:,:,:,:,Im,:,:)); % \delta
% Ip = Ip(Ip); Im = Im(Im); % increase shifts to \pm2
% dmuy(:,:,:,:,:,:,J,:,1) = (Ux(:,:,:,:,:,:,Jp,:)+Ux(:,:,:,:,:,:,Jm,:))/2; % \mu
% dmuy(:,:,:,:,:,:,J,:,2) = (Ux(:,:,:,:,:,:,Jp,:)-Ux(:,:,:,:,:,:,Jm,:)); % \delta
% Jp = Jp(Jp); Jm = Jm(Jm); % increase shifts to \pm2
% dmuz(:,:,:,:,:,:,:,K,1) = (Ux(:,:,:,:,:,:,:,Kp)+Ux(:,:,:,:,:,:,:,Km))/2; % \mu
% dmuz(:,:,:,:,:,:,:,K,2) = (Ux(:,:,:,:,:,:,:,Kp)-Ux(:,:,:,:,:,:,:,Km)); % \delta
% Kp = Kp(Kp); Km = Km(Km); % increase shifts to \pm2
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,I,:,:,1) = (U(:,:,:,:,:,Ip,:,:) ...
-U(:,:,:,:,:,Im,:,:))/2; %\mu\delta
dmu(:,:,:,:,:,I,:,:,2) = (U(:,:,:,:,:,Ip,:,:) ...
-2*U(:,:,:,:,:,I,:,:) +U(:,:,:,:,:,Im,:,:)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$ of these to form successively
higher order centred differences in space.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,I,:,:,k) = dmu(:,:,:,:,:,Ip,:,:,k-2) ...
-2*dmu(:,:,:,:,:,I,:,:,k-2) +dmu(:,:,:,:,:,Im,:,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values to be Dirichlet face values for
each patch \cite[]{Roberts06d, Bunder2013b}, using the weights
pre-computed by \verb|configPatches3()|. Here interpolate to
specified order.
For the case where next-to-face values interpolate to the
opposite face-values: when we have an ensemble of
configurations, different configurations might be coupled to
each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to|, \verb|patches.bo|,
\verb|patches.fr| and \verb|patches.ba|.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(nx,2:(ny-1),2:(nz-1),:,patches.ri,I,:,:) ...
= U(1,:,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,1),-8).*dmu(1,:,:,:,:,:,:,:,:) ,9);
u(1 ,2:(ny-1),2:(nz-1),:,patches.le,I,:,:) ...
= U(k,:,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,1),-8).*dmu(k,:,:,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\paragraph{\(y\)-normal face values} Interpolate from either
the next-to-edge-face values, or the centre-cross-plane
values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,[2 ny-1],2:(nz-1),:,:,I,J,K);
else % interpolate centre-cross values
U = u(:,j0,2:(nz-1),:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,:,J,:,1) = (U(:,:,:,:,:,:,Jp,:) ...
-U(:,:,:,:,:,:,Jm,:))/2; %\mu\delta
dmu(:,:,:,:,:,:,J,:,2) = (U(:,:,:,:,:,:,Jp,:) ...
-2*U(:,:,:,:,:,:,J,:) +U(:,:,:,:,:,:,Jm,:)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,:,J,:,k) = dmu(:,:,:,:,:,:,Jp,:,k-2) ...
-2*dmu(:,:,:,:,:,:,J,:,k-2) +dmu(:,:,:,:,:,:,Jm,:,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches3()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(:,ny,2:(nz-1),:,patches.to,:,J,:) ...
= U(:,1,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,2),-8).*dmu(:,1,:,:,:,:,:,:,:) ,9);
u(:,1 ,2:(nz-1),:,patches.bo,:,J,:) ...
= U(:,k,:,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,2),-8).*dmu(:,k,:,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\paragraph{\(z\)-normal face values} Interpolate from either
the next-to-edge-face values, or the centre-cross-plane
values.
\begin{matlab}
%}
if patches.EdgyInt % interpolate next-to-face values
U = u(:,:,[2 nz-1],:,:,I,J,K);
else % interpolate centre-cross values
U = u(:,:,k0,:,:,I,J,K);
end;%if patches.EdgyInt
%{
\end{matlab}
Adjoin extra dimension for the array of differences.
\begin{matlab}
%}
szUO=size(U); szUO=[szUO ones(1,8-length(szUO)) ordCC];
%{
\end{matlab}
Store finite differences ($\mu\delta, \delta^2, \mu\delta^3,
\delta^4, \ldots$) in this array.
\begin{matlab}
%}
if ~patches.parallel, dmu = zeros(szUO); % 9D
else dmu = zeros(szUO,patches.codist); % 9D
end%if patches.parallel
%{
\end{matlab}
First compute differences $\mu\delta$ and $\delta^2$.
\begin{matlab}
%}
if patches.stag % use only odd numbered neighbours
error('polynomial interpolation not yet for staggered patch coupling')
else %disp('starting standard interpolation')
dmu(:,:,:,:,:,:,:,K,1) = (U(:,:,:,:,:,:,:,Kp) ...
-U(:,:,:,:,:,:,:,Km))/2; %\mu\delta
dmu(:,:,:,:,:,:,:,K,2) = (U(:,:,:,:,:,:,:,Kp) ...
-2*U(:,:,:,:,:,:,:,K) +U(:,:,:,:,:,:,:,Km)); %\delta^2
end% if stag
%{
\end{matlab}
Recursively take $\delta^2$.
\begin{matlab}
%}
for k = 3:ordCC
dmu(:,:,:,:,:,:,:,K,k) = dmu(:,:,:,:,:,:,:,Kp,k-2) ...
-2*dmu(:,:,:,:,:,:,:,K,k-2) +dmu(:,:,:,:,:,:,:,Km,k-2);
end
%{
\end{matlab}
Interpolate macro-values using the weights pre-computed by
\verb|configPatches3()|. An ensemble of configurations may
have cross-coupling.
\begin{matlab}
%}
k=1+patches.EdgyInt; % use centre or two faces
u(:,:,nz,:,patches.fr,:,:,K) ...
= U(:,:,1,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsr(:,3),-8).*dmu(:,:,1,:,:,:,:,:,:) ,9);
u(:,:,1 ,:,patches.ba,:,:,K) ...
= U(:,:,k,:,:,:,:,:)*(1-patches.stag) ...
+sum( shiftdim(patches.Cwtsl(:,3),-8).*dmu(:,:,k,:,:,:,:,:,:) ,9);
%{
\end{matlab}
\subsubsection{Case of spectral interpolation}
Assumes the domain is macro-periodic.
\begin{matlab}
%}
else% patches.ordCC<=0, spectral interpolation
%{
\end{matlab}
We interpolate in terms of the patch index, $I$~say, not
directly in space. As the macroscale fields are $N$-periodic
in the patch index~$I$, the macroscale Fourier transform
writes the centre-patch values as $U_I=\sum_{k}C_ke^{ik2\pi
I/N}$. Then the face-patch values $U_{I\pm r}
=\sum_{k}C_ke^{ik2\pi/N(I\pm r)} =\sum_{k}C'_ke^{ik2\pi
I/N}$ where $C'_k =C_ke^{ikr2\pi/N}$. For $N$~patches we
resolve `wavenumbers' $|k|<N/2$, so set row vector
$\verb|ks| =k2\pi/N$ for `wavenumbers' $\mathcode`\,="213B
k=(0,1, \ldots, k_{\max}, -k_{\max}, \ldots, -1)$ for
odd~$N$, and $\mathcode`\,="213B k=(0,1, \ldots, k_{\max},
\pm(k_{\max}+1) -k_{\max}, \ldots, -1)$ for even~$N$.
Deal with staggered grid by doubling the number of fields
and halving the number of patches (\verb|configPatches3|
tests there are an even number of patches). Then the
patch-ratio is effectively halved. The patch faces are near
the middle of the gaps and swapped.
\begin{matlab}
%}
if patches.stag % transform by doubling the number of fields
error('staggered grid not yet implemented??')
v=nan(size(u)); % currently to restore the shape of u
u=cat(3,u(:,1:2:nPatch,:),u(:,2:2:nPatch,:));
stagShift=reshape(0.5*[ones(nVars,1);-ones(nVars,1)],1,1,[]);
iV=[nVars+1:2*nVars 1:nVars]; % scatter interp to alternate field
r=r/2; % ratio effectively halved
nPatch=nPatch/2; % halve the number of patches
nVars=nVars*2; % double the number of fields
else % the values for standard spectral
stagShift = 0;
iV = 1:nVars;
end%if patches.stag
%{
\end{matlab}
Interpolate the three directions in succession, in this way
we naturally fill-in face-edge and corner values. Start with
\(x\)-direction, and give most documentation for that case
as the others are essentially the same. Need these indices
of patch interior.
\begin{matlab}
%}
ix = 2:nx-1; iy = 2:ny-1; iz = 2:nz-1;
%{
\end{matlab}
\paragraph{\(x\)-normal face values} Now set wavenumbers
into a vector at the correct dimension. In the case of
even~$N$ these compute the $+$-case for the highest
wavenumber zig-zag mode, $\mathcode`\,="213B k=(0,1, \ldots,
k_{\max}, +(k_{\max}+1) -k_{\max}, \ldots, -1)$.
\begin{matlab}
%}
kMax = floor((Nx-1)/2);
kr = shiftdim( rx*2*pi/Nx*(mod((0:Nx-1)+kMax,Nx)-kMax) ,-4);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields. Unless doing patch-edgy
interpolation when FT the next-to-face values. If there are
an even number of points, then if complex, treat as positive
wavenumber, but if real, treat as cosine. When using an
ensemble of configurations, different configurations might
be coupled to each other, as specified by \verb|patches.le|,
\verb|patches.ri|, \verb|patches.to|, \verb|patches.bo|,
\verb|patches.fr| and \verb|patches.ba|.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(i0,iy,iz,:,:,:,:,:) ,[],6);
Cp = Cm;
else
Cm = fft( u( 2,iy,iz ,:,patches.le,:,:,:) ,[],6);
Cp = fft( u(nx-1,iy,iz ,:,patches.ri,:,:,:) ,[],6);
end%if ~patches.EdgyInt
%{
\end{matlab}
Now invert the Fourier transforms to complete interpolation.
Enforce reality when appropriate.
\begin{matlab}
%}
u(nx,iy,iz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],6) );
u( 1,iy,iz,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],6) );
%{
\end{matlab}
\paragraph{\(y\)-normal face values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Ny-1)/2);
kr = shiftdim( ry*2*pi/Ny*(mod((0:Ny-1)+kMax,Ny)-kMax) ,-5);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,j0,iz,:,:,:,:,:) ,[],7);
Cp = Cm;
else
Cm = fft( u(:,2 ,iz ,:,patches.bo,:,:,:) ,[],7);
Cp = fft( u(:,ny-1,iz ,:,patches.to,:,:,:) ,[],7);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,ny,iz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],7) );
u(:, 1,iz,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],7) );
%{
\end{matlab}
\paragraph{\(z\)-normal face values} Set wavenumbers into a
vector.
\begin{matlab}
%}
kMax = floor((Nz-1)/2);
kr = shiftdim( rz*2*pi/Nz*(mod((0:Nz-1)+kMax,Nz)-kMax) ,-6);
%{
\end{matlab}
Compute the Fourier transform of the patch values on the
centre-planes for all the fields.
\begin{matlab}
%}
if ~patches.EdgyInt
Cm = fft( u(:,:,k0,:,:,:,:,:) ,[],8);
Cp = Cm;
else
Cm = fft( u(:,:,2 ,:,patches.ba,:,:,:) ,[],8);
Cp = fft( u(:,:,nz-1 ,:,patches.fr,:,:,:) ,[],8);
end%if ~patches.EdgyInt
%{
\end{matlab}
Invert the Fourier transforms to complete interpolation.
\begin{matlab}
%}
u(:,:,nz,:,:,:,:,:) = uclean( ifft( ...
Cm.*exp(1i*(stagShift+kr)) ,[],8) );
u(:,:, 1,:,:,:,:,:) = uclean( ifft( ...
Cp.*exp(1i*(stagShift-kr)) ,[],8) );
%{
\end{matlab}
\begin{matlab}
%}
end% if ordCC>0
%{
\end{matlab}
\subsection{Non-periodic macroscale interpolation}
\begin{matlab}
%}
else% patches.periodic false
assert(~patches.stag, ...
'not yet implemented staggered grids for non-periodic')
%{
\end{matlab}
Determine the order of interpolation~\verb|px|, \verb|py|
and~\verb|pz| (potentially different in the different
directions!), and hence size of the (forward) divided
difference tables in~\verb|F|~(9D) for interpolating to
left/right, top/bottom, and front/back faces. Because of the
product-form of the patch grid, and because we are doing
\emph{only} either edgy interpolation or cross-patch
interpolation (\emph{not} just the centre patch value), the
interpolations are all 1D interpolations.
\begin{matlab}
%}
if patches.ordCC<1
px = Nx-1; py = Ny-1; pz = Nz-1;
else px = min(patches.ordCC,Nx-1);
py = min(patches.ordCC,Ny-1);
pz = min(patches.ordCC,Nz-1);
end
% interior indices of faces (ix n/a)
ix=2:nx-1; iy=2:ny-1; iz=2:nz-1;
%{
\end{matlab}
\subsubsection{\(x\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble. For~\verb|EdgyInt|, the
`reversal' of the next-to-face values are because their
values are to interpolate to the opposite face of each
patch. \todo{Have no plans to implement core averaging as yet.}
\begin{matlab}
%}
F = nan(patches.EdgyInt+1,ny-2,nz-2,nVars,nEnsem,Nx,Ny,Nz,px+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u([nx-1 2],iy,iz,:,:,:,:,:);
X = x([nx-1 2],:,:,:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(i0,iy,iz,:,:,:,:,:);
X = x(i0,:,:,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
\paragraph{Form tables of divided differences} Compute
tables of (forward) divided differences
\cite[e.g.,][]{DividedDifferences} for every variable, and
across ensemble, and in both directions, and for all three
types of faces (left/right, top/bottom, and front/back).
Recursively find all divided differences in the respective
direction.
\begin{matlab}
%}
for q = 1:px
i = 1:Nx-q;
F(:,:,:,:,:,i,:,:,q+1) ...
= ( F(:,:,:,:,:,i+1,:,:,q)-F(:,:,:,:,:,i,:,:,q)) ...
./(X(:,:,:,:,:,i+q,:,:) -X(:,:,:,:,:,i,:,:));
end
%{
\end{matlab}
\paragraph{Interpolate with divided differences} Now
interpolate to find the face-values on left/right faces
at~\verb|Xface| for every interior~\verb|Y,Z|.
\begin{matlab}
%}
Xface = x([1 nx],:,:,:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|i| are those of the left face of
each interpolation stencil, because the table is of forward
differences. This alternative: the case of order~\(p_x\),
\(p_y\) and~\(p_z\) interpolation across the domain,
asymmetric near the boundaries of the rectangular domain.
\begin{matlab}
%}
i = max(1,min(1:Nx,Nx-ceil(px/2))-floor(px/2));
Uface = F(:,:,:,:,:,i,:,:,px+1);
for q = px:-1:1
Uface = F(:,:,:,:,:,i,:,:,q) ...
+(Xface-X(:,:,:,:,:,i+q-1,:,:)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(1 ,iy,iz,:,patches.le,:,:,:) = Uface(1,:,:,:,:,:,:,:);
u(nx,iy,iz,:,patches.ri,:,:,:) = Uface(2,:,:,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(y\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,patches.EdgyInt+1,nz-2,nVars,nEnsem,Nx,Ny,Nz,py+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u(:,[ny-1 2],iz,:,:,:,:,:);
Y = y(:,[ny-1 2],:,:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(:,j0,iz,:,:,:,:,:);
Y = y(:,j0,:,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:py
j = 1:Ny-q;
F(:,:,:,:,:,:,j,:,q+1) ...
= ( F(:,:,:,:,:,:,j+1,:,q)-F(:,:,:,:,:,:,j,:,q)) ...
./(Y(:,:,:,:,:,:,j+q,:) -Y(:,:,:,:,:,:,j,:));
end
%{
\end{matlab}
Interpolate to find the top/bottom faces~\verb|Yface| for
every~\(x\) and interior~\(z\).
\begin{matlab}
%}
Yface = y(:,[1 ny],:,:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|j| are those of the bottom face
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
j = max(1,min(1:Ny,Ny-ceil(py/2))-floor(py/2));
Uface = F(:,:,:,:,:,:,j,:,py+1);
for q = py:-1:1
Uface = F(:,:,:,:,:,:,j,:,q) ...
+(Yface-Y(:,:,:,:,:,:,j+q-1,:)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,1 ,iz,:,patches.bo,:,:,:) = Uface(:,1,:,:,:,:,:,:);
u(:,ny,iz,:,patches.to,:,:,:) = Uface(:,2,:,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{\(z\)-direction values}
Set function values in first `column' of the tables for
every variable and across ensemble.
\begin{matlab}
%}
F = nan(nx,ny,patches.EdgyInt+1,nVars,nEnsem,Nx,Ny,Nz,pz+1);
if patches.EdgyInt % interpolate next-to-face values
F(:,:,:,:,:,:,:,:,1) = u(:,:,[nz-1 2],:,:,:,:,:);
Z = z(:,:,[nz-1 2],:,:,:,:,:);
else % interpolate mid-patch cross-patch values
F(:,:,:,:,:,:,:,:,1) = u(:,:,k0,:,:,:,:,:);
Z = z(:,:,k0,:,:,:,:,:);
end%if patches.EdgyInt
%{
\end{matlab}
Form tables of divided differences.
\begin{matlab}
%}
for q = 1:pz
k = 1:Nz-q;
F(:,:,:,:,:,:,:,k,q+1) ...
= ( F(:,:,:,:,:,:,:,k+1,q)-F(:,:,:,:,:,:,:,k,q)) ...
./(Z(:,:,:,:,:,:,:,k+q) -Z(:,:,:,:,:,:,:,k));
end
%{
\end{matlab}
Interpolate to find the face-values on front/back
faces~\verb|Zface| for every~\(x,y\).
\begin{matlab}
%}
Zface = z(:,:,[1 nz],:,:,:,:,:);
%{
\end{matlab}
Code Horner's recursive evaluation of the interpolation
polynomials. Indices~\verb|k| are those of the bottom face
of each interpolation stencil, because the table is of
forward differences.
\begin{matlab}
%}
k = max(1,min(1:Nz,Nz-ceil(pz/2))-floor(pz/2));
Uface = F(:,:,:,:,:,:,:,k,pz+1);
for q = pz:-1:1
Uface = F(:,:,:,:,:,:,:,k,q) ...
+(Zface-Z(:,:,:,:,:,:,:,k+q-1)).*Uface;
end
%{
\end{matlab}
Finally, insert face values into the array of field values,
using the required ensemble shifts.
\begin{matlab}
%}
u(:,:,1 ,:,patches.fr,:,:,:) = Uface(:,:,1,:,:,:,:,:);
u(:,:,nz,:,patches.ba,:,:,:) = Uface(:,:,2,:,:,:,:,:);
%{
\end{matlab}
\subsubsection{Optional NaNs for safety}
We want a user to set outer face values on the extreme
patches according to the microscale boundary conditions that
hold at the extremes of the domain. Consequently, unless testing, override
their computed interpolation values with~\verb|NaN|.
\begin{matlab}
%}
if isfield(patches,'intTest')&&patches.intTest
else % usual case
u( 1,:,:,:,:, 1,:,:) = nan;
u(nx,:,:,:,:,Nx,:,:) = nan;
u(:, 1,:,:,:,:, 1,:) = nan;
u(:,ny,:,:,:,:,Ny,:) = nan;
u(:,:, 1,:,:,:,:, 1) = nan;
u(:,:,nz,:,:,:,:,Nz) = nan;
end%if
%{
\end{matlab}
End of the non-periodic interpolation code.
\begin{matlab}
%}
end%if patches.periodic else
%{
\end{matlab}
\paragraph{Unfold multiple edges} No need to restore~\(x,y,z\).
\begin{matlab}
%}
if mean(patches.nEdge)>1
nVars = nVars/(mx*my*mz);
u = reshape( u ,nx,ny,nz,mx,my,mz,nVars,nEnsem,Nx,Ny,Nz);
nx = nx*mx;
ny = ny*my;
nz = nz*mz;
u = reshape( permute(u,[4 1 5 2 6 3 7:11]) ...
,nx,ny,nz,nVars,nEnsem,Nx,Ny,Nz);
end%if patches.nEdge
%{
\end{matlab}
Fin, returning the 8D array of field values with
interpolated faces.
\begin{matlab}
%}
end% function patchEdgeInt3
%{
\end{matlab}
\end{devMan}
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
homoDiff31spmd.m
|
.m
|
EquationFreeGit-master/Patch/homoDiff31spmd.m
| 10,046 |
utf_8
|
893ea075ff595700254aece837a89c03
|
% homoDiff31spmd simulates heterogeneous diffusion in 1D
% space on 3D patches as a Proof of Principle example of
% parallel computing with spmd. The interest here is on
% using spmd and comparing it with code not using spmd. The
% discussion here only addresses issues with spmd and
% parallel computing. For discussion on the 3D patch scheme
% with heterogeneous diffusion, see code and documentation
% for homoDiffEdgy3. AJR, Aug--Dec 2020
%!TEX root = ../Doc/eqnFreeDevMan.tex
%{
\section{\texttt{homoDiff31spmd}: computational
homogenisation of a 1D dispersion via parallel simulation on
small 3D patches of heterogeneous diffusion}
\label{sec:homoDiff31spmd}
\localtableofcontents
Simulate effective dispersion along 1D space on 3D patches
of heterogeneous diffusion as a Proof of Principle example
of parallel computing with \verb|spmd|. With only one patch
in each of the $y,z$-directions, the solution simulated is
strictly periodic in~$y,z$ with period~\verb|ratio|: there
are only macro-scale variations in the $x$-direction. The
discussion here only addresses issues with \verb|spmd|
parallel computing. For discussion on the 3D patch scheme
with heterogeneous diffusion, see code and documentation for
\verb|homoDiffEdgy3| in \cref{sec:homoDiffEdgy3}.
Choose one of four cases:
\begin{itemize}
\item \verb|theCase=1| is corresponding code without
parallelisation (in this toy problem it is much the quickest
because there is no expensive communication);
\item \verb|theCase=2| for minimising coding by a user of
\verb|spmd|-blocks;
\item \verb|theCase=3| is for users happier to explicitly
invoke \verb|spmd|-blocks.
\item \verb|theCase=4| invokes projective integration for
long-time simulation via short bursts of the
micro-computation, bursts done within \verb|spmd|-blocks for
parallel computing.
\end{itemize}
First, clear all to remove any existing globals, old
composites, etc---although a parallel pool persists.
Then choose the case.
\begin{matlab}
%}
clear all
theCase = 1
%{
\end{matlab}
Set micro-scale heterogeneity with various spatial periods
in the three directions.
\begin{matlab}
%}
mPeriod = [4 3 2] %1+randperm(3)
cHetr = exp(0.3*randn([mPeriod 3]));
cHetr = cHetr*mean(1./cHetr(:))
%{
\end{matlab}
Configure the patch scheme with some arbitrary choices of
domain, patches, size ratios---here each patch is a unit
cube in space. Choose some random order of interpolation.
Set \verb|patches| information to be global so the info can
be used for Case~1 without being explicitly passed as
arguments. Choose the parallel option if not Case~1, which
invokes \verb|spmd|-block internally, so that field
variables become \emph{distributed} across cpus.
\begin{matlab}
%}
if any(theCase==[1 2]), global patches, end
nSubP=mPeriod+2
nPatch=[9 1 1]
ratio=0.3
Len=nPatch(1)/ratio
ordCC=2*randi([0 3])
disp('**** Setting configPatches3')
patches = configPatches3(@heteroDiff3,[0 Len 0 1 0 1], nan ...
, nPatch, ordCC, [ratio 1 1], nSubP, 'EdgyInt',true ...
,'hetCoeffs',cHetr ,'parallel',(theCase>1) );
%{
\end{matlab}
\subsection{Simulate heterogeneous diffusion}
Set initial conditions of a simulation as shown in
\cref{fig:homoDiff31spmdt0}.
\begin{matlab}
%}
disp('**** Set initial condition and testing du0dt =')
if theCase==1
%{
\end{matlab}
Without parallel processing, invoke the usual operations.
\begin{matlab}
%}
u0 = exp( -(patches.x-Len/2).^2/Len ...
-patches.y.^2/2-patches.z.^2 );
u0 = u0.*(1+0.2*rand(size(u0)));
du0dt = patchSys3(0,u0);
%{
\end{matlab}
With parallel, must use an \verb|spmd|-block for
computations: there is no difference in cases~2--4 here.
Also, we must sometimes explicitly code how to distribute
some new arrays over the cpus. Now \verb|patchSys3| does
not invoke \verb|spmd| so higher level code must, as here.
Even if \verb|patches| is global, inside \verb|spmd|-block
we must pass it explicitly as a parameter to
\verb|patchSys3|.
\begin{matlab}
%}
else, spmd
u0 = exp( -(patches.x-Len/2).^2/Len ...
-patches.y.^2/2-patches.z.^2/4 );
u0 = u0.*(1+0.2*rand(size(u0),patches.codist));
du0dt = patchSys3(0,u0,patches);
end%spmd
end%if theCase
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:homoDiff31spmdt0}initial
field~$u(x,y,z,0)$ of the patch scheme applied to a
heterogeneous diffusion~\pde. The vertical spread indicates
the extent of the structure in~$u$ in the cross-section
variables~$y,z$. \cref{fig:homoDiff31spmdtFin}
plots the nearly smooth field values at time $t=0.4$. }
\includegraphics[scale=0.8]{homoDiff31spmdt0}
\end{figure}
Integrate in time. Use non-uniform time-steps for
fun, and to show more of the initial rapid transients.
Alternatively, use \verb|RK2mesoPatch| which reduces
communication between patches, recalling that, by default,
\verb|RK2mesoPatch| does ten micro-steps for each specified
step in~\verb|ts|. For unit cube patches, need micro-steps
less than about~$0.004$ for stability.
\begin{matlab}
%}
warning('Integrating system in time, wait patiently')
ts=0.4*linspace(0,1,21).^2;
%{
\end{matlab}
Go to the selected case.
\begin{matlab}
%}
switch theCase
%{
\end{matlab}
\begin{enumerate}
\item For non-parallel, we could use \verb|RK2mesoPatch| as
indicated below, but instead choose to use standard
\verb|ode23| as here \verb|patchSys3| accesses patch
information via global \verb|patches|. For post-processing,
reshape each and every row of the computed solution to the
correct array size---that of the initial condition.
\begin{matlab}
%}
case 1
% [us,uerrs] = RK2mesoPatch(ts,u0);
[ts,us] = ode23(@patchSys3,ts,u0(:));
us=reshape(us,[length(ts) size(u0)]);
%{
\end{matlab}
\item In the second case, \verb|RK2mesoPatch| detects a
parallel patch code has been requested, but has only one cpu
worker, so it auto-initiates an \verb|spmd|-block for the
integration. Both this and the next case return
\emph{composite} results, so just keep one version of the
results.
\begin{matlab}
%}
case 2
us = RK2mesoPatch(ts,u0);
us = us{1};
%{
\end{matlab}
\item In this third case, a user could merge this explicit
\verb|spmd|-block with the previous one that sets the
initial conditions.
\begin{matlab}
%}
case 3,spmd
us = RK2mesoPatch(ts,u0,[],patches);
end%spmd
us = us{1};
%{
\end{matlab}
\item In this fourth case, use Projective Integration (PI)
over long times (\verb|PIRK4| also works). Currently the PI
is done serially, with parallel \verb|spmd|-blocks only
invoked inside function \verb|aBurst()| (\cref{secmBfPI}) to
compute each burst of the micro-scale simulation. A
macro-scale time-step of about~$3$ seems good to resolve the
decay of the macro-scale `homogenised' diffusion.
\footnote{Curiously, \texttt{PIG()} appears to suffer
unrecoverable instabilities with its variable step size!}
The function \verb|microBurst()| here interfaces to
\verb|aBurst()| (\cref{secmBfPI}) in order to provide shaped
initial states, and to provide the patch information.
\begin{matlab}
%}
case 4
microBurst = @(tb0,xb0,bT) ...
aBurst(tb0 ,reshape(xb0,size(u0)) ,patches);
ts = 0:3:51
us = PIRK2(microBurst,ts,gather(u0(:)));
us = reshape(us,[length(ts) size(u0)]);
%{
\end{matlab}
\end{enumerate}
End the four cases.
\begin{matlab}
%}
end%switch theCase
%{
\end{matlab}
\subsection{Plot the solution}
Optionally save some plots to file.
\begin{matlab}
%}
if 0, global OurCf2eps, OurCf2eps=true, end
%{
\end{matlab}
Animate the solution field over time. Since the spatial
domain is long in~$x$ and thin in~$y,z$, just plot field
values as a function of~$x$.
\begin{matlab}
%}
figure(1), clf
if theCase==1
x = reshape( patches.x(2:end-1,:,:,:) ,[],1);
else, spmd
x = reshape(gather( patches.x(2:end-1,:,:,:) ),[],1);
end%spmd
x = x{1};
end
%{
\end{matlab}
For every time step draw the field values as dots and pause
for a short display.
\begin{matlab}
%}
nTimes = length(ts)
for l = 1:length(ts)
%{
\end{matlab}
At each time, squeeze interior point data into a 4D array,
permute to get all the $x$-variation in the first two
dimensions, and reshape into $x$-variation for each and
every~$(y,z)$.
\begin{matlab}
%}
u = reshape( permute( squeeze( ...
us(l,2:end-1,2:end-1,2:end-1,:) ) ,[1 4 2 3]) ,numel(x),[]);
%{
\end{matlab}
Draw point data to show spread at each cross-section, as
well as macro-scale variation in the long space direction.
\begin{matlab}
%}
if l==1
hp = plot(x,u,'.');
axis([0 Len 0 max(u(:))])
xlabel('space $x$'), ylabel('$u(x,y,z,t)$')
ifOurCf2eps([mfilename 't0'])
legend(['time = ' num2str(ts(l),'%4.2f')])
disp('**** pausing, press blank to animate')
pause
else
for p=1:size(u,2), hp(p).YData=u(:,p); end
legend(['time = ' num2str(ts(l),'%4.2f')])
pause(0.1)
end
%{
\end{matlab}
\begin{figure}
\centering \caption{\label{fig:homoDiff31spmdtFin}final
field~$u(x,y,z,0.4)$ of the patch scheme applied to a
heterogeneous diffusion~\pde. }
\includegraphics[scale=0.8]{homoDiff31spmdtFin}
\end{figure}
Finish the animation loop, and optionally output the final
plot, \cref{fig:homoDiff31spmdtFin}.
\begin{matlab}
%}
end%for over time
ifOurCf2eps([mfilename 'tFin'])
%{
\end{matlab}
\subsection{\texttt{microBurst} function for Projective Integration}
\label{secmBfPI}
Projective Integration stability seems to need bursts longer
than~$0.2$. Here take ten meso-steps, each with default ten
micro-steps so the micro-scale step is~$0.002$. With
macro-step~$3$, these parameters usually give stable
projective integration (but not always).
\begin{matlab}
%}
function [tbs,xbs] = aBurst(tb0,xb0,patches)
normx=max(abs(xb0(:)));
disp(['aBurst t = ' num2str(tb0) ' |x| = ' num2str(normx)])
assert(normx<10,'solution exploding')
tbs = tb0+(0:0.02:0.2);
spmd
xb0 = codistributed(xb0,patches.codist);
xbs = RK2mesoPatch(tbs,xb0,[],patches);
end%spmd
xbs=reshape(xbs{1},length(tbs),[]);
end%function
%{
\end{matlab}
%\input{../Patch/heteroDiff3.m}
Fin.
%}
|
github
|
uoa1184615/EquationFreeGit-master
|
simpleWavepde.m
|
.m
|
EquationFreeGit-master/Patch/simpleWavepde.m
| 1,216 |
utf_8
|
67dc4777a37a0c263f408f1bfaf79596
|
% Used by patchEdgeInt1test.m
% AJR, 2018
function Ut=simpleWavepde(t,U,x)
% global patches
dx=x(2)-x(1);
Ut=nan(size(U));
ht=Ut;
%{
\end{matlab}
Compute the PDE derivatives at points internal to the
patches.
\begin{matlab}
%}
i=2:size(U,1)-1;
%{
\end{matlab}
Here `wastefully' compute time derivatives for both \pde{}s
at all grid points---for `simplicity'---and then merges the
staggered results. Since \(\dot h_{ij}
\approx-(u_{i+1,j}-u_{i-1,j})/(2\cdot dx)
=-(U_{i+1,j}-U_{i-1,j})/(2\cdot dx)\) as adding\slash
subtracting one from the index of a \(h\)-value is the
location of the neighbouring \(u\)-value on the staggered
micro-grid.
\begin{matlab}
%}
ht(i,:)=-(U(i+1,:)-U(i-1,:))/(2*dx);
%{
\end{matlab}
Since \(\dot u_{ij} \approx-(h_{i+1,j}-h_{i-1,j})/(2\cdot
dx) =-(U_{i+1,j}-U_{i-1,j})/(2\cdot dx)\) as adding\slash
subtracting one from the index of a \(u\)-value is the
location of the neighbouring \(h\)-value on the staggered
micro-grid.
\begin{matlab}
%}
Ut(i,:)=-(U(i+1,:)-U(i-1,:))/(2*dx);
%{
\end{matlab}
Then overwrite the unwanted~\(\dot u_{ij}\) with the
corresponding wanted~\(\dot h_{ij}\).
\begin{matlab}
%}
% Ut(patches.hPts)=ht(patches.hPts);
Ut(1:2:end) = ht(1:2:end);
Ut([1 end]) = 0;
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.