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
|
dustin-cook/Opensees-master
|
fn_plot_ida.m
|
.m
|
Opensees-master/+ida/fn_plot_ida.m
| 19,458 |
utf_8
|
6b4c3bc0d4f53c391639ac9a92d41014
|
function [ ] = fn_plot_ida(analysis, model, gm_set_table, ida_results, SSF_ew, main_dir)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
%% Initial Setup
% Import packages
import plotting_tools.*
% Defined fixed parames
if analysis.run_z_motion
params = {'b','e','cp'};
else
params = {'b','cp'};
end
% params = {'b','e','b_e','io','ls','cp','euro_th_NC','euro_th_SD','euro_th_DL'};
frag_probs = [10 25 50 75 100];
% Define Directiries
read_dir = [main_dir '/' 'IDA' '/' 'Fragility Data'];
plot_dir = [main_dir '/' 'IDA' '/' 'IDA Plots'];
if ~exist(plot_dir,'dir')
mkdir(plot_dir)
end
% Load data
ida_table = readtable([read_dir filesep 'ida_table.csv']);
gm_table = readtable([read_dir filesep 'gm_table.csv']);
load([read_dir filesep 'frag_curves.mat'])
%% Plot IDA curves
fprintf('Saving IDA Summary Data and Figures to Directory: %s \n',plot_dir)
if analysis.run_z_motion
drs = {'x','z'};
else
drs = {'x'};
end
for d = 1:length(drs)
% Plot IDA curves
hold on
for gms = 1:height(gm_set_table)
ida_plt = plot(ida_table.(['drift_' drs{d}])(strcmp(ida_table.eq_name,gm_set_table.eq_name{gms})),ida_table.(['sa_' drs{d}])(strcmp(ida_table.eq_name,gm_set_table.eq_name{gms})),'-o','color',[0.75 0.75 0.75],'HandleVisibility','off');
end
% plot(frag.mean_idr_ew,frag.p695_sa_ew,'b','lineWidth',1.5,'DisplayName','Mean Drift')
% plot(frag.mean_idr_ew,frag.p_15_sa_ew,'--b','lineWidth',1.5,'DisplayName','15th Percentile')
% plot(frag.mean_idr_ew,frag.p_85_sa_ew,'--b','lineWidth',1.5,'DisplayName','85th Percentile')
plot([0,0.1],[ida_results.spectra(d),ida_results.spectra(d)],'--k','lineWidth',1.5,'DisplayName','ICSB Motion')
xlim([0 0.1])
xlabel('Max Drift')
ylabel(['Sa(T_1=' num2str(ida_results.period(d)) 's) (g)'])
fn_format_and_save_plot( plot_dir, ['IDA Plot ' drs{d} ' Frame Direction'], 3 )
end
%% Component IDA Curves (only for x dir)
% vals2plot = {'gravity_dcr', 'mean_b', 'max_b', 'max_cp', 'lat_cap_ratio_both'};
% for v = 1:length(vals2plot)
% % replace drift
% hold on
% for gms = 1:height(gm_set_table)
% ida_plt = plot(ida_table.(vals2plot{v})(strcmp(ida_table.eq_name,gm_set_table.eq_name{gms})),ida_table.('sa_x')(strcmp(ida_table.eq_name,gm_set_table.eq_name{gms})),'-o','color',[0.75 0.75 0.75],'HandleVisibility','off');
% end
% xlabel(vals2plot{v})
% ylabel(['Sa(T_1=' num2str(ida_results.period(d)) 's) (g)'])
% fn_format_and_save_plot( plot_dir, ['IDA Plot - ' vals2plot{v} ' - 1'], 3 )
%
% % % replace sa
% % hold on
% % for gms = 1:height(gm_set_table)
% % ida_plt = plot(ida_table.('drift_x')(strcmp(ida_table.eq_name,gm_set_table.eq_name{gms})),ida_table.(vals2plot{v})(strcmp(ida_table.eq_name,gm_set_table.eq_name{gms})),'-o','color',[0.75 0.75 0.75],'HandleVisibility','off');
% % end
% % xlabel('Max Drift')
% % ylabel(vals2plot{v})
% % fn_format_and_save_plot( plot_dir, ['IDA Plot - ' vals2plot{v} ' - 2'], 3 )
% end
%% Calculate Post Fragulity Curve P695 factors
if analysis.run_z_motion
factor_3D = 1.11;
else
factor_3D = 1.0;
end
SSF = SSF_ew; % Assume EW SSF
% Set Ida summary table
ida_summary_table.direction = 'EW';
ida_summary_table.period = ida_results.period(1);
ida_summary_table.spectra = ida_results.spectra(1);
ida_summary_table.mce = ida_results.mce(1);
% Collapse Median Sa
ida_summary_table.sa_med_col = frag_curves.collapse.theta;
ida_summary_table.sa_med_UR = frag_curves.UR.theta;
ida_summary_table.sa_med_CP = frag_curves.b.theta(1);
% Collapse Margin Ratio
ida_summary_table.cmr = ida_summary_table.sa_med_col / ida_summary_table.mce;
ida_summary_table.cmr_UR = ida_summary_table.sa_med_UR / ida_summary_table.mce;
ida_summary_table.cmr_CP = ida_summary_table.sa_med_CP / ida_summary_table.mce;
% Adjust for SSF and 3D
ida_summary_table.acmr = factor_3D*SSF*ida_summary_table.cmr;
ida_summary_table.acmr_UR = factor_3D*SSF*ida_summary_table.cmr_UR;
ida_summary_table.acmr_CP = factor_3D*SSF*ida_summary_table.cmr_CP;
median_adjustment = ida_summary_table.sa_med_col*(factor_3D*SSF - 1);
ida_summary_table.p_col_mce = logncdf(ida_summary_table.mce,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
ida_summary_table.p_col_mce_adjust = logncdf(ida_summary_table.mce,log(frag_curves.collapse.theta + median_adjustment),0.6);
ida_summary_table.p_UR_mce = logncdf(ida_summary_table.mce,log(frag_curves.UR.theta),frag_curves.UR.beta);
ida_summary_table.p_UR_mce_adjusted = logncdf(ida_summary_table.mce,log(frag_curves.UR.theta + median_adjustment),0.6);
ida_summary_table.p_CP_mce = logncdf(ida_summary_table.mce,log(frag_curves.b.theta(1)),frag_curves.b.beta(1));
ida_summary_table.p_C_ICSM = logncdf(ida_summary_table.spectra,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% Save IDA results as table
ida_results_table = struct2table(ida_summary_table);
writetable(ida_results_table,[plot_dir filesep 'ida_results.csv'])
%% Plot Frag Curves
% color scheme
matlab_colors = [0 0.4470 0.7410;
0.85 0.325 0.0980;
0.929 0.694 0.1250;
0.494 0.184 0.556;
0.466 0.674 0.188;
0.301 0.7445 0.933;
0.635 0.078 0.184];
matlab_colors = [matlab_colors;matlab_colors;matlab_colors]; % stack matlab colors so they repeat
% Sa points to plot fragility curves
x_points = 0.01:0.01:4;
% Total Collapse with discrete scatter
if analysis.run_z_motion
opts = {'', '_x', '_z'};
else
opts = {''};
end
for c = 1:length(opts)
hold on
% Gravity
rank_sa = sort(gm_table.sa_collapse_grav(~isnan(gm_table.sa_collapse_grav)));
rank_val = 1:length(rank_sa);
sct = scatter(rank_sa,rank_val./length(rank_sa),'k','filled','HandleVisibility','off');
cdf = logncdf(x_points,log(frag_curves.collapse_grav.theta),frag_curves.collapse_grav.beta);
plot(x_points,cdf,'k','DisplayName','Gravity Collapse')
% Sidesway
rank_sa = sort(gm_table.(['sa_collapse' opts{c}])(~isnan(gm_table.(['sa_collapse' opts{c}]))));
rank_val = 1:length(rank_sa);
sct = scatter(rank_sa,rank_val./length(rank_sa),'m','filled','HandleVisibility','off');
cdf = logncdf(x_points,log(frag_curves.(['collapse' opts{c}]).theta),frag_curves.(['collapse' opts{c}]).beta);
plot(x_points,cdf,'m','DisplayName','Sidesway Collapse')
% Drift
% rank_sa = sort(gm_table.sa_collapse_drift_6(~isnan(gm_table.sa_collapse_drift_6)));
% rank_val = 1:length(rank_sa);
% sct = scatter(rank_sa,rank_val./length(rank_sa),'r','filled','HandleVisibility','off');
% cdf = logncdf(x_points,log(frag_curves.collapse_drift_6.theta),frag_curves.collapse_drift_6.beta);
% plot(x_points,cdf,'r','DisplayName','Collapse at 6% Drift')
% % All
% rank_sa = sort(gm_table.(['sa_collapse_2' opts{c}])(~isnan(gm_table.(['sa_collapse_2' opts{c}]))));
% rank_val = 1:length(rank_sa);
% sct = scatter(rank_sa,rank_val./length(rank_sa),'k','filled','HandleVisibility','off');
% cdf = logncdf(x_points,log(frag_curves.(['collapse_2' opts{c}]).theta),frag_curves.(['collapse_2' opts{c}]).beta);
% plot(x_points,cdf,'k','DisplayName','Collapse Fragility All')
xlabel('Sa(T_{1-EW}) (g)')
ylabel('P[Collapse]')
xlim([0,1.5])
fn_format_and_save_plot( plot_dir, ['Collapse Fragility' opts{c}], 6 )
end
% % Total Collapse with 695 adjustments
% figure
% hold on
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'b','lineWidth',1,'DisplayName','Collapse Fragility')
% cdf = logncdf(x_points,log(frag_curves.collapse.theta + median_adjustment),frag_curves.collapse.beta);
% plot(x_points,cdf,'--b','lineWidth',1,'DisplayName','Adjustment')
% cdf = logncdf(x_points,log(frag_curves.collapse.theta + median_adjustment),0.6);
% plot(x_points,cdf,':b','lineWidth',1.25,'DisplayName','With Uncertainty')
% plot([ida_results.mce(1),ida_results.mce(1)],[0,1],'--k','lineWidth',0.5,'DisplayName','MCE_R')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Collapse]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Collapse Fragility with 695 Uncertainty', 6 )
% % Total Collapse with breakdown in each direction
% figure
% hold on
% rank_sa = sort(gm_table.sa_collapse(~isnan(gm_table.sa_collapse)));
% rank_val = (1:length(rank_sa))/length(rank_sa);
% scatter(rank_sa,rank_val,'k','filled','HandleVisibility','off');
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'k','DisplayName','Total Collapse Fragility')
% rank_sa = sort(gm_table.sa_collapse_x(~isnan(gm_table.sa_collapse_x)));
% rank_val = (1:length(rank_sa))/length(rank_sa);
% scatter(rank_sa,rank_val,'b','filled','HandleVisibility','off');
% cdf = logncdf(x_points,log(frag_curves.ew_collapse.theta),frag_curves.ew_collapse.beta);
% plot(x_points,cdf,'b','DisplayName','EW Frame Fragility')
% rank_sa = sort(gm_table.sa_collapse_z(~isnan(gm_table.sa_collapse_z)));
% rank_val = (1:length(rank_sa))/length(rank_sa);
% scatter(rank_sa,rank_val,'r','filled','HandleVisibility','off');
% cdf = logncdf(x_points,log(frag_curves.ns_collapse.theta),frag_curves.ns_collapse.beta);
% plot(x_points,cdf,'r','DisplayName','NS Wall Fragility')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Collapse]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Collapse Fragility Both Directions', 6 )
%
% % ASCE 41 Unacceptable Response v Total Collapse with 695 adjustments
% figure
% hold on
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'b','DisplayName','Collapse Fragility')
% cdf = logncdf(x_points,log(frag_curves.UR.theta),frag_curves.UR.beta);
% plot(x_points,cdf,'-.r','DisplayName','Unacceptable Response')
% plot([ida_results.mce(1),ida_results.mce(1)],[0,1],'--k','lineWidth',0.5,'DisplayName','MCE_R')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Unacceptable Response Fragility', 6 )
% Plot Each acceptance Criteria
for p = 1:length(params)
plot_name = [params{p} ' Fragilities'];
fn_plot_frag_curves(x_points, frag_curves.(params{p}), frag_curves.collapse_2, frag_curves.collapse, ida_results.spectra(1), plot_name, plot_dir, [0,1.5], params{p} )
if analysis.run_z_motion
plot_name = [params{p} ' Fragilities_x'];
fn_plot_frag_curves(x_points, frag_curves.([params{p} '_x']), frag_curves.collapse_2_x, frag_curves.collapse_x, ida_results.spectra(1), plot_name, plot_dir, [0,1.5], params{p} )
plot_name = [params{p} ' Fragilities_z'];
fn_plot_frag_curves(x_points, frag_curves.([params{p} '_z']), frag_curves.collapse_2_z, frag_curves.collapse_z, ida_results.spectra(2), plot_name, plot_dir, [0,1.5], params{p} )
end
end
% First Acceptance criteria met
% figure
% hold on
% cdf = logncdf(x_points,log(frag_curves.cols_1.cp.theta(1)),frag_curves.cols_1.cp.beta(1));
% plot(x_points,cdf,'color',matlab_colors(1,:),'lineWidth',1.5,'DisplayName','ASCE 41 CP')
% cdf = logncdf(x_points,log(frag_curves.cols_1.euro_th_NC.theta(1)),frag_curves.cols_1.euro_th_NC.beta(1));
% plot(x_points,cdf,'--','color',matlab_colors(2,:),'lineWidth',1.5,'DisplayName','EuroCode NC')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'EuroCode - First Acceptance Criteria', 6 )
%
% % 50% Acceptance criteria met
% figure
% hold on
% cdf = logncdf(x_points,log(frag_curves.cols_1.cp.theta(4)),frag_curves.cols_1.cp.beta(4));
% plot(x_points,cdf,'color',matlab_colors(1,:),'lineWidth',1.5,'DisplayName','ASCE 41 CP')
% cdf = logncdf(x_points,log(frag_curves.cols_1.euro_th_NC.theta(4)),frag_curves.cols_1.euro_th_NC.beta(4));
% plot(x_points,cdf,'--','color',matlab_colors(2,:),'lineWidth',1.5,'DisplayName','EuroCode NC')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'EuroCode - 50% Acceptance Criteria', 6 )
% % Plot For Gravity Load Lost
% figure
% hold on
% for f = 1:length(frag_probs)
% cdf = logncdf(x_points,log(frag_curves.gravity.(['percent_lost_' num2str(frag_probs(f))]).theta),frag_curves.gravity.(['percent_lost_' num2str(frag_probs(f))]).beta);
% plot(x_points,cdf,'color',matlab_colors(f+1,:),'lineWidth',1.5,'DisplayName',[num2str(frag_probs(f)) '% Gravity Capacity Lost'])
% end
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'-k','lineWidth',2,'DisplayName','Collapse Fragility')
% cdf = logncdf(x_points,log(frag_curves.UR.theta),frag_curves.UR.beta);
% plot(x_points,cdf,'-.r','lineWidth',2,'DisplayName','Unacceptable Response')
% plot([ida_results.spectra(1) ida_results.spectra(1)],[0 1],'--k','lineWidth',1.5,'DisplayName','ICSB Motion')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Gravity Load Lost Fragilities', 6 )
%
% Plot For Drift Fragilities
colormap(parula)
caxis([0 10])
cmap = parula(10);
for c = 1:length(opts)
hold on
for d = 1:10
cdf = logncdf(x_points,log(frag_curves.drift.(['idr' opts{c} '_' num2str(d)]).theta),frag_curves.drift.(['idr' opts{c} '_' num2str(d)]).beta);
plot(x_points,cdf,'color',cmap(d,:),'lineWidth',1.5,'HandleVisibility','off')
end
cdf = logncdf(x_points,log(frag_curves.(['collapse_2' opts{c}]).theta),frag_curves.(['collapse_2' opts{c}]).beta);
plot(x_points,cdf,'--k','lineWidth',2,'DisplayName','Gravity Collapse')
cdf = logncdf(x_points,log(frag_curves.(['collapse' opts{c}]).theta),frag_curves.(['collapse' opts{c}]).beta);
plot(x_points,cdf,'--m','lineWidth',2,'DisplayName','Sidesway Collapse')
xlabel('Sa(T_{1-EW}) (g)')
ylabel('P[Exceedance]')
xlim([0,2])
h = colorbar;
ylabel(h, 'Peak Drift')
for i = 1:length(h.TickLabels)
h.TickLabels{i} = [num2str(str2double(h.TickLabels{i})*20) '%'];
end
fn_format_and_save_plot( plot_dir, ['Max Drift Fragilities' opts{c}], 6 )
% Plot For grav dcr
hold on
for d = 1:10
cdf = logncdf(x_points,log(frag_curves.gravity.(['dcr_' num2str(d*10)]).theta),frag_curves.gravity.(['dcr_' num2str(d*10)]).beta);
plot(x_points,cdf,'color',matlab_colors(d,:),'lineWidth',1.5,'DisplayName',['Grav DCR > ' num2str(d)/10])
end
cdf = logncdf(x_points,log(frag_curves.(['collapse' opts{c}]).theta),frag_curves.(['collapse' opts{c}]).beta);
plot(x_points,cdf,'-k','lineWidth',2,'DisplayName','Collapse Fragility')
xlabel('Sa(T_{1-EW}) (g)')
ylabel('P[Exceedance]')
xlim([0,2])
fn_format_and_save_plot( plot_dir, ['Grav DCR Fragilities' opts{c}], 6 )
end
% Plot For lateral cap
hold on
for d = 1:9
cdf = logncdf(x_points,log(frag_curves.lateral.(['cap_both_' num2str(d*10)]).theta),frag_curves.lateral.(['cap_both_' num2str(d*10)]).beta);
plot(x_points,cdf,'color',matlab_colors(d,:),'lineWidth',1.5,'DisplayName',[num2str(d)/10 '% Lat Capacity Remains'])
end
cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
plot(x_points,cdf,'-k','lineWidth',2,'DisplayName','Collapse Fragility')
xlabel('Sa(T_{1-EW}) (g)')
ylabel('P[Exceedance]')
xlim([0,2])
fn_format_and_save_plot( plot_dir, 'Lateral Capacity Fragilities', 6 )
%
%
% % Plot For Adjacent Components
% figure
% hold on
% cdf = logncdf(x_points,log(frag_curves.adjacent_comp.any.theta),frag_curves.adjacent_comp.any.beta);
% plot(x_points,cdf,'color',matlab_colors(1,:),'DisplayName','Any Adjacent Component')
% cdf = logncdf(x_points,log(frag_curves.adjacent_comp.any_frame.theta),frag_curves.adjacent_comp.any_frame.beta);
% plot(x_points,cdf,'color',matlab_colors(2,:),'DisplayName','Any Adjacent Frame Component')
% cdf = logncdf(x_points,log(frag_curves.adjacent_comp.all.theta),frag_curves.adjacent_comp.all.beta);
% plot(x_points,cdf,'color',matlab_colors(3,:),'DisplayName','All Adjacent Components')
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'-k','DisplayName','Collapse Fragility')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Adjacent Component Fragilities', 6 )
%
% % Plot For Percent of Collapse Energy
% figure
% hold on
% for f = 1:length(frag_probs)
% cdf = logncdf(x_points,log(frag_curves.energy.(['percent_collapse_' num2str(frag_probs(f))]).theta),frag_curves.energy.(['percent_collapse_' num2str(frag_probs(f))]).beta);
% plot(x_points,cdf,'color',matlab_colors(f,:),'DisplayName',[num2str(frag_probs(f)) '% of Collapse Energy'])
% end
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'-k','DisplayName','Collapse Fragility')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Collapse Energy Fragilities', 6 )
%
% % Plot Multiple trigger types together
% % Plot For Adjacent Components
% figure
% hold on
% cdf = logncdf(x_points,log(frag_curves.cols_walls_1.b_e.theta(1)),frag_curves.cols_walls_1.b_e.beta(1));
% plot(x_points,cdf,'color',matlab_colors(1,:),'DisplayName','ASCE 41 CP')
% cdf = logncdf(x_points,log(frag_curves.adjacent_comp.any.theta),frag_curves.adjacent_comp.any.beta);
% plot(x_points,cdf,'color',matlab_colors(2,:),'DisplayName','Any Adjacent Component')
% cdf = logncdf(x_points,log(frag_curves.gravity.percent_lost_25.theta),frag_curves.gravity.percent_lost_25.beta);
% plot(x_points,cdf,'color',matlab_colors(3,:),'DisplayName','25% Load Capacity Lost')
% cdf = logncdf(x_points,log(frag_curves.drift.idr_2.theta),frag_curves.drift.idr_2.beta);
% plot(x_points,cdf,'color',matlab_colors(4,:),'DisplayName','2% Max Interstory Drift')
% cdf = logncdf(x_points,log(frag_curves.collapse.theta),frag_curves.collapse.beta);
% plot(x_points,cdf,'-k','DisplayName','Collapse Fragility')
% xlabel('Sa(T_{1-EW}) (g)')
% ylabel('P[Exceedance]')
% xlim([0,2])
% fn_format_and_save_plot( plot_dir, 'Multi Fragility Compare', 6 )
end
function [ ] = fn_plot_frag_curves(x_points, frag_curves, col_frag_curve, col_no_grav, icsb_motion, plot_name, plot_dir, x_range, param_name)
% Import packages
import plotting_tools.*
% colormap(parula)
colormap(parula)
cmap = parula(100);
hold on
cdf = logncdf(x_points,log(frag_curves.theta(1)),frag_curves.beta(1));
plot(x_points,cdf,'color',cmap(round(100*frag_curves.prct_mech(1)),:),'lineWidth',1.5,'HandleVisibility','off')
for i = 2:height(frag_curves)
cdf = logncdf(x_points,log(frag_curves.theta(i)),frag_curves.beta(i));
% plot(x_points,cdf,'color',cmap(i,:),'lineWidth',1.5,'DisplayName',[num2str(100*frag_curves.prct_mech(i)) '% of Mechanism'])
plot(x_points,cdf,'color',cmap(round(100*frag_curves.prct_mech(i)),:),'lineWidth',1.5,'HandleVisibility','off')
end
cdf = logncdf(x_points,log(col_frag_curve.theta),col_frag_curve.beta);
plot(x_points,cdf,'--k','lineWidth',2,'DisplayName','Gravity Collapse')
cdf = logncdf(x_points,log(col_no_grav.theta),col_no_grav.beta);
plot(x_points,cdf,'--m','lineWidth',2,'DisplayName','Sidesway Collapse')
% plot([icsb_motion icsb_motion],[0 1],'--k','lineWidth',1.5,'DisplayName','ICSB Motion')
xlabel('Sa(T_{1-EW}) (g)')
ylabel('P[Exceedance]')
xlim(x_range)
h = colorbar;
ylabel(h, ['Fraction of Components Exceeding ' upper(param_name)])
fn_format_and_save_plot( plot_dir, plot_name, 6 )
end
|
github
|
dustin-cook/Opensees-master
|
fn_collect_ida_data.m
|
.m
|
Opensees-master/+ida/fn_collect_ida_data.m
| 16,452 |
utf_8
|
b447072a963f905edc4204b5c38695f5
|
function [ ] = fn_collect_ida_data(analysis, model, gm_set_table, ida_results, main_dir, write_dir)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
%% Initial Setup
% Import packages
import plotting_tools.*
% Defined fixed parames
% params = {'b','e','io','ls','cp','euro_th_NC','euro_th_SD','euro_th_DL'};
% params = {'b','io','ls','cp','euro_th_NC','euro_th_SD','euro_th_DL'};
if analysis.run_z_motion
params = {'b','e','io','ls','cp'};
else
params = {'b','io','ls','cp'};
end
% load element properties
ele_prop_table = readtable(['inputs' filesep 'element.csv'],'ReadVariableNames',true);
% Load model data
model_dir = [main_dir '/' 'opensees_data'];
asce41_dir = [main_dir '/' 'asce_41_data'];
load([asce41_dir filesep 'element_analysis.mat']);
% Collect IDA data
id = 0;
id_missing = 0;
for gm = 1:height(gm_set_table)
gm_dir = [main_dir '/' 'IDA' '/' 'Summary Data' '/' 'GM_' num2str(gm_set_table.set_id(gm)) '_' num2str(gm_set_table.pair(gm))];
scale_folders = dir([gm_dir filesep 'Scale_*']);
for s = 1:length(scale_folders)
% Load data
outputs_dir = [main_dir '/' 'IDA' '/' 'Summary Data' '/' 'GM_' num2str(gm_set_table.set_id(gm)) '_' num2str(gm_set_table.pair(gm)) '/' scale_folders(s).name];
outputs_file = [outputs_dir filesep 'summary_results.mat'];
hinge_file = [outputs_dir filesep 'hinge_analysis.mat'];
story_file = [outputs_dir filesep 'story_analysis.mat'];
if exist(outputs_file,'file') && exist(hinge_file,'file')
load(outputs_file)
load(hinge_file)
load(story_file)
if isfield(summary,'max_drift_x')
id = id + 1;
ida.id(id,1) = id;
ida.eq_name{id,1} = gm_set_table.eq_name{gm};
ida.scale(id,1) = str2double(regexp(scale_folders(s).name,'(?<=_).+$','match'));
if analysis.run_z_motion
ida.max_drift(id,1) = max(summary.max_drift_x,summary.max_drift_z);
else
ida.max_drift(id,1) = summary.max_drift_x;
end
% X direction
ida.sa_x(id,1) = summary.sa_x;
ida.sa_geo(id,1) = summary.sa_x;
ida.mce_ratio_x(id,1) = ida.sa_x(id,1)/ida_results.mce(1);
ida.drift_x(id,1) = summary.max_drift_x;
% z direction
if analysis.run_z_motion
ida.sa_z(id,1) = summary.sa_z;
ida.sa_geo(id,1) = geomean([summary.sa_x,summary.sa_z]);
ida.mce_ratio_z(id,1) = ida.sa_z(id,1)/ida_results.mce(2);
ida.drift_z(id,1) = summary.max_drift_z;
end
% Collapse metrics
ida.collapse(id,1) = summary.collapse;
if summary.collapse > 0
ida.collapse_direction{id,1} = summary.collapse_direction;
ida.collapse_mech{id,1} = summary.collaspe_mech;
if strcmp(summary.collapse_direction,'x')
ida.collapse_x(id,1) = summary.collapse;
ida.collapse_z(id,1) = NaN;
elseif strcmp(summary.collapse_direction,'z')
ida.collapse_x(id,1) = NaN;
ida.collapse_z(id,1) = summary.collapse;
end
if contains(summary.collaspe_mech,'column')
ida.collapse_comps(id,1) = sum(hinge.b_ratio(strcmp(hinge.ele_type,'column')) >= 1);
elseif contains(summary.collaspe_mech,'wall')
ida.collapse_comps(id,1) = sum(hinge.e_ratio(strcmp(hinge.ele_type,'wall')) >= 1);
else
ida.collapse_comps(id,1) = sum(hinge.b_ratio >= 1);
end
else
ida.collapse_direction{id,1} = 'NA';
ida.collapse_mech{id,1} = 'NA';
ida.collapse_x(id,1) = NaN;
ida.collapse_z(id,1) = NaN;
ida.collapse_comps(id,1) = NaN;
end
% % Dissapated Energy
% col_hinges = hinge(hinge.story == 1 & strcmp(hinge.direction,'primary') & strcmp(hinge.ele_type,'column'),:);
% in_plane_col_base = hinge(hinge.story == 1 & hinge.ele_side == 1 & strcmp(hinge.direction,'primary') & strcmp(hinge.ele_type,'column'),:);
%
% ew_pushover_energy = 0;
% for e = 1:height(col_hinges)
% pushover_TH = load([pushover_dir filesep 'hinge_TH_' num2str(col_hinges.id(e)) '.mat']);
% ew_pushover_energy = max(pushover_TH.hin_TH.energy_ft_lbs) + ew_pushover_energy;
% end
% % ns_pushover_energy = 0;
% % for e = 1:height(wall_hinges)
% % pushover_TH = load([pushover_dir filesep 'hinge_TH_' num2str(wall_hinges.id(e)) '.mat']);
% % ns_pushover_energy = max(pushover_TH.hin_TH.energy_ft_lbs) + ns_pushover_energy;
% % end
% ida.total_energy_ft_lbs(id,1) = sum(cols_walls_1_hinges.total_engergy_ft_lbs);
% ida.total_energy_ew(id,1) = sum(col_hinges.total_engergy_ft_lbs);
% % ida.total_energy_ns(id,1) = sum(wall_hinges.total_engergy_ft_lbs);
% % ida.norm_energy_tot(id,1) = ida.total_energy_ft_lbs(id,1) / (ew_pushover_energy + ns_pushover_energy);
% ida.norm_energy_tot(id,1) = ida.total_energy_ft_lbs(id,1) / (ew_pushover_energy);
% ida.norm_energy_ew(id,1) = ida.total_energy_ew(id,1) / ew_pushover_energy;
% % ida.norm_energy_ns(id,1) = ida.total_energy_ns(id,1) / ns_pushover_energy;
% % ida.norm_energy_max(id,1) = max([ida.norm_energy_ew(id,1),ida.norm_energy_ns(id,1)]);
% ida.norm_energy_max(id,1) = ida.norm_energy_ew(id,1);
% Gravity and Lateral Capacity Remaining (currently only works
% for EW frame direction, need to record column response OOP to
% fix)
for i = 1:height(story)
gravity_load(i) = sum(story.story_dead_load(i:end)) + sum(story.story_live_load(i:end));
col_hinges_1 = hinge(hinge.story == i & strcmp(hinge.ele_type,'column') & hinge.ele_side == 1,:);
col_hinges_2 = hinge(hinge.story == i & strcmp(hinge.ele_type,'column') & hinge.ele_side == 2,:);
if ~isempty(col_hinges_1)
grav_cap_1 = sum(col_hinges_1.P_capacity);
grav_cap_2 = sum(col_hinges_2.P_capacity);
gravity_capacity(i) = min([grav_cap_1,grav_cap_2]);
else
gravity_capacity(i) = inf;
end
end
axial_dcr = gravity_load ./ gravity_capacity;
ida.gravity_dcr(id,1) = max(axial_dcr);
% Lateral Capacity Remaining (first story)
% full strength
all_cols = element(element.story == 1 & strcmp(element.type,'column'),:);
lat_cap_tot = sum(all_cols.Mn_pos_1) + sum(all_cols.Mn_pos_2);
% Mean rotation capacity of columns
ida.mean_rot_cap(id,1) = mean([all_cols.b_hinge_1;all_cols.b_hinge_2]);
% Mean rotation capacity of columns from gravity
tn = tan(pi*65/180);
for c = 1:height(all_cols)
ele_prop = ele_prop_table(ele_prop_table.id == all_cols.ele_id(c),:);
for sd = 1:2
as = ele_prop.(['Av_' num2str(hinge.ele_side(sd))]);
fyt = ele_prop.fy_e;
dc = ele_prop.w/2 - ele_prop.clear_cover;
s = ele_prop.(['S_' num2str(hinge.ele_side(sd))]);
all_cols.(['drift_grav_' num2str(sd)])(c) = (4/100)*(1+tn^2)/(tn + all_cols.Pmax(c)*(s / (as*fyt*dc*tn)));
end
end
ida.mean_rot_cap_grav(id,1) = mean([all_cols.drift_grav_1;all_cols.drift_grav_2]);
ida.mean_rot_cap_grav_min(id,1) = mean(min(all_cols.drift_grav_1,all_cols.drift_grav_2));
% remaining hinges and columns
failed_col_any = hinge.element_id(hinge.story == 1 & strcmp(hinge.ele_type,'column') & hinge.a_ratio > 1);
failed_col_1 = hinge.element_id(hinge.story == 1 & strcmp(hinge.ele_type,'column') & hinge.ele_side == 1 & hinge.a_ratio > 1);
failed_col_2 = hinge.element_id(hinge.story == 1 & strcmp(hinge.ele_type,'column') & hinge.ele_side == 2 & hinge.a_ratio > 1);
remianing_cols = element(element.story == 1 & strcmp(element.type,'column') & ~ismember(element.id,unique(failed_col_any)),:);
remianing_cols_1 = element(element.story == 1 & strcmp(element.type,'column') & ~ismember(element.id,failed_col_1),:);
remianing_cols_2 = element(element.story == 1 & strcmp(element.type,'column') & ~ismember(element.id,failed_col_2),:);
% remaining columns with no damage
lat_cap_remain = sum(remianing_cols.Mn_pos_1) + sum(remianing_cols.Mn_pos_2);
ida.lat_cap_ratio_any(id,1) = lat_cap_remain / lat_cap_tot;
% remaining columns with only 1 side damaged
lat_cap_remain = sum(remianing_cols_1.Mn_pos_1) + sum(remianing_cols_2.Mn_pos_2);
ida.lat_cap_ratio_both(id,1) = lat_cap_remain / lat_cap_tot;
% max side of columns remaining
lat_cap_remain = max([sum(remianing_cols_1.Mn_pos_1),sum(remianing_cols_2.Mn_pos_2)]);
ida.lat_cap_ratio_max(id,1) = lat_cap_remain / (lat_cap_tot/2); % only works when columns are symmetric
% how many full column failures are there
ida.num_full_col_fails(id,1) = sum(~ismember(all_cols.id,remianing_cols_1.id) & ~ismember(all_cols.id,remianing_cols_2.id));
else
id_missing = id_missing + 1;
missing_ida.eq_name{id_missing,1} = gm_set_table.eq_name{gm};
missing_ida.scale(id_missing,1) = str2double(regexp(scale_folders(s).name,'(?<=_).+$','match'));
end
else
id_missing = id_missing + 1;
missing_ida.eq_name{id_missing,1} = gm_set_table.eq_name{gm};
missing_ida.scale(id_missing,1) = str2double(regexp(scale_folders(s).name,'(?<=_).+$','match'));
end
end
end
ida_table = struct2table(ida);
% Remove all cases that failed to converge yet did not get far enough
failed_convergence = ida_table(ida_table.collapse == 5,:);
ida_table(ida_table.collapse == 5,:) = []; % filter out failed models
% Go through and define collapse props for each ground motion
for gm = 1:height(gm_set_table)
filt_collapse = ida_table.collapse > 0 & strcmp(ida_table.eq_name,gm_set_table.eq_name{gm});
% Remove all GM's that do not collapse
if sum(filt_collapse) == 0
ida_table(strcmp(ida_table.eq_name,gm_set_table.eq_name{gm}),:) = [];
else
collapse_idx = find(filt_collapse,1,'first');
gm_set_table.scale_collapse(gm) = ida_table.scale(collapse_idx);
gm_set_table.scale_jbc(gm) = ida_table.scale(collapse_idx - 1);
gm_set_table.collapse_dir(gm) = ida_table.collapse_direction(collapse_idx);
gm_set_table.collapse_mech(gm) = ida_table.collapse_mech(collapse_idx);
gm_set_table.collapse_comps(gm) = ida_table.collapse_comps(collapse_idx);
end
end
gm_set_table(gm_set_table.scale_collapse == 0,:) = [];
% Go through IDA table and get hinge properties based on collapse mechanism
for i = 1:height(ida_table)
outputs_dir = [main_dir '/' 'IDA' '/' 'Summary Data' '/' 'GM_' num2str(gm_set_table.set_id(strcmp(gm_set_table.eq_name,ida_table.eq_name{i}))) '_' num2str(gm_set_table.pair(strcmp(gm_set_table.eq_name,ida_table.eq_name{i}))) '/Scale_' num2str(ida_table.scale(i))];
hinge_file = [outputs_dir filesep 'hinge_analysis.mat'];
load(hinge_file)
% Identify collapse case for this GM
gm_stripes = ida_table(strcmp(ida_table.eq_name,ida_table.eq_name{i}),:);
collapse_idx = find(gm_stripes.collapse > 0,1,'first');
collapse_hinge_file = [main_dir '/' 'IDA' '/' 'Summary Data' '/' 'GM_' num2str(gm_set_table.set_id(strcmp(gm_set_table.eq_name,ida_table.eq_name{i}))) '_' num2str(gm_set_table.pair(strcmp(gm_set_table.eq_name,ida_table.eq_name{i}))) '/Scale_' num2str(gm_stripes.scale(collapse_idx)) filesep 'hinge_analysis.mat'];
collapse_hinge = load(collapse_hinge_file);
% Get element group filters from collapse case
if contains(gm_stripes.collapse_mech{collapse_idx},'column')
% collapse mechanism is all column hinges that have failed in the first stripe that collapse
mech_filter = strcmp(collapse_hinge.hinge.direction,'primary') & collapse_hinge.hinge.b_ratio >= 1 & strcmp(collapse_hinge.hinge.ele_type,'column');
elseif contains(gm_stripes.collapse_mech{collapse_idx},'wall')
% collapse mechanism is all wall hinges that have failed in the first stripe that collapse
mech_filter = strcmp(collapse_hinge.hinge.direction,'primary') & collapse_hinge.hinge.e_ratio >= 1 & strcmp(collapse_hinge.hinge.ele_type,'wall');
else
% collapse mechanism is all hinges that have failed in the first stripe that collapse
mech_filter = strcmp(collapse_hinge.hinge.direction,'primary') & (collapse_hinge.hinge.b_ratio >= 1 | collapse_hinge.hinge.e_ratio >= 1);
end
% mech_filter = strcmp(collapse_hinge.hinge.direction,'primary') & collapse_hinge.hinge.b_ratio >= 1;
ida_table.num_comps(i) = sum(mech_filter);
mech_hinges = hinge(mech_filter,:);
% For Each accetance criteria listed above
for p = 1:length(params)
[ num_eles, percent_eles, num_eles_15, max_ele, min_ele, mean_ele, range_ele, std_ele, cov_ele ] = fn_collect_component_data(params{p}, ida_table.collapse(i), ida_table.collapse_direction{i}, mech_hinges);
ida_table.(['num_' params{p}])(i) = num_eles;
ida_table.(['percent_' params{p}])(i) = percent_eles;
ida_table.(['num_' params{p} '_15'])(i) = num_eles_15;
ida_table.(['max_' params{p}])(i) = max_ele;
ida_table.(['min_' params{p}])(i) = min_ele;
ida_table.(['mean_' params{p}])(i) = mean_ele;
ida_table.(['range_' params{p}])(i) = range_ele;
ida_table.(['std_' params{p}])(i) = std_ele;
ida_table.(['cov_' params{p}])(i) = cov_ele;
end
% % Unacceptable Response
% if ida_table.collapse(i) == 1 || ida_table.collapse(i) == 3 || ida_table.num_b_15(i) > 0
% ida_table.UR(i) = 1;
% else
% ida_table.UR(i) = 0;
% end
%
% % Gravity Load Lost
% first_story_elements = element(ismember(element.id, mech_hinges.element_id),:);
% hinges_lost_grav = mech_hinges(mech_hinges.b_ratio > 1,:);
% elements_lost_grav = element(ismember(element.id, hinges_lost_grav.element_id),:);
% grav_load_lost = sum(elements_lost_grav.P_grav);
% total_grav_load = sum(first_story_elements.P_grav);
% ida_table.gravity_load_lost_ratio(i) = grav_load_lost / total_grav_load;
end
% Save Tabular Results as CSVs
writetable(gm_set_table,[write_dir filesep 'gm_table.csv'])
writetable(ida_table,[write_dir filesep 'ida_table.csv'])
if exist('missing_ida','var')
writetable(struct2table(missing_ida),[write_dir filesep 'idas_missing.csv'])
end
writetable(failed_convergence,[write_dir filesep 'idas_failed_convergence.csv'])
end
function [ num_eles, percent_eles, num_eles_15, max_ele, min_ele, mean_ele, range_ele, std_ele, cov_ele ] = fn_collect_component_data(var_name, collapse_flag, collaspe_dir, ele_hinges)
ele_ratios = ele_hinges.([var_name '_ratio']);
num_eles = 0;
num_eles_15 = 0;
for e = 1:length(ele_ratios)
if (collapse_flag == 3 || collapse_flag == 1)
if strcmp(ele_hinges.ele_direction(e),collaspe_dir)
num_eles = num_eles + 1; % if collapse this gm, in this direction, set this element to 1
num_eles_15 = num_eles_15 + 1;
end
elseif ele_ratios(e) >= 1.5
num_eles_15 = num_eles_15 + 1;
num_eles = num_eles + 1;
elseif ele_ratios(e) >= 1
num_eles = num_eles + 1;
end
end
percent_eles = num_eles / length(ele_ratios);
max_ele = max(ele_ratios);
min_ele = min(ele_ratios);
mean_ele = mean(ele_ratios);
range_ele = max_ele - min_ele;
std_ele = std(ele_ratios);
cov_ele = std_ele/mean_ele;
end
|
github
|
dustin-cook/Opensees-master
|
fn_LR_classification.m
|
.m
|
Opensees-master/+ida/fn_LR_classification.m
| 4,345 |
utf_8
|
8d9543972142be96cfc4d77f90939f0a
|
function [ ] = fn_LR_classification(analysis,model,gm_set_table)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
%% Initial Setup
% Load Fragility Data
read_dir = ['outputs' '/' model.name{1} '/' analysis.proceedure '_' analysis.id '/' 'IDA' '/' 'Fragility Data'];
ida_table = readtable([read_dir filesep 'ida_table.csv']);
%% Fake new collapse cases above for each ground motion such that LR is balanced (or just take the just before collapse and just after collapse for each)
% for gm = 1:height(gm_set_table)
% gm_response_no_col = ida_table(strcmp(ida_table.eq_name,gm_set_table.eq_name(gm)) & ida_table.collapse == 0,:);
% Sa_jbc = max(gm_response_no_col.sa_x);
% ida_table.jbc(strcmp(ida_table.eq_name,gm_set_table.eq_name(gm)) & ida_table.sa_x == Sa_jbc) = 1;
% end
% filt_ida_table = ida_table(ida_table.jbc == 1 | ida_table.collapse > 0,:);
new_ida_table = table;
for gm = 1:height(gm_set_table)
gm_response = ida_table(strcmp(ida_table.eq_name,gm_set_table.eq_name(gm)),:);
gm_response.collapse(end) = 1;
no_col_cases = gm_response(gm_response.collapse == 0,:);
col_cases = gm_response(gm_response.collapse > 0,:);
pt_diff = height(no_col_cases) - height(col_cases);
new_cases = col_cases(end,:);
sa_orig = gm_response.sa_x(gm_response.scale == 1)
new_sa = 0.25*sa_orig + col_cases.sa_x(end);
new_cases.sa_x = new_sa;
for s = 2:pt_diff
new_sa = new_sa + 0.25*sa_orig;
new_cases(s,:) = col_cases(end,:);
new_cases.sa_x(s) = new_sa;
end
new_ida_table = [new_ida_table;no_col_cases;col_cases;new_cases];
end
%% For each component metric, quantify comparison logistic regression
% Collapse
attrs = {'sa_x', 'max_drift', 'drift_x', 'drift_z', 'gravity_load_lost_ratio','gravity_load_lost_ratio_alt','total_energy_ft_lbs','norm_energy_max','norm_energy_tot',...
'num_adjacent_failure_any','num_adjacent_failure_any_frame','num_adjacent_failure_all', 'cols_walls_1_num_cp', 'cols_walls_1_percent_cp',...
'cols_walls_1_max_cp','cols_walls_1_min_cp','cols_walls_1_mean_cp','cols_walls_1_range_cp','cols_walls_1_std_cp','cols_walls_1_cov_cp',...
'cols_walls_1_num_b_e','cols_walls_1_percent_b_e','cols_walls_1_max_b_e','cols_walls_1_mean_b_e'};
for a = 1:length(attrs)
plot_dir = ['outputs' '/' model.name{1} '/' analysis.proceedure '_' analysis.id '/' 'IDA' '/' 'ML Plots' '/' 'Collapse'];
[LR.collapse.(attrs{a})] = fn_logistic_regression(max(new_ida_table.(attrs{a}),1e-6), min(new_ida_table.collapse,1), plot_dir, attrs{a});
end
% Save Logistic Regression Fits
save([read_dir filesep 'LR_data.mat'],'LR')
end
function [metrics] = fn_logistic_regression(max_component_response, collapse_target, plot_dir, x_label)
import plotting_tools.fn_format_and_save_plot
%% Logistic Regression
B = mnrfit(log(max_component_response),categorical(~collapse_target));
% B = glmfit(log(ida_table_full.sa_x),collapse_target,'binomial','link','probit');
z_val = B(1) + log(max_component_response)*B(2);
prob_val = 1 ./ (1+exp(-z_val));
metrics.LR_value_coef = B(1);
metrics.LR_correlation_coef = B(2);
metrics.LR_threshold_response_ratio = -B(1)/B(2);
metrics.LR_prob_consequece_given_component = 1 / (1+exp(-(B(1) + 1*B(2))));
prediction = zeros(length(collapse_target),1);
prediction(prob_val > 0.5) = 1;
metrics.LR_accuracy = sum(collapse_target == prediction)/length(collapse_target);
TP = sum(and(prediction,collapse_target));
TN = sum(and(~prediction,~collapse_target));
FP = sum(and(prediction,~collapse_target));
FN = sum(and(~prediction,collapse_target));
metrics.LR_precision = TP / (TP+FP);
metrics.LR_recall = TP / (FN+TP);
metrics.LR_F1 = 2*metrics.LR_precision*metrics.LR_recall / (metrics.LR_precision + metrics.LR_recall);
max_val = max(max_component_response)*1.1;
x_points = linspace(min(max_component_response),max_val,1000);
z_predict = B(1) + log(x_points)*B(2);
prob_predict = 1 ./ (1+exp(-z_predict));
hold on
scatter(max_component_response,collapse_target,'DisplayName','Recorded Collapse')
plot(x_points,prob_predict,'DisplayName','Predicted Collapse')
xlabel(strrep(x_label,'_',' '))
ylabel('Probability of Collapse')
xlim([0,max_val])
fn_format_and_save_plot( plot_dir, x_label, 3, 1 )
% Change Metrics to table for outputs
metrics = struct2table(metrics);
end
|
github
|
dustin-cook/Opensees-master
|
fn_create_fragilities.m
|
.m
|
Opensees-master/+ida/fn_create_fragilities.m
| 20,396 |
utf_8
|
4a3ced77909b5d5079c9ae7ba7388c7a
|
function [ ] = fn_create_fragilities(analysis, write_dir)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
%% Initial Setup
% Import packages
import plotting_tools.*
% Defined fixed parames
% params = {'b','e','b_e','io','ls','cp','euro_th_NC','euro_th_SD','euro_th_DL'};
% mechs = { 'cols_1', 'walls_1', 'cols_walls_1'};
if analysis.run_z_motion
attrs = {'sa_geo', 'max_drift', 'drift_x', 'drift_z', 'gravity_dcr', 'lat_cap_ratio_any', 'lat_cap_ratio_both', 'lat_cap_ratio_max', ...
'num_cp', 'percent_cp','max_cp','min_cp','mean_cp','range_cp','std_cp','cov_cp',...
'num_b','percent_b','min_b','max_b','mean_b', 'num_full_col_fails',...
'num_e','percent_e','min_e','max_e','mean_e'};
params = {'b','e','io','ls','cp'};
else
attrs = {'sa_geo', 'max_drift', 'drift_x', 'gravity_dcr', 'lat_cap_ratio_any', 'lat_cap_ratio_both', 'lat_cap_ratio_max', ...
'num_cp', 'percent_cp','max_cp','min_cp','mean_cp','range_cp','std_cp','cov_cp',...
'num_b','percent_b','min_b','max_b','mean_b', 'num_full_col_fails'};
params = {'b','io','ls','cp'};
end
frag_probs = [10 25 50 75 100];
%% Collect info for each ground motion (new fragilities)
ida_table = readtable([write_dir filesep 'ida_table.csv']);
gm_table = readtable([write_dir filesep 'gm_table.csv']);
gm_data.collapse = table;
gm_data.collapse_2 = table;
gm_data.gravity = table;
gm_data.collapse_x = table;
gm_data.collapse_2_x = table;
if analysis.run_z_motion
gm_data.collapse_z = table;
gm_data.collapse_2_z = table;
end
for gm = 1:height(gm_table)
gm_response = ida_table(strcmp(ida_table.eq_name,gm_table.eq_name(gm)),:);
if ~isempty(gm_response)
gm_response_no_col = ida_table(strcmp(ida_table.eq_name,gm_table.eq_name(gm)) & ida_table.collapse == 0,:);
gm_response_no_col.collapse(gm_response_no_col.sa_geo == max(gm_response_no_col.sa_geo)) = 1; % Flag just before collapse point
jbc = gm_response_no_col;
% Just Before Collapse
gm_data.collapse.eq_name{gm} = gm_table.eq_name{gm};
gm_data.collapse_x.eq_name{gm} = gm_table.eq_name{gm};
if analysis.run_z_motion
gm_data.collapse_z.eq_name{gm} = gm_table.eq_name{gm};
end
for a = 1:length(attrs)
gm_data.collapse.(attrs{a})(gm) = min(jbc.(attrs{a})(jbc.collapse == 1));
if strcmp(gm_table.collapse_dir{gm},'x')
gm_data.collapse_x.(attrs{a})(gm) = min(jbc.(attrs{a})(jbc.collapse == 1));
if analysis.run_z_motion
gm_data.collapse_z.(attrs{a})(gm) = NaN;
end
elseif strcmp(gm_table.collapse_dir{gm},'z')
gm_data.collapse_x.(attrs{a})(gm) = NaN;
gm_data.collapse_z.(attrs{a})(gm) = min(jbc.(attrs{a})(jbc.collapse == 1));
end
end
% Post Process Collapse
pp_collapse = jbc;
pp_collapse.collapse(pp_collapse.max_drift >= 0.06) = 1;
pp_collapse.collapse(pp_collapse.gravity_dcr >= 1) = 1;
gm_data.collapse_2.eq_name{gm} = gm_table.eq_name{gm};
gm_data.collapse_2_x.eq_name{gm} = gm_table.eq_name{gm};
if analysis.run_z_motion
gm_data.collapse_2_z.eq_name{gm} = gm_table.eq_name{gm};
end
for a = 1:length(attrs)
gm_data.collapse_2.(attrs{a})(gm) = min(pp_collapse.(attrs{a})(pp_collapse.collapse == 1));
if strcmp(gm_table.collapse_dir{gm},'x')
gm_data.collapse_2_x.(attrs{a})(gm) = min(pp_collapse.(attrs{a})(pp_collapse.collapse == 1));
if analysis.run_z_motion
gm_data.collapse_2_z.(attrs{a})(gm) = NaN;
end
elseif strcmp(gm_table.collapse_dir{gm},'z')
gm_data.collapse_2_x.(attrs{a})(gm) = NaN;
gm_data.collapse_2_z.(attrs{a})(gm) = min(pp_collapse.(attrs{a})(pp_collapse.collapse == 1));
end
end
% % Full Gravity Exceedance
% gm_data.full_gravity.eq_name{gm} = gm_set_table.eq_name{gm};
% for a = 1:length(attrs)
% gm_data.full_gravity.(attrs{a})(gm) = min(jbc.(attrs{a})(jbc.gravity_dcr >= 1));
% end
end
end
% Save Tabular Results as CSVs
save([write_dir filesep 'gm_data.mat'],'gm_data')
%% Create Fragility Curves based on Baker MLE (New Fragilities)
% collape and unnacceptable response
field_names = fieldnames(gm_data);
for i = 1:length(field_names)
fld = field_names{i};
for j = 2:width(gm_data.(fld))
var_name = gm_data.(fld).Properties.VariableNames{j};
[new_frag_curves.(fld).(var_name)] = fn_fit_fragility_MOM(gm_data.(fld).(var_name));
end
end
% Save Frag Curve Data
save([write_dir filesep 'new_frag_curves.mat'],'new_frag_curves')
%% Collect info for each ground motion (traditional fragilities)
for gm = 1:height(gm_table)
gm_response = ida_table(strcmp(ida_table.eq_name,gm_table.eq_name(gm)),:);
gm_table.sa_collapse(gm) = max([min(gm_response.sa_geo(gm_response.collapse > 0)),NaN]);
gm_table.sa_collapse_drift(gm) = max([min(gm_response.sa_geo(gm_response.collapse == 1)),NaN]);
gm_table.sa_collapse_drift_6(gm) = max([min(gm_response.sa_geo(gm_response.max_drift >= 0.06)),NaN]);
gm_table.sa_collapse_grav(gm) = max([min(gm_response.sa_geo(gm_response.gravity_dcr >= 1)),NaN]);
gm_table.sa_collapse_2(gm) = max([min(gm_response.sa_geo(gm_response.collapse > 0 | gm_response.max_drift >= 0.06 | gm_response.gravity_dcr > 1)),NaN]);
gm_table.sa_collapse_x(gm) = max([min(gm_response.sa_geo(gm_response.collapse_x > 0)),NaN]);
gm_table.sa_collapse_2_x(gm) = max([min(gm_response.sa_geo(gm_response.collapse_x > 0 | gm_response.drift_x >= 0.06 | gm_response.gravity_dcr > 1)),NaN]);
gm_table.sa_collapse_convergence(gm) = max([min(gm_response.sa_geo(gm_response.collapse == 3)),NaN]);
gm_table.sa_UR_accept_15(gm) = max([min(gm_response.sa_geo(gm_response.num_b_15 > 0)),NaN]);
gm_table.sa_UR(gm) = max([min(gm_response.sa_geo(gm_response.collapse == 1 | gm_response.collapse == 3 | gm_response.num_b_15 > 0)),NaN]);
if analysis.run_z_motion
gm_table.sa_collapse_z(gm) = max([min(gm_response.sa_geo(gm_response.collapse_z > 0)),NaN]);
gm_table.sa_collapse_2_z(gm) = max([min(gm_response.sa_geo(gm_response.collapse_z > 0 | gm_response.drift_z >= 0.06 | gm_response.gravity_dcr > 1)),NaN]);
end
% 1% to 10% drift fragilities
for d = 1:10
gm_table.(['sa_drift_' num2str(d)])(gm) = max([min(gm_response.sa_geo(gm_response.max_drift >= d/100)),NaN]);
if analysis.run_z_motion
gm_table.(['sa_drift_x_' num2str(d)])(gm) = max([min(gm_response.sa_geo(gm_response.drift_x >= d/100)),NaN]);
gm_table.(['sa_drift_z_' num2str(d)])(gm) = max([min(gm_response.sa_geo(gm_response.drift_z >= d/100)),NaN]);
end
end
% drift limit at mean rotation capacity
gm_table.sa_drift_mean_rot(gm) = max([min(gm_response.sa_geo(gm_response.max_drift >= gm_response.mean_rot_cap(1))),NaN]);
gm_table.sa_drift_mean_rot_grav(gm) = max([min(gm_response.sa_geo(gm_response.max_drift >= gm_response.mean_rot_cap_grav(1))),NaN]);
gm_table.sa_drift_mean_rot_grav_min(gm) = max([min(gm_response.sa_geo(gm_response.max_drift >= gm_response.mean_rot_cap_grav_min(1))),NaN]);
% grav load dcr
for f = 1:10
gm_table.(['sa_gravity_dcr_' num2str(f*10)])(gm) = max([min(gm_response.sa_geo(gm_response.gravity_dcr >= f/10)),NaN]);
end
% lateral cap remaining
for f = 1:9
gm_table.(['sa_lat_cap_any_' num2str(f*10)])(gm) = max([min(gm_response.sa_geo(gm_response.lat_cap_ratio_any < f/10)),NaN]);
gm_table.(['sa_lat_cap_both_' num2str(f*10)])(gm) = max([min(gm_response.sa_geo(gm_response.lat_cap_ratio_both < f/10)),NaN]);
gm_table.(['sa_lat_cap_max_' num2str(f*10)])(gm) = max([min(gm_response.sa_geo(gm_response.lat_cap_ratio_max < f/10)),NaN]);
end
% % adjacent components
% gm_set_table.sa_adjacent_component_any(gm) = max([min(gm_response.sa_geo(gm_response.adjacent_failure_any == 1)),NaN]);
% gm_set_table.sa_adjacent_component_any_frame(gm) = max([min(gm_response.sa_geo(gm_response.adjacent_failure_any_frame == 1)),NaN]);
% gm_set_table.sa_adjacent_component_all(gm) = max([min(gm_response.sa_geo(gm_response.adjacent_failure_all == 1)),NaN]);
%
% % Energy
% gm_table.collapse_energy(gm) = max([min(gm_response.total_energy_ft_lbs(gm_response.collapse == 1)),NaN]);
% for f = 1:length(frag_probs)
% gm_table.(['sa_collapse_energy_percent_' num2str(frag_probs(f))])(gm) = max([min(gm_response.sa_geo(gm_response.total_energy_ft_lbs/gm_table.collapse_energy(gm) >= frag_probs(f)/100)),NaN]);
% end
% non directional component fragilities
for p = 1:length(params)
gm_table.(['sa_first_' params{p}])(gm) = max([min(gm_response.sa_geo(gm_response.(['num_' params{p}]) > 0)),NaN]);
if any(strcmp(gm_response.collapse_direction,'x'))
gm_table.(['sa_first_' params{p} '_x'])(gm) = max([min(gm_response.sa_geo(gm_response.(['num_' params{p}]) > 0)),NaN]);
if analysis.run_z_motion
gm_table.(['sa_first_' params{p} '_z'])(gm) = NaN;
end
elseif any(strcmp(gm_response.collapse_direction,'z'))
gm_table.(['sa_first_' params{p} '_x'])(gm) = NaN;
gm_table.(['sa_first_' params{p} '_z'])(gm) = max([min(gm_response.sa_geo(gm_response.(['num_' params{p}]) > 0)),NaN]);
end
for pr = 1:length(frag_probs)
gm_table.(['sa_' num2str(frag_probs(pr)) '_percent_' params{p}])(gm) = max([min(gm_response.sa_geo(gm_response.(['percent_' params{p}]) >= frag_probs(pr)/100)),NaN]);
if any(strcmp(gm_response.collapse_direction,'x'))
gm_table.(['sa_' num2str(frag_probs(pr)) '_percent_' params{p} '_x'])(gm) = max([min(gm_response.sa_geo(gm_response.(['percent_' params{p}]) >= frag_probs(pr)/100)),NaN]);
if analysis.run_z_motion
gm_table.(['sa_' num2str(frag_probs(pr)) '_percent_' params{p} '_z'])(gm) = NaN;
end
elseif any(strcmp(gm_response.collapse_direction,'z'))
gm_table.(['sa_' num2str(frag_probs(pr)) '_percent_' params{p} '_x'])(gm) = NaN;
gm_table.(['sa_' num2str(frag_probs(pr)) '_percent_' params{p} '_z'])(gm) = max([min(gm_response.sa_geo(gm_response.(['percent_' params{p}]) >= frag_probs(pr)/100)),NaN]);
end
end
end
% % X direction Curves
% gm_set_table.sa_collapse_x(gm) = max([min(gm_response.sa_geo(strcmp(gm_response.collapse_direction,'x'))),NaN]);
% for p = 1:length(params)
% if any(strcmp(gm_response.collapse_direction,'x'))
% gm_set_table.(['sa_cols_1_first_' params{p}])(gm) = max([min(gm_response.sa_geo(gm_response.(['cols_1_num_' params{p}]) > 0)),NaN]);
% else
% gm_set_table.(['sa_cols_1_first_' params{p}])(gm) = NaN;
% end
% for pr = 1:length(frag_probs)
% if any(strcmp(gm_response.collapse_direction,'x'))
% gm_set_table.(['sa_cols_1_' num2str(frag_probs(pr)) '_percent_' params{p}])(gm) = max([min(gm_response.sa_geo(gm_response.(['cols_1_percent_' params{p}]) >= frag_probs(pr)/100)),NaN]);
% else
% gm_set_table.(['sa_cols_1_' num2str(frag_probs(pr)) '_percent_' params{p}])(gm) = NaN;
% end
% end
% end
%
%
% % Z direction curves
% if analysis.run_z_motion
% gm_set_table.sa_collapse_z(gm) = max([min(gm_response.sa_geo(strcmp(gm_response.collapse_direction,'z'))),NaN]);
% for p = 1:length(params)
% gm_set_table.(['sa_walls_1_first_' params{p}])(gm) = max([min(gm_response.sa_geo(gm_response.(['walls_1_num_' params{p}]) > 0)),NaN]);
% for pr = 1:length(frag_probs)
% gm_set_table.(['sa_walls_1_' num2str(frag_probs(pr)) '_percent_' params{p}])(gm) = max([min(gm_response.sa_geo(gm_response.(['walls_1_percent_' params{p}]) >= frag_probs(pr)/100)),NaN]);
% end
% end
% end
end
% Save Tabular Results as CSVs
writetable(gm_table,[write_dir filesep 'gm_table.csv'])
%% Create Fragility Curves based on Baker MLE (traditional Fragilities)
% collape and unnacceptable response
[frag_curves.collapse] = fn_fit_fragility_MOM(gm_table.sa_collapse);
[frag_curves.collapse_drift] = fn_fit_fragility_MOM(gm_table.sa_collapse_drift);
[frag_curves.collapse_drift_6] = fn_fit_fragility_MOM(gm_table.sa_collapse_drift_6);
[frag_curves.collapse_grav] = fn_fit_fragility_MOM(gm_table.sa_collapse_grav);
[frag_curves.collapse_2] = fn_fit_fragility_MOM(gm_table.sa_collapse_2);
[frag_curves.collapse_x] = fn_fit_fragility_MOM(gm_table.sa_collapse_x);
[frag_curves.collapse_2_x] = fn_fit_fragility_MOM(gm_table.sa_collapse_2_x);
[frag_curves.collapse_convergence] = fn_fit_fragility_MOM(gm_table.sa_collapse_convergence);
[frag_curves.UR_accept_15] = fn_fit_fragility_MOM(gm_table.sa_UR_accept_15);
[frag_curves.UR] = fn_fit_fragility_MOM(gm_table.sa_UR);
if analysis.run_z_motion
[frag_curves.collapse_z] = fn_fit_fragility_MOM(gm_table.sa_collapse_z);
[frag_curves.collapse_2_z] = fn_fit_fragility_MOM(gm_table.sa_collapse_2_z);
end
% non directional component fragilities
for p = 1:length(params)
[frag_curves.(params{p})] = fn_multi_frag_curves(gm_table, params{p}, '', frag_probs, ida_table.num_comps(1));
if analysis.run_z_motion
[frag_curves.([params{p} '_x'])] = fn_multi_frag_curves(gm_table, params{p}, '_x', frag_probs, ida_table.num_comps(1));
[frag_curves.([params{p} '_z'])] = fn_multi_frag_curves(gm_table, params{p}, '_z', frag_probs, ida_table.num_comps(1));
end
end
% 1% to 5% drift fragilities
for d = 1:10
[frag_curves.drift.(['idr_' num2str(d)])] = fn_fit_fragility_MOM(gm_table.(['sa_drift_' num2str(d)]));
if analysis.run_z_motion
[frag_curves.drift.(['idr_x_' num2str(d)])] = fn_fit_fragility_MOM(gm_table.(['sa_drift_x_' num2str(d)]));
[frag_curves.drift.(['idr_z_' num2str(d)])] = fn_fit_fragility_MOM(gm_table.(['sa_drift_z_' num2str(d)]));
end
end
% Drift limit at mean deformation capacity
[frag_curves.drift.idr_mean_rot] = fn_fit_fragility_MOM(gm_table.sa_drift_mean_rot);
[frag_curves.drift.idr_mean_rot_grav] = fn_fit_fragility_MOM(gm_table.sa_drift_mean_rot_grav);
[frag_curves.drift.idr_mean_rot_grav_min] = fn_fit_fragility_MOM(gm_table.sa_drift_mean_rot_grav_min);
% grav dcr
for f = 1:10
[frag_curves.gravity.(['dcr_' num2str(f*10)])] = fn_fit_fragility_MOM(gm_table.(['sa_gravity_dcr_' num2str(f*10)]));
end
% lat cap
for f = 1:9
[frag_curves.lateral.(['cap_any_' num2str(f*10)])] = fn_fit_fragility_MOM(gm_table.(['sa_lat_cap_any_' num2str(f*10)]));
[frag_curves.lateral.(['cap_both_' num2str(f*10)])] = fn_fit_fragility_MOM(gm_table.(['sa_lat_cap_both_' num2str(f*10)]));
[frag_curves.lateral.(['cap_max_' num2str(f*10)])] = fn_fit_fragility_MOM(gm_table.(['sa_lat_cap_max_' num2str(f*10)]));
end
% % adjacent components
% [frag_curves.adjacent_comp.any] = fn_fit_fragility_MOM(gm_set_table.sa_adjacent_component_any);
% [frag_curves.adjacent_comp.any_frame] = fn_fit_fragility_MOM(gm_set_table.sa_adjacent_component_any_frame);
% [frag_curves.adjacent_comp.all] = fn_fit_fragility_MOM(gm_set_table.sa_adjacent_component_all);
% % Collapse Energy
% for f = 1:length(frag_probs)
% [frag_curves.energy.(['percent_collapse_' num2str(frag_probs(f))])] = fn_fit_fragility_MOM(gm_table.(['sa_collapse_energy_percent_' num2str(frag_probs(f))]));
% end
% % X direction Curves
% [frag_curves.ew_collapse] = fn_fit_fragility_MOM(gm_set_table.sa_collapse_x);
% for p = 1:length(params)
% [frag_curves.cols_1.(params{p})] = fn_multi_frag_curves(gm_set_table, 'cols_1', params{p}, frag_probs, ida_table.num_comps_cols_1(1));
% end
%
% % Z direction curves
% if analysis.run_z_motion
% [frag_curves.ns_collapse] = fn_fit_fragility_MOM(gm_set_table.sa_collapse_z);
% for p = 1:length(params)
% [frag_curves.walls_1.(params{p})] = fn_multi_frag_curves(gm_set_table, 'walls_1', params{p}, frag_probs, ida_table.num_comps_walls_1(1));
% end
% end
% Save Frag Curve Data
save([write_dir filesep 'frag_curves.mat'],'frag_curves')
% Write outputs summary file
outputs.med_sa_collapse = frag_curves.collapse.theta;
outputs.med_sa_collapse_grav = frag_curves.collapse_2.theta;
outputs.med_sa_cp = frag_curves.cp.theta(1);
outputs.med_sa_cp_10 = frag_curves.cp.theta(frag_curves.cp.prct_mech == 0.1);
outputs.med_sa_cp_25 = frag_curves.cp.theta(find(frag_curves.cp.prct_mech == 0.25,1,'first'));
outputs.med_sa_cp_50 = frag_curves.cp.theta(find(frag_curves.cp.prct_mech == 0.5,1,'first'));
outputs.med_sa_cp_75 = frag_curves.cp.theta(find(frag_curves.cp.prct_mech == 0.75,1,'first'));
outputs.med_sa_b = frag_curves.b.theta(1);
outputs.collapse_margin = outputs.med_sa_collapse/outputs.med_sa_cp;
outputs.collapse_margin_grav = outputs.med_sa_collapse_grav/outputs.med_sa_cp;
outputs.collapse_margin_grav_b = outputs.med_sa_collapse_grav/outputs.med_sa_b;
outputs.num_comps = median(gm_data.collapse_2.num_cp);
outputs.percent_comps = median(gm_data.collapse_2.percent_cp);
outputs.num_full_col_fails = median(gm_data.collapse_2.num_full_col_fails);
outputs.drift = new_frag_curves.collapse_2.drift_x.theta;
outputs.med_sa_drift_2 = frag_curves.drift.idr_2.theta;
outputs.med_sa_drift_3 = frag_curves.drift.idr_3.theta;
outputs.med_sa_drift_4 = frag_curves.drift.idr_4.theta;
outputs.gravity_dcr = median(gm_data.collapse_2.gravity_dcr);
outputs.lat_cap_any = median(gm_data.collapse_2.lat_cap_ratio_any);
outputs.lat_cap_both = median(gm_data.collapse_2.lat_cap_ratio_both);
outputs.lat_cap_max = median(gm_data.collapse_2.lat_cap_ratio_max);
outputs.med_sa_lat_50 = frag_curves.lateral.cap_both_50.theta;
outputs.med_sa_lat_60 = frag_curves.lateral.cap_both_60.theta;
outputs.med_sa_lat_70 = frag_curves.lateral.cap_both_70.theta;
outputs.med_sa_lat_80 = frag_curves.lateral.cap_both_80.theta;
outputs.med_sa_lat_90 = frag_curves.lateral.cap_both_90.theta;
outputs.med_sa_grav_30 = frag_curves.gravity.dcr_30.theta;
outputs.med_sa_grav_40 = frag_curves.gravity.dcr_40.theta;
outputs.med_sa_grav_50 = frag_curves.gravity.dcr_50.theta;
outputs.med_sa_grav_60 = frag_curves.gravity.dcr_60.theta;
outputs.med_sa_grav_70 = frag_curves.gravity.dcr_70.theta;
outputs.med_sa_grav_80 = frag_curves.gravity.dcr_80.theta;
outputs.med_sa_drift_mean = frag_curves.drift.idr_mean_rot.theta;
outputs.med_sa_drift_mean_grav = frag_curves.drift.idr_mean_rot_grav.theta;
outputs.med_sa_drift_mean_grav_min = frag_curves.drift.idr_mean_rot_grav_min.theta;
if analysis.run_z_motion
outputs.med_sa_collapse_x = frag_curves.collapse_x.theta;
outputs.med_sa_collapse_z = frag_curves.collapse_z.theta;
outputs.med_sa_collapse_grav_x = frag_curves.collapse_2_x.theta;
outputs.med_sa_collapse_grav_z = frag_curves.collapse_2_z.theta;
outputs.med_sa_cp_x = frag_curves.cp_x.theta(1);
outputs.med_sa_cp_z = frag_curves.cp_z.theta(1);
end
writetable(struct2table(outputs),[write_dir filesep 'summary_outputs.csv'])
end
function [params] = fn_fit_fragility_MOM(limit_state_dist)
limit_state_dist(isnan(limit_state_dist)) = [];
limit_state_dist(limit_state_dist <= 0) = 1e-6;
if ~isempty(limit_state_dist)
[pHat, ~] = lognfit(limit_state_dist);
params.theta = exp(pHat(1));
params.beta = pHat(2);
else
params.theta = NaN;
params.beta = NaN;
end
end
function [frag_curves] = fn_multi_frag_curves(gm_set_table, param, dir, frag_probs, num_comp_mech)
frag_curves = table;
frag_curves.num_comp(1) = 1;
frag_curves.prct_mech(1) = round(1/num_comp_mech,3);
[fits] = fn_fit_fragility_MOM(gm_set_table.(['sa_' 'first_' param dir]));
frag_curves.theta(1) = fits.theta;
frag_curves.beta(1) = fits.beta;
for pr = 1:length(frag_probs)
frag_curves.num_comp(pr+1) = ceil(num_comp_mech*frag_probs(pr)/100);
frag_curves.prct_mech(pr+1) = frag_probs(pr)/100;
[fits] = fn_fit_fragility_MOM(gm_set_table.(['sa_' num2str(frag_probs(pr)) '_percent_' param dir]));
frag_curves.theta(pr+1) = fits.theta;
frag_curves.beta(pr+1) = fits.beta;
end
end
|
github
|
dustin-cook/Opensees-master
|
fn_plot_element_scatter.m
|
.m
|
Opensees-master/+plotting_tools/fn_plot_element_scatter.m
| 17,661 |
utf_8
|
a1b10c01814b77664a7808663903e84d
|
function [ ] = fn_plot_element_scatter( element, ele_type, story, hinge, write_dir )
% Description: Fn to create scatter plots of hinge acceptance results
% Created By: Dustin Cook
% Date Created: 3/11/2019
% Inputs:
% Outputs:
% Assumptions:
%% Initial Setup
% Define Plot Dir
plot_dir = [write_dir filesep 'Scatter Plots'];
%% Begin Method
for s = 1:height(story)
story_id = story.id(s);
ele_story = element(element.story == story_id,:);
% Elements of one type
ele = ele_story(strcmp(ele_story.type,ele_type),:);
ele2use = ele(ele.length >= 89,:); % Omit the nubs on the end of the frame (improve the way I am doing this)
hins = hinge(ismember(hinge.element_id,ele2use.id),:);
% Primary Direction
prim_hin = hins(strcmp(hins.direction,'primary'),:);
if ~isempty(prim_hin)
side_1 = prim_hin(prim_hin.ele_side == 1,:);
side_2 = prim_hin(prim_hin.ele_side == 2,:);
if strcmp(ele_type,'wall')
if any(strcmp('d_ratio',side_1.Properties.VariableNames))
plot_name = ['d ratio - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'd_ratio', 'Max(\Delta)/"d"', ele_type )
end
else
% a ratio
if any(strcmp('a_ratio',side_1.Properties.VariableNames))
plot_name = ['a ratio - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
plot_name = ['a ratio - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
end
% b ratio
if any(strcmp('b_ratio',side_1.Properties.VariableNames))
plot_name = ['b ratio - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
plot_name = ['b ratio - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
end
end
% V ratio
plot_name = ['V ratio - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
if ~strcmp(ele_type,'wall')
plot_name = ['V ratio - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
end
% M ratio
if any(strcmp('M_ratio_pos',side_1.Properties.VariableNames))
plot_name = ['M ratio - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'M_ratio_pos', 'Max(M)/Mn', ele_type )
if ~strcmp(ele_type,'wall')
plot_name = ['M ratio - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'M_ratio_pos', 'Max(M)/Mn', ele_type )
end
end
if any(strcmp('M_ratio',side_1.Properties.VariableNames))
plot_name = ['M ratio - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'M_ratio', 'Max(M)/Mn', ele_type )
if ~strcmp(ele_type,'wall')
plot_name = ['M ratio - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'M_ratio', 'Max(M)/Mn', ele_type )
end
end
% Linear DCRs
if any(strcmp('V_ratio_mod',side_1.Properties.VariableNames))
% Modified Demands
plot_name = ['V ratio mod - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio_mod', 'Max(V)/V_n', ele_type )
plot_name = ['V ratio mod - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'V_ratio_mod', 'Max(V)/V_n', ele_type )
plot_name = ['M ratio mod - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'M_ratio_mod', 'Max(M)/M_n', ele_type )
plot_name = ['M ratio mod - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'M_ratio_mod', 'Max(M)/M_n', ele_type )
% Acceptance DCRs
plot_name = ['DCR V Accept CP - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio_accept_cp', 'Max(V)/V_n', ele_type )
plot_name = ['DCR V Accept CP - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'V_ratio_accept_cp', 'Max(V)/V_n', ele_type )
plot_name = ['DCR M Accept CP - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'M_ratio_accept_cp', 'Max(M)/M_n', ele_type )
plot_name = ['DCR M Accept CP - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'M_ratio_accept_cp', 'Max(M)/M_n', ele_type )
plot_name = ['DCR P Accept CP - Primary - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'P_ratio_accept_cp', 'Max(P)/M_n', ele_type )
plot_name = ['DCR P Accept CP - Primary - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'P_ratio_accept_cp', 'Max(P)/M_n', ele_type )
end
end
% OOP Direction
oop_hin = hins(strcmp(hins.direction,'oop'),:);
if ~isempty(oop_hin)
side_1 = oop_hin(oop_hin.ele_side == 1,:);
side_2 = oop_hin(oop_hin.ele_side == 2,:);
if strcmp(ele_type,'wall')
% a ratio
plot_name = ['a ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
% b ratio
plot_name = ['b ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
% V ratio
plot_name = ['V ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
% M ratio
plot_name = ['M ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'M_ratio_pos', 'Max(M)/Mn', ele_type )
else
% a ratio
plot_name = ['a ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
plot_name = ['a ratio - OOP - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
% b ratio
plot_name = ['b ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
plot_name = ['b ratio - OOP - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
% V ratio
plot_name = ['V ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
plot_name = ['V ratio - OOP - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
% M ratio
plot_name = ['M ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'M_ratio_pos', 'Max(M)/Mn', ele_type )
plot_name = ['M ratio - OOP - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'M_ratio_pos', 'Max(M)/Mn', ele_type )
end
end
% SRSS Direction
srss_hin = hins(strcmp(hins.direction,'primary'),:);
srss_hin_oop = hins(strcmp(hins.direction,'oop'),:);
if ~isempty(srss_hin) && ~isempty(srss_hin_oop)
plot_name = ['SRSS - ' 'Story - ' num2str(story_id) ' - ' ele_type];
srss_hin.a_ratio = sqrt(srss_hin.a_ratio.^2 + srss_hin_oop.a_ratio.^2);
srss_hin.b_ratio = sqrt(srss_hin.b_ratio.^2 + srss_hin_oop.b_ratio.^2);
srss_hin.V_ratio = sqrt(srss_hin.V_ratio.^2 + srss_hin_oop.V_ratio.^2);
clear srss_names
[srss_names{1:height(srss_hin)}] = deal('SRSS');
srss_hin.direction = srss_names';
side_1 = srss_hin(srss_hin.ele_side == 1,:);
side_2 = srss_hin(srss_hin.ele_side == 2,:);
if strcmp(ele_type,'wall')
% V ratio
plot_name = ['V ratio - OOP - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
else
% a ratio
plot_name = ['a ratio - SRSS - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
plot_name = ['a ratio - SRSS - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'a_ratio', 'Max(\theta)/"a"', ele_type )
% b ratio
plot_name = ['b ratio - SRSS - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
plot_name = ['b ratio - SRSS - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'b_ratio', 'Max(\theta)/"b"', ele_type )
% V ratio
plot_name = ['V ratio - SRSS - Side 1 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_1, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
plot_name = ['V ratio - SRSS - Side 2 - Story - ' num2str(story_id) ' - ' ele_type];
fn_plot_results_scatter( side_2, plot_dir, plot_name, 'V_ratio', 'Max(V)/Vn', ele_type )
end
end
end
function [ ] = fn_plot_results_scatter( data, plot_dir, plot_name, target, y_lab, ele_type )
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
% Import Packages
import plotting_tools.fn_format_and_save_plot
% Matlab colors
matlab_colors = [0, 0.4470, 0.7410;
0.8500, 0.3250, 0.0980;
0.9290, 0.6940, 0.1250;
0.4940, 0.1840, 0.5560;
0.4660, 0.6740, 0.1880;
0.3010, 0.7450, 0.9330;
0.6350, 0.0780, 0.1840];
if strcmp(data.direction(1),'SRSS')
plt_color = [0 0 0];
elseif strcmp(data.direction(1),'primary')
if strcmp(data.ele_direction(1),'x')
plt_color = matlab_colors(2,:);
elseif strcmp(data.ele_direction(1),'z')
plt_color = matlab_colors(1,:);
end
elseif strcmp(data.direction(1),'oop')
if strcmp(data.ele_direction(1),'x')
plt_color = matlab_colors(1,:);
elseif strcmp(data.ele_direction(1),'z')
plt_color = matlab_colors(2,:);
end
end
ele_nums = 1:height(data);
% Plot Scatter
hold on
plot([0.5,height(data)+0.5],[1,1],'--k')
scatter(ele_nums(data.damage_recorded >= 2),data.(target)(data.damage_recorded >= 2), 50, plt_color, 's', 'filled' )
scatter(ele_nums(data.damage_recorded <= 1),data.(target)(data.damage_recorded <= 1), 50, plt_color, 's' )
ylabel(y_lab)
xlim([0.5,height(data)+0.5])
ylim([0, inf])
xlabel([ele_type ' #'])
box on
set(gcf,'position',[200, 500, 350, 300]);
fn_format_and_save_plot( plot_dir, plot_name, 0 )
% % B or E Ratio
% subplot(3,1,2)
% hold on
% plot([0.5,height(data)+height(side_2)+0.5],[1,1],'--k')
% if strcmp(ele_type,'wall') && strcmp(direction,'primary')
% scatter(ele_nums(data.damage_recorded == 3),data.e_ratio(data.damage_recorded == 3), 'o', 'filled', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
% scatter(ele_nums(data.damage_recorded == 2),data.e_ratio(data.damage_recorded == 2), 'o', 'filled', 'MarkerEdgeColor', [1 0.5 0], 'MarkerFaceColor', [1 0.5 0] )
% scatter(ele_nums(data.damage_recorded == 1),data.e_ratio(data.damage_recorded == 1), 'o', 'filled', 'MarkerEdgeColor', 'c', 'MarkerFaceColor', 'c' )
% scatter(ele_nums(data.damage_recorded == 0),data.e_ratio(data.damage_recorded == 0), 'o', 'filled', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b' )
% scatter(side_2_id(side_2.damage_recorded == 3),side_2.e_ratio(side_2.damage_recorded == 3), 'd', 'filled', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
% scatter(side_2_id(side_2.damage_recorded == 2),side_2.e_ratio(side_2.damage_recorded == 2), 'd', 'filled', 'MarkerEdgeColor', [1 0.5 0], 'MarkerFaceColor', [1 0.5 0] )
% scatter(side_2_id(side_2.damage_recorded == 1),side_2.e_ratio(side_2.damage_recorded == 1), 'd', 'filled', 'MarkerEdgeColor', 'c', 'MarkerFaceColor', 'c' )
% scatter(side_2_id(side_2.damage_recorded == 0),side_2.e_ratio(side_2.damage_recorded == 0), 'd', 'filled', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b' )
% ylabel('Max(\Delta)/"e"')
% else
% scatter(ele_nums(data.damage_recorded == 3),data.b_ratio(data.damage_recorded == 3), 'o', 'filled', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
% scatter(ele_nums(data.damage_recorded == 2),data.b_ratio(data.damage_recorded == 2), 'o', 'filled', 'MarkerEdgeColor', [1 0.5 0], 'MarkerFaceColor', [1 0.5 0] )
% scatter(ele_nums(data.damage_recorded == 1),data.b_ratio(data.damage_recorded == 1), 'o', 'filled', 'MarkerEdgeColor', 'c', 'MarkerFaceColor', 'c' )
% scatter(ele_nums(data.damage_recorded == 0),data.b_ratio(data.damage_recorded == 0), 'o', 'filled', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b' )
% scatter(side_2_id(side_2.damage_recorded == 3),side_2.b_ratio(side_2.damage_recorded == 3), 'd', 'filled', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
% scatter(side_2_id(side_2.damage_recorded == 2),side_2.b_ratio(side_2.damage_recorded == 2), 'd', 'filled', 'MarkerEdgeColor', [1 0.5 0], 'MarkerFaceColor', [1 0.5 0] )
% scatter(side_2_id(side_2.damage_recorded == 1),side_2.b_ratio(side_2.damage_recorded == 1), 'd', 'filled', 'MarkerEdgeColor', 'c', 'MarkerFaceColor', 'c' )
% scatter(side_2_id(side_2.damage_recorded == 0),side_2.b_ratio(side_2.damage_recorded == 0), 'd', 'filled', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b' )
% ylabel('Max(\theta)/"b"')
% end
% set(gca,'XTickLabel',[])
% xlim([0.5,height(data)+height(side_2)+0.5])
% ylim([0, inf])
% fn_format_and_save_plot( plot_dir, plot_name, 2, 0 )
%
% % V Ratio
% subplot(3,1,3)
% hold on
% plot([0.5,height(data)+height(side_2)+0.5],[1,1],'--k')
% scatter(ele_nums(data.damage_recorded == 3),data.V_ratio(data.damage_recorded == 3), 'o', 'filled', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
% scatter(ele_nums(data.damage_recorded == 2),data.V_ratio(data.damage_recorded == 2), 'o', 'filled', 'MarkerEdgeColor', [1 0.5 0], 'MarkerFaceColor', [1 0.5 0] )
% scatter(ele_nums(data.damage_recorded == 1),data.V_ratio(data.damage_recorded == 1), 'o', 'filled', 'MarkerEdgeColor', 'c', 'MarkerFaceColor', 'c' )
% scatter(ele_nums(data.damage_recorded == 0),data.V_ratio(data.damage_recorded == 0), 'o', 'filled', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b' )
% scatter(side_2_id(side_2.damage_recorded == 3),side_2.V_ratio(side_2.damage_recorded == 3), 'd', 'filled', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r' )
% scatter(side_2_id(side_2.damage_recorded == 2),side_2.V_ratio(side_2.damage_recorded == 2), 'd', 'filled', 'MarkerEdgeColor', [1 0.5 0], 'MarkerFaceColor', [1 0.5 0] )
% scatter(side_2_id(side_2.damage_recorded == 1),side_2.V_ratio(side_2.damage_recorded == 1), 'd', 'filled', 'MarkerEdgeColor', 'c', 'MarkerFaceColor', 'c' )
% scatter(side_2_id(side_2.damage_recorded == 0),side_2.V_ratio(side_2.damage_recorded == 0), 'd', 'filled', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b' )
% xlabel([upper(ele_type(1)) ele_type(2:end) 's'])
% ylabel('Max(V)/Vn')
% xlim([0.5,height(data)+height(side_2)+0.5])
% ylim([0, inf])
% fn_format_and_save_plot( plot_dir, plot_name, 2, 1 )
end
end
|
github
|
dustin-cook/Opensees-master
|
fn_plot_edp_profiles.m
|
.m
|
Opensees-master/+plotting_tools/fn_plot_edp_profiles.m
| 6,536 |
utf_8
|
a3f4545e519f61100c5c3676eadb551c
|
function [ ] = fn_plot_edp_profiles( plot_dir, ground_motion, story, target_disp_in, record_edp )
% Description: Fn to plot edp profiles of the analysis
% Created By: Dustin Cook
% Date Created: 1/7/2019
% Inputs:
% Outputs:
% Assumptions:
%% Initial Setup
% Plot Directory
edp_plot_dir = [plot_dir filesep 'EDP Profiles'];
%% Caclulate Profiles
% X accels
if any(strcmp('max_accel_x',story.Properties.VariableNames))
edp_accel_x = [ground_motion.x.pga; story.max_accel_x];
% edp_accel_x_center = [ground_motion.x.pga; story.max_accel_center_x];
end
% X disps
edp_disp_x = [0; story.max_disp_x];
% edp_disp_x_center = [0; story.max_disp_center_x];
if any(strcmp('max_disp_x_mod',story.Properties.VariableNames))
edp_mods.max_disp.x = [0; story.max_disp_x_mod];
% edp_mods.max_disp_center.x = [0; story.max_disp_center_x_mod];
else
edp_mods.max_disp = [];
% edp_mods.max_disp_center = [];
end
% Z direction
if isfield(ground_motion,'z')
% Z accels
if any(strcmp('max_accel_z',story.Properties.VariableNames))
edp_accel_z = [ground_motion.z.pga; story.max_accel_z];
% edp_accel_z_center = [ground_motion.z.pga; story.max_accel_center_z];
end
% Z disps
edp_disp_z = [0; story.max_disp_z];
edp_disp_z_center = [0; story.max_disp_center_z];
if ismember('max_twist_z',story.Properties.VariableNames)
edp_disp_z_twist = [0; story.max_twist_z];
else
edp_disp_z_twist = [];
end
if any(strcmp('max_disp_z_mod',story.Properties.VariableNames))
edp_mods.max_disp.z = [0; story.max_disp_z_mod];
edp_mods.max_disp_center.z = [0; story.max_disp_center_z_mod];
end
else
edp_accel_z = [];
% edp_accel_z_center = [];
edp_disp_z = [];
% edp_disp_z_center = [];
edp_disp_z_twist = [];
end
if isempty(record_edp)
record_edp.max_accel = [];
% record_edp.max_accel_center = [];
record_edp.max_disp = [];
% record_edp.max_disp_center = [];
record_edp.max_twist = [];
end
%% Plot Profiles
% Acceleration
if any(strcmp('max_accel_x',story.Properties.VariableNames))
fn_plot_profile( edp_accel_x, edp_accel_z, [min(story.id);(story.id+1)], edp_plot_dir, 'Acceleration Profile', 'Acceleration (g)', NaN, record_edp.max_accel, [])
% fn_plot_profile( edp_accel_x_center, edp_accel_z_center, [min(story.id);(story.id+1)], edp_plot_dir, 'Acceleration Profile Center', 'Acceleration (g)', NaN, record_edp.max_accel_center, [])
end
% Displacement
fn_plot_profile( edp_disp_x, edp_disp_z, [min(story.id);(story.id+1)], edp_plot_dir, 'Displacement Profile', 'Displacement (in)', target_disp_in, record_edp.max_disp, edp_mods.max_disp)
% if ~any(isnan(edp_disp_x_center))
% fn_plot_profile( edp_disp_x_center, edp_disp_z_center, [min(story.id);(story.id+1)], edp_plot_dir, 'Displacement Profile Center', 'Displacement (in)', target_disp_in, record_edp.max_disp_center, edp_mods.max_disp_center)
% end
% Drift
if isfield(ground_motion,'z')
fn_plot_profile( story.max_drift_x, story.max_drift_z, story.id, edp_plot_dir, 'Drift Profile', 'Interstory Drift', NaN, [], [] )
else
fn_plot_profile( story.max_drift_x, [], story.id, edp_plot_dir, 'Drift Profile', 'Interstory Drift', NaN, [], [] )
end
% Twist
if ~isempty(edp_disp_z_twist)
fn_plot_profile( [], edp_disp_z_twist, [min(story.id);(story.id+1)], edp_plot_dir, 'Twist Profile', 'Twist (in)', NaN, record_edp.max_twist, [])
end
end
function [ ] = fn_plot_profile( profile_x, profile_z, story_ids, plot_dir, plot_name, name, target_disp, recording, mod_profile )
%UNTITLED9 Summary of this function goes here
% Detailed explanation goes here
%% Initial Setup
% Import Packages
import plotting_tools.*
% Define Colors
matlab_colors = [0, 0.4470, 0.7410;
0.8500, 0.3250, 0.0980;
0.9290, 0.6940, 0.1250;
0.4940, 0.1840, 0.5560;
0.4660, 0.6740, 0.1880;
0.3010, 0.7450, 0.9330;
0.6350, 0.0780, 0.1840];
%% NS Plot
if ~isempty(profile_z)
if strcmp(name,'Interstory Drift') || strcmp(name,'Twist (in)')
subplot(1,2,1)
else
subplot(1,3,1)
end
hold on
max_data = ceil(120*max(profile_z))/100;
% Plot Extra data
if ~isempty(recording)
plot(recording.z(~isnan(recording.z)),story_ids(~isnan(recording.z)),'k--o','MarkerFaceColor','k','DisplayName','Recorded')
max_data = ceil(1.2*max([profile_z;recording.z]));
end
if ~isempty(mod_profile)
plot(mod_profile.z,story_ids,'--','color',matlab_colors(1,:),'linewidth',1.5,'DisplayName','Linear Modifications')
end
% Plot main profile
plot(profile_z,story_ids,'color',matlab_colors(1,:),'linewidth',1.5,'DisplayName','Analysis')
% Add target dispalcement
if isstruct(target_disp)
scatter(target_disp.z,max(story_ids),75,matlab_colors(1,:),'*','DisplayName','Target Displacement')
end
xlabel(['NS ' name])
if strcmp(name,'Interstory Drift')
ylabel('Story')
else
ylabel('Floor Level')
end
xlim([0,max_data])
ylim([min(story_ids),max(story_ids)])
yticks(story_ids)
% legend('location','northwest')
% legend boxoff
box on
% Subplot space for EW plot
if strcmp(name,'Interstory Drift')
subplot(1,2,2)
elseif ~strcmp(name,'Twist (in)')
subplot(1,3,2)
end
end
%% EW Plot
if ~isempty(profile_x)
hold on
max_data = ceil(120*max(profile_x))/100;
% Additional data
if ~isempty(recording)
plot(recording.x(~isnan(recording.x)),story_ids(~isnan(recording.x)),'k--o','MarkerFaceColor','k','DisplayName','Recorded')
max_data = ceil(1.2*max([profile_x;recording.x]));
end
if ~isempty(mod_profile)
plot(mod_profile.x,story_ids,'--','color',matlab_colors(2,:),'linewidth',1.5,'DisplayName','Linear Modifications')
end
% Main data
plot(profile_x,story_ids,'color',matlab_colors(2,:),'linewidth',1.5,'DisplayName','Analysis')
% Add target dispalcement
if isstruct(target_disp)
scatter(target_disp.x,max(story_ids),75,matlab_colors(2,:),'*','DisplayName','Target Displacement')
end
xlabel(['EW ' name])
xlim([0,max_data])
ylim([min(story_ids),max(story_ids)])
yticks(story_ids)
box on
end
if ~strcmp(name,'Interstory Drift')
hL = legend('location','east');
legend boxoff
set(hL,'Position', [0.52 0.48 0.52 0.1])
end
fn_format_and_save_plot( plot_dir, plot_name, 0 )
end
|
github
|
dustin-cook/Opensees-master
|
fn_plot_elevation.m
|
.m
|
Opensees-master/+plotting_tools/fn_plot_elevation.m
| 6,476 |
utf_8
|
9b84969410cca7b0f170e082d2dc078f
|
function [ ] = fn_plot_elevation( hinge_or_joint, element, node, elev_title, plot_dir, direction, x_start, x_end, z_start, z_end )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
if strcmp(direction,'x')
type_filter = ~strcmp(element.type,'wall');
elseif strcmp(direction,'z')
type_filter = strcmp(element.type,'wall');
end
% Filter Elements
count = 0;
for i = 1:length(element.id)
if (node.z(node.id == element.node_1(i)) >= z_start) && (node.z(node.id == element.node_1(i)) <= z_end) &&(node.x(node.id == element.node_1(i)) >= x_start) && (node.x(node.id == element.node_1(i)) <= x_end)
if (node.z(node.id == element.node_2(i)) >= z_start) && (node.z(node.id == element.node_2(i)) <= z_end) && (node.x(node.id == element.node_2(i)) >= x_start) && (node.x(node.id == element.node_2(i)) <= x_end)
if type_filter(i)
count = count + 1;
ele(count,:) = element(i,:);
ele_new.id(count) = ele.id(count);
ele_new.old_node_1(count) = ele.node_1(count);
ele_new.old_node_2(count) = ele.node_2(count);
ele_new.node_1(count) = count*2-1;
ele_new.node_2(count) = count*2;
new_node.id(count*2-1) = count*2-1;
new_node.id(count*2) = count*2;
new_node.x(count*2-1) = node.x(node.id == ele.node_1(count));
new_node.x(count*2) = node.x(node.id == ele.node_2(count));
new_node.y(count*2-1) = node.y(node.id == ele.node_1(count));
new_node.y(count*2) = node.y(node.id == ele.node_2(count));
new_node.z(count*2-1) = node.z(node.id == ele.node_1(count));
new_node.z(count*2) = node.z(node.id == ele.node_2(count));
end
end
end
end
% Define Colors
cmap1 = [0, 114, 189;
238 235 112;
252 160 98;
241 95 95]/255;
cmap2 = [0,60,48;
1,102,94;
53,151,143;
128,205,193;
199,234,229;
246,232,195;
223,194,125;
191,129,45;
140,81,10;
84,48,5]/255;
cmap3 = [0, 114, 189;
241 95 95]/255;
%% Plot DCR on elevation of building
if contains(elev_title,'Joint')
plot_joint_elevation(ele_new, direction, new_node, hinge_or_joint, cmap1, 4, plot_dir, ['ASCE 41 Acceptance - ' elev_title], 'accept', node)
plot_joint_elevation(ele_new, direction, new_node, hinge_or_joint, cmap3, 1, plot_dir, ['Yield Check - ' elev_title], 'yield', node)
else
plot_elevation(ele_new, direction, new_node, hinge_or_joint, cmap1, 4, plot_dir, ['ASCE 41 Acceptance - ' elev_title], 'accept')
if any(strcmp('b_ratio',hinge_or_joint.Properties.VariableNames))
plot_elevation(ele_new, direction, new_node, hinge_or_joint, cmap2, 1, plot_dir, ['b Hinge Rotation - ' elev_title], 'b_ratio')
end
end
function [] = plot_elevation(ele_new, direction, new_node, hinge, cmap, cmap_max, plot_dir, plot_name, target)
% Import Packages
import plotting_tools.*
% Graph structure
s = ele_new.node_1;
t = ele_new.node_2;
G = graph(s,t);
% Plot Graph
if strcmp(direction,'z')
x = new_node.z;
elseif strcmp(direction,'x')
x = new_node.x;
end
y = new_node.y;
H = plot(G,'XData',x,'YData',y,'NodeLabel',{});
axis off
%% Highlight Performance
% Highlight elemets that pass Acceptance Criteria
cmap_length = length(cmap(:,1));
for e = 1:length(ele_new.id)
hinges = hinge(hinge.element_id == ele_new.id(e) & strcmp(hinge.direction,'primary'),:);
for h = 1:height(hinges)
if any(strcmp('node',hinges.Properties.VariableNames))
hinge_new_node_1 = ele_new.node_1(ele_new.old_node_1 == hinges.node(h));
hinge_new_node_2 = ele_new.node_2(ele_new.old_node_2 == hinges.node(h));
hinge_new_node = max([hinge_new_node_1, hinge_new_node_2]);
else
hinge_new_node_1 = ele_new.node_1(ele_new.old_node_1 == hinges.node_1(h) | ele_new.old_node_1 == hinges.node_2(h));
hinge_new_node_2 = ele_new.node_2(ele_new.old_node_2 == hinges.node_1(h) | ele_new.old_node_1 == hinges.node_2(h));
hinge_new_node = max([hinge_new_node_1, hinge_new_node_2]);
end
cmap_idx = max([min([round(hinges.(target)(h)*cmap_length/cmap_max),cmap_length]),1]);
highlight(H,hinge_new_node) % Make hinge bigger
highlight(H,hinge_new_node,'NodeColor',cmap(cmap_idx,:)) % Highlight hinges
end
end
%% Format and save plot
title(plot_name)
fn_format_and_save_plot( plot_dir, plot_name, 4 )
end
function [] = plot_joint_elevation(ele_new, direction, new_node, joint, cmap, cmap_max, plot_dir, plot_name, target, node)
% Import Packages
import plotting_tools.*
% Graph structure
s = ele_new.node_1;
t = ele_new.node_2;
G = graph(s,t);
% Plot Graph
if strcmp(direction,'z')
x = new_node.z;
elseif strcmp(direction,'x')
x = new_node.x;
end
y = new_node.y;
H = plot(G,'XData',x,'YData',y,'NodeLabel',{});
axis off
%% Highlight Performance
% Highlight elemets that pass Acceptance Criteria
cmap_length = length(cmap(:,1));
hold on
for e = 1:length(ele_new.id)
jnt_1 = joint(joint.column_high == ele_new.id(e) | joint.beam_right == ele_new.id(e),:);
if ~isempty(jnt_1)
x_val = node.x(node.id == jnt_1.y_neg);
y_up = node.y(node.id == jnt_1.y_pos);
y_low = node.y(node.id == jnt_1.y_neg);
y_val = mean([y_up,y_low]);
cmap_idx = max([min([round(jnt_1.(target)*cmap_length/cmap_max),cmap_length]),1]);
scatter(x_val,y_val,100,cmap(cmap_idx,:),'filled','s')
% highlight(H,ele_new.node_1(e)) % Make hinge bigger
% highlight(H,ele_new.node_1(e),'NodeColor',cmap(cmap_idx,:)) % Highlight hinges
end
jnt_2 = joint(joint.column_low == ele_new.id(e) | joint.beam_left == ele_new.id(e),:);
if ~isempty(jnt_2)
x_val = node.x(node.id == jnt_2.y_neg);
y_up = node.y(node.id == jnt_2.y_pos);
y_low = node.y(node.id == jnt_2.y_neg);
y_val = mean([y_up,y_low]);
cmap_idx = max([min([round(jnt_2.(target)*cmap_length/cmap_max),cmap_length]),1]);
scatter(x_val,y_val,100,cmap(cmap_idx,:),'filled','s')
% highlight(H,ele_new.node_2(e)) % Make hinge bigger
% highlight(H,ele_new.node_2(e),'NodeColor',cmap(cmap_idx,:)) % Highlight hinges
end
end
%% Format and save plot
title(plot_name)
fn_format_and_save_plot( plot_dir, plot_name, 4 )
end
end
|
github
|
vedaldi/mcnSSD-master
|
compile_mcnSSD.m
|
.m
|
mcnSSD-master/compile_mcnSSD.m
| 3,094 |
utf_8
|
a129708c9a7b2fc9ab21ce9c6ee29a84
|
function compile_mcnSSD(varargin)
% COMPILE_MCNSSD compile the C++/CUDA components of the SSD Detector
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
tokens = {vl_rootnn, 'matlab', 'mex', '.build', 'last_compile_opts.mat'} ;
last_args_path = fullfile(tokens{:}) ; opts = {} ;
if exist(last_args_path, 'file'), opts = {load(last_args_path)} ; end
opts = selectCompileOpts(opts) ;
vl_compilenn(opts{:}, varargin{:}, 'preCompileFn', @preCompileFn) ;
% ------------------------------------------------------------------------
function [opts, mex_src, lib_src, flags] = preCompileFn(opts, mex_src, ...
lib_src, flags)
% ------------------------------------------------------------------------
mcn_root = vl_rootnn() ;
root = fullfile(fileparts(mfilename('fullpath')), 'matlab') ;
% Build inside the module path
flags.src_dir = fullfile(root, 'src') ;
flags.mex_dir = fullfile(root, 'mex') ;
flags.bld_dir = fullfile(flags.mex_dir, '.build') ;
implDir = fullfile(flags.bld_dir,'bits/impl') ;
if ~exist(implDir, 'dir'), mkdir(implDir) ; end
mex_src = {} ; lib_src = {} ;
if opts.enableGpu, ext = 'cu' ; else, ext = 'cpp' ; end
% Add mcn dependencies
lib_src{end+1} = fullfile(mcn_root, 'matlab/src/bits', ['data.' ext]) ;
lib_src{end+1} = fullfile(mcn_root, 'matlab/src/bits', ['datamex.' ext]) ;
lib_src{end+1} = fullfile(mcn_root,'matlab/src/bits/impl/copy_cpu.cpp') ;
if opts.enableGpu
lib_src{end+1} = fullfile(mcn_root,'matlab/src/bits/datacu.cu') ;
lib_src{end+1} = fullfile(mcn_root,'matlab/src/bits/impl/copy_gpu.cu') ;
end
% ----------------------
% include required files
% ----------------------
% old style include - leave as comment in case users have different setup
%if ~isfield(flags, 'cc'), flags.cc = {inc} ; else, flags.cc{end+1} = inc ; end
% new style include
inc = sprintf('-I"%s"', fullfile(mcn_root,'matlab','src')) ;
inc_local = sprintf('-I"%s"', fullfile(root, 'src')) ;
flags.base{end+1} = inc ; flags.base{end+1} = inc_local ;
% Add module files
lib_src{end+1} = fullfile(root,'src/bits',['nnmultiboxdetector.' ext]) ;
mex_src{end+1} = fullfile(root,'src',['vl_nnmultiboxdetector.' ext]) ;
% CPU-specific files
lib_src{end+1} = fullfile(root,'src/bits/impl/multiboxdetector_cpu.cpp') ;
% GPU-specific files
if opts.enableGpu
lib_src{end+1} = fullfile(root,'src/bits/impl/multiboxdetector_gpu.cu') ;
end
% -------------------------------------
function opts = selectCompileOpts(opts)
% -------------------------------------
keep = {'enableGpu', 'enableImreadJpeg', 'enableCudnn', 'enableDouble', ...
'imageLibrary', 'imageLibraryCompileFlags', ...
'imageLibraryLinkFlags', 'verbose', 'debug', 'cudaMethod', ...
'cudaRoot', 'cudaArch', 'defCudaArch', 'cudnnRoot', 'preCompileFn'} ;
s = opts{1} ;
f = fieldnames(s) ;
for i = 1:numel(f)
if ~ismember(f{i}, keep)
s = rmfield(s, f{i}) ;
end
end
opts = {s} ;
|
github
|
vedaldi/mcnSSD-master
|
ssd_evaluation.m
|
.m
|
mcnSSD-master/core/ssd_evaluation.m
| 12,198 |
utf_8
|
13583628f1b3f5c051fe580181a6d2db
|
function ssd_evaluation(expDir, net, opts)
% ----------------------------------------------------------------
% Prepare imdb
% ----------------------------------------------------------------
if exist(opts.dataOpts.imdbPath, 'file')
imdb = load(opts.dataOpts.imdbPath) ;
else
imdb = opts.dataOpts.getImdb(opts) ;
imdbDir = fileparts(opts.dataOpts.imdbPath) ;
if ~exist(imdbDir, 'dir')
mkdir(imdbDir) ;
end
save(opts.dataOpts.imdbPath, '-struct', 'imdb') ;
end
opts = opts.dataOpts.configureImdbOpts(expDir, opts) ;
switch opts.testset
case 'val'
setLabel = 2 ;
case 'test'
setLabel = 3 ;
end
testIdx = find(imdb.images.set == setLabel) ;
% ----------------------------------------------------------------
% Retrieve from caches if possible
% ----------------------------------------------------------------
rawPreds = checkCache('rawPreds', opts, net, imdb, testIdx) ;
decoded = checkCache('decodedPreds', opts, rawPreds, imdb, testIdx) ;
results = checkCache('results', opts, opts.modelName, decoded, imdb) ;
opts.dataOpts.displayResults(opts.modelName, results, opts) ;
% ------------------------------------------------
function res = checkCache(varname, opts, varargin)
% ------------------------------------------------
switch varname
case 'rawPreds'
path = opts.cacheOpts.rawPredsCache ;
flag = opts.cacheOpts.refreshPredictionCache ;
func = @computePredictions ;
case 'decodedPreds'
path = opts.cacheOpts.decodedPredsCache ;
flag = opts.cacheOpts.refreshDecodedPredCache ;
func = @decodePredictions ;
case 'results'
path = opts.cacheOpts.resultsCache ;
flag = opts.cacheOpts.refreshEvaluationCache ;
func = opts.dataOpts.eval_func ;
end
if exist(path, 'file') && ~flag
fprintf('loading %s from cache\n', varname) ;
tmp = load(path) ;
res = tmp.(varname) ;
else
s.(varname) = func(varargin{:}, opts) ;
save(path, '-struct', 's', '-v7.3') ;
res = s.(varname) ;
end
% -------------------------------------------------------------------------
function decodedPreds = decodePredictions(predictions, imdb, testIdx, opts)
% -------------------------------------------------------------------------
% For small datasets (e.g. just a few thousand frames), serial
% decoding tends to be faster
switch opts.dataOpts.decoder
case 'serial'
decodedPreds = decodeSerial(predictions, imdb, testIdx, opts) ;
case 'parallel'
decodedPreds = decodeParallel(predictions, imdb, testIdx, opts) ;
otherwise
error('deocoder %s not recognised (should be serial or parallel)', ...
opts.dataOpts.deocoder) ;
end
% -------------------------------------------------------------------------
function decodedPreds = decodeSerial(predictions, imdb, testIdx, opts)
% -------------------------------------------------------------------------
numClasses = numel(imdb.meta.classes) ;
% gather predictions by class, and store the corresponding
% image id (i.e. image name) and bouding boxes
imageIds = cell(1, numClasses) ;
scores = cell(1, numClasses) ;
bboxes = cell(1, numClasses) ;
for c = 1:numClasses
fprintf('extracting predictions for %s\n', imdb.meta.classes{c}) ;
for p = 1:numel(testIdx)
% add offset for background class (for compatibility with caffe)
target = c + 1 ;
% find predictions for current image
preds = predictions(:,:,:,p) ;
targetIdx = find(preds(:,1) == target) ;
pScores = preds(targetIdx, 2) ;
pBoxes = preds(targetIdx, 3:end) ;
% clip predictions to fall in image and scale the
% bounding boxes from [0,1] to absolute pixel values
if pBoxes
pBoxes = min(max(pBoxes, 0), 1) ;
imsz = single(imdb.images.imageSizes{testIdx(p)}) ;
switch opts.dataOpts.resultsFormat
case 'minMax'
pBoxes = [pBoxes(:,1) * imsz(2) ...
pBoxes(:,2) * imsz(1) ...
pBoxes(:,3) * imsz(2) ...
pBoxes(:,4) * imsz(1) ] ;
case 'minWH'
pBoxes = [pBoxes(:,1) * imsz(2) ...
pBoxes(:,2) * imsz(1) ...
(pBoxes(:,3) - pBoxes(:,1)) * imsz(2) ...
(pBoxes(:,4) - pBoxes(:,2)) * imsz(1) ] ;
end
% store results
pId = imdb.images.name{testIdx(p)} ;
scores{c} = vertcat(scores{c}, pScores) ;
bboxes{c} = vertcat(bboxes{c}, pBoxes) ;
imageIds{c} = vertcat(imageIds{c}, repmat({pId}, size(pScores))) ;
end
fprintf('extracting predictions for image %d/%d\n', p, numel(testIdx)) ;
end
end
decodedPreds.imageIds = imageIds ;
decodedPreds.scores = scores ;
decodedPreds.bboxes = bboxes ;
% -------------------------------------------------------------------------
function decodedPreds = decodeParallel(predictions, imdb, testIdx, opts)
% -------------------------------------------------------------------------
numClasses = numel(imdb.meta.classes) ;
% gather predictions by class, and store the corresponding
% image id (i.e. image name) and bouding boxes
imageIds = cell(1, numClasses) ;
scores = cell(1, numClasses) ;
bboxes = cell(1, numClasses) ;
% Use preallocation to enable parallel evaluation
predsPerIm = uint32(size(predictions, 1)) ;
numTotal = double(predsPerIm) * numel(testIdx) ;
for c = 1:numClasses
fprintf('extracting predictions for %s\n', opts.dataOpts.classes{c}) ;
% add offset for background class (for compatibility with caffe)
target = c + 1 ;
cBoxes = zeros(numTotal, 4, 'single') ;
cScores = zeros(numTotal, 1, 'single') ;
cImageIds = cell(numTotal, 1) ;
keep = false(numTotal, 1) ;
parfor p = 1:numTotal
offset = mod(p - 1, predsPerIm) + 1 ;
imId = idivide(p - 1, predsPerIm) + 1 ;
preds = predictions(offset,:,:,imId) ;
keep(p) = (preds(1) == target) ;
if ~keep(p)
continue
else
pScore = preds(2) ;
if pScore < opts.dataOpts.scoreThresh
keep(p) = false ;
continue
end
pBox = preds(3:end) ;
% clip predictions to fall in image and scale the
% bounding boxes from [0,1] to absolute pixel values
pBox = min(max(pBox, 0), 1) ;
imsz = single(imdb.images.imageSizes{testIdx(p)}) ;
switch opts.dataOpts.resultsFormat
case 'minMax'
pBox = [pBox(1) * imsz(2) ...
pBox(2) * imsz(1) ...
pBox(3) * imsz(2) ...
pBox(4) * imsz(1) ] ;
case 'minWH'
pBox = [pBox(1) * imsz(2) ...
pBox(2) * imsz(1) ...
(pBox(3) - pBox(1)) * imsz(2) ...
(pBox(4) - pBox(2)) * imsz(1) ] ;
end
% store results
cScores(p) = pScore ;
cBoxes(p,:) = pBox ;
cImageIds{p} = imdb.images.name{testIdx(imId)} ;
end
fprintf('extracting prediction %d/%d for %s\n', p, numTotal, ...
opts.dataOpts.classes{c}) ;
end
scores{c} = cScores(find(keep)) ;
bboxes{c} = cBoxes(find(keep),:) ;
imageIds{c} = cImageIds(find(keep)) ;
end
decodedPreds.imageIds = imageIds ;
decodedPreds.scores = scores ;
decodedPreds.bboxes = bboxes ;
% ------------------------------------------------------------------
function predictions = computePredictions(net, imdb, testIdx, opts)
% ------------------------------------------------------------------
prepareGPUs(opts, true) ;
if numel(opts.gpus) <= 1
state = processDetections(net, imdb, testIdx, opts) ;
predictions = state.predictions ;
else
predictions = zeros(200, 6, 1, numel(testIdx), 'single') ;
spmd
% resolve parallel path issue
addpath(fullfile(vl_rootnn, 'contrib/mcnSSD/matlab/mex')) ;
state = processDetections(net, imdb, testIdx, opts) ;
end
for i = 1:numel(opts.gpus)
state_ = state{i} ;
predictions(:,:,:,state_.computedIdx) = state_.predictions ;
end
end
% ------------------------------------------------------------------
function state = processDetections(net, imdb, testIdx, opts)
% ------------------------------------------------------------------
% benchmark speed
num = 0 ;
adjustTime = 0 ;
stats.time = 0 ;
stats.num = num ;
start = tic ;
% find the output predictions made by the network
outVars = net.getOutputs() ;
predVar = outVars{1} ;
% prepare to store network predictions
predIdx = net.getVarIndex(opts.modelOpts.predVar) ;
net.vars(predIdx).precious = true ;
if ~isempty(opts.gpus), net.move('gpu') ; end
% pre-compute the indices of the predictions made by each worker
startIdx = labindex:numlabs:opts.batchOpts.batchSize ;
idx = arrayfun(@(x) {x:opts.batchOpts.batchSize:numel(testIdx)}, startIdx) ;
computedIdx = sort(horzcat(idx{:})) ;
% top 200 preds kept
keepTopK = net.layers(net.getLayerIndex('detection_out')).block.keepTopK ;
state.predictions = zeros(keepTopK, 6, 1, numel(computedIdx), 'single') ;
state.computedIdx = computedIdx ;
offset = 1 ;
for t = 1:opts.batchOpts.batchSize:numel(testIdx)
% display progress
progress = fix((t-1) / opts.batchOpts.batchSize) + 1 ;
totalBatches = ceil(numel(testIdx) / opts.batchOpts.batchSize) ;
fprintf('evaluating batch %d / %d: ', progress, totalBatches) ;
batchSize = min(opts.batchOpts.batchSize, numel(testIdx) - t + 1) ;
batchStart = t + (labindex - 1) ;
batchEnd = min(t + opts.batchOpts.batchSize - 1, numel(testIdx)) ;
batch = testIdx(batchStart : numlabs : batchEnd) ;
num = num + numel(batch) ;
if numel(batch) == 0, continue ; end
inputs = opts.modelOpts.get_eval_batch(imdb, batch, opts) ;
if opts.prefetch
batchStart_ = t + (labindex - 1) + opts.batchOpts.batchSize ;
batchEnd_ = min(t + 2*opts.batchOpts.batchSize - 1, numel(testIdx)) ;
nextBatch = testIdx(batchStart_: numlabs : batchEnd_) ;
opts.modelOpts.get_eval_batch(imdb, nextBatch, opts, 'prefetch', true) ;
end
net.eval(inputs) ;
storeIdx = offset:offset + numel(batch) -1 ;
offset = offset + numel(batch) ;
state.predictions(:,:,:,storeIdx) = net.vars(predIdx).value ;
time = toc(start) + adjustTime ;
batchTime = time - stats.time ;
stats.num = num ;
stats.time = time ;
currentSpeed = batchSize / batchTime ;
averageSpeed = (t + batchSize - 1) / time ;
if t == 3*opts.batchOpts.batchSize + 1
% compensate for the first three iterations, which are outliers
adjustTime = 4*batchTime - time ;
stats.time = time + adjustTime ;
end
fprintf('speed %.1f (%.1f) Hz', averageSpeed, currentSpeed) ;
fprintf('\n') ;
end
net.move('cpu') ;
% -------------------------------------------------------------------------
function clearMex()
% -------------------------------------------------------------------------
clear vl_tmove vl_imreadjpeg ;
% -------------------------------------------------------------------------
function prepareGPUs(opts, cold)
% -------------------------------------------------------------------------
numGpus = numel(opts.gpus) ;
if numGpus > 1
% check parallel pool integrity as it could have timed out
pool = gcp('nocreate') ;
if ~isempty(pool) && pool.NumWorkers ~= numGpus
delete(pool) ;
end
pool = gcp('nocreate') ;
if isempty(pool)
parpool('local', numGpus) ;
cold = true ;
end
end
if numGpus >= 1 && cold
fprintf('%s: resetting GPU\n', mfilename)
clearMex() ;
if numGpus == 1
gpuDevice(opts.gpus)
else
spmd
clearMex() ;
gpuDevice(opts.gpus(labindex))
end
end
end
|
github
|
vedaldi/mcnSSD-master
|
ssd_train.m
|
.m
|
mcnSSD-master/core/ssd_train.m
| 2,022 |
utf_8
|
6b556426c87f82c6525207c0a22271c8
|
function ssd_train(expDir, opts, varargin)
% ----------------------------------------------------------------
% Prepare imdb
% ----------------------------------------------------------------
imdbPath = opts.dataOpts.imdbPath ;
if exist(imdbPath, 'file')
imdb = load(imdbPath) ;
else
imdb = opts.dataOpts.getImdb(opts) ;
if ~exist(fileparts(imdbPath), 'dir'), mkdir(fileparts(imdbPath)) ; end
save(imdbPath, '-struct', 'imdb') ;
end
[opts, imdb] = opts.dataOpts.prepareImdb(imdb, opts) ;
% --------------------------------------------------------------------
% Train
% --------------------------------------------------------------------
if ~exist(expDir, 'dir')
mkdir(expDir) ;
end
confirmConfig(expDir, opts) ;
net = opts.modelOpts.net_init(opts) ;
[net,info] = cnn_train_dag(net, imdb, ...
@(i,b) opts.modelOpts.get_batch(i, b, opts.batchOpts), ...
opts.train, ...
'expDir', expDir) ;
% --------------------------------------------------------------------
% Evaluatte
% --------------------------------------------------------------------
[net, modelName] = deployModel(expDir, opts) ;
opts.eval_func('net', net, 'modelName', modelName, 'gpus', opts.train.gpus) ;
% --------------------------------------------------
function [net, modelName] = deployModel(expDir, opts)
% --------------------------------------------------
bestEpoch = findBestEpoch(expDir, 'priorityMetric', 'mbox_loss', ...
'prune', true) ;
bestNet = fullfile(expDir, sprintf('net-epoch-%d.mat', bestEpoch)) ;
deployPath = sprintf(opts.modelOpts.deployPath, bestEpoch) ;
opts.modelOpts.deploy_func(bestNet, deployPath, opts.modelOpts.numClasses) ;
net = dagnn.DagNN.loadobj(load(deployPath)) ;
[~,modelName,~] = fileparts(expDir) ;
|
github
|
vedaldi/mcnSSD-master
|
ssd_zoo.m
|
.m
|
mcnSSD-master/core/ssd_zoo.m
| 1,688 |
utf_8
|
2c7de7034bb3301178fbac60f4f65fcf
|
function net = ssd_zoo(modelName)
caffeModels = {
'ssd-pascal-vggvd-300', ...
'ssd-pascal-vggvd-512', ...
'ssd-pascal-plus-vggvd-300', ...
'ssd-pascal-vggvd-ft-300', ...
'ssd-pascal-plus-vggvd-512', ...
'ssd-pascal-plus-vggvd-ft-300', ...
'ssd-pascal-plus-vggvd-ft-512', ...
'ssd-pascal-vggvd-ft-512', ...
'vgg-vd-16-reduced', ...
'ssd-pascal-mobilenet-ft', ...
} ;
mcnModels = {
'ssd-mcn-pascal-vggvd-300', ...
'ssd-mcn-pascal-vggvd-512', ...
} ;
modelNames = horzcat(caffeModels, mcnModels) ;
assert(ismember(modelName, modelNames), 'unrecognised model') ;
modelDir = fullfile(vl_rootnn, 'data/models-import') ;
modelPath = fullfile(modelDir, sprintf('%s.mat', modelName)) ;
if ~exist(modelPath, 'file')
fetchModel(modelName, modelPath) ;
end
net = dagnn.DagNN.loadobj(load(modelPath)) ;
% ---------------------------------------
function fetchModel(modelName, modelPath)
% ---------------------------------------
waiting = true ;
prompt = sprintf(strcat('%s was not found at %s\nWould you like to ', ...
' download it from THE INTERNET (y/n)?\n'), modelName, modelPath) ;
while waiting
str = input(prompt,'s') ;
switch str
case 'y'
% ensure target directory exists
if ~exist(fileparts(modelPath), 'dir')
mkdir(fileparts(modelPath)) ;
end
fprintf(sprintf('Downloading %s ... \n', modelName)) ;
baseUrl = 'http://www.robots.ox.ac.uk/~albanie/models/ssd' ;
url = sprintf('%s/%s.mat', baseUrl, modelName) ;
urlwrite(url, modelPath) ;
return ;
case 'n'
throw(exception) ;
otherwise
fprintf('input %s not recognised, please use `y` or `n`\n', str) ;
end
end
|
github
|
vedaldi/mcnSSD-master
|
ssd_init.m
|
.m
|
mcnSSD-master/core/ssd_init.m
| 22,779 |
utf_8
|
81641239af58a92c7173e6e7a85d2f6e
|
function net = ssd_init(opts)
% SSD_INIT Initialize a Single Shot Multibox Detector Network
% NET = SSD_INIT randomly initializes an SSD network architecture
% for reproducibility, fix the seed
rng(0, 'twister') ;
% load trunk model
net = ssd_zoo('vgg-vd-16-reduced') ;
% -------------------------------------------------------------
% Set meta properties of net
% -------------------------------------------------------------
switch opts.modelOpts.architecture
case 300
imSize = [300 300] ;
addExtraConv = false ;
case 500
imSize = [500 500] ;
addExtraConv = true ;
case 512
imSize = [512 512] ;
addExtraConv = true ;
otherwise
error('architecture %d is not recognised', ...
opts.modelOpts.architecture) ;
end
net.meta.normalization.imageSize = imSize ;
% -------------------------------------------------------------
% Network truncation
% -------------------------------------------------------------
% modify trunk biases learnning rate and weight decay to match caffe
params = {'conv1_1b', ...
'conv1_2b', ...
'conv2_1b', ...
'conv2_2b', ...
'conv3_1b', ...
'conv3_2b', ...
'conv3_3b', ...
'conv4_1b', ...
'conv4_2b', ...
'conv4_3b' ...
'conv5_1b', ...
'conv5_2b', ...
'conv5_3b' ...
'fc6b', ...
'fc7b' ...
} ;
for i = 1:length(params)
net = matchCaffeBiases(net, params{i}) ;
end
% update fc6 to match SSD
net.layers(net.getLayerIndex('fc6')).block.dilate = [6 6] ;
net.layers(net.getLayerIndex('fc6')).block.pad = [6 6] ;
% Truncate the layers following relu7
net.removeLayer('fc8') ;
net.removeLayer('prob') ;
% rename input variable to 'data'
net.renameVar('x0', 'data') ;
% Alter the pooling to match SSD
net.layers(net.getLayerIndex('pool5')).block.stride = [1 1] ;
net.layers(net.getLayerIndex('pool5')).block.poolSize = [3 3] ;
net.layers(net.getLayerIndex('pool5')).block.pad = [1 1 1 1] ;
% --------------------------------------------------------------
% Architectural modifications - add new conv layer stacks
% --------------------------------------------------------------
prefix = 'conv6' ;
inLayer = 'relu7' ;
channelsIn = 1024 ;
bottleneck = 256 ;
channelsOut = 512 ;
kernelSizes = [1 3] ;
paddings = [0 0 0 0 ; 1 1 1 1] ;
strides = [ 1 1 ; 2 2 ] ;
net = addConvStack(net, prefix, inLayer, channelsIn, bottleneck, ...
channelsOut, kernelSizes, paddings, strides) ;
prefix = 'conv7' ;
inLayer = 'conv6_2_relu' ;
channelsIn = 512 ;
bottleneck = 128 ;
channelsOut = 256 ;
kernelSizes = [1 3] ;
paddings = [0 0 0 0 ; 1 1 1 1] ;
strides = [ 1 1 ; 2 2 ] ;
net = addConvStack(net, prefix, inLayer, channelsIn, bottleneck, ...
channelsOut, kernelSizes, paddings, strides) ;
prefix = 'conv8' ;
inLayer = 'conv7_2_relu' ;
finalLayer = 'conv8_2_relu' ;
channelsIn = 256 ;
bottleneck = 128 ;
channelsOut = 256 ;
kernelSizes = [1 3] ;
paddings = [0 0 0 0 ; 0 0 0 0] ;
strides = [ 1 1 ; 1 1 ] ;
net = addConvStack(net, prefix, inLayer, channelsIn, bottleneck, ...
channelsOut, kernelSizes, paddings, strides) ;
prefix = 'conv9' ;
inLayer = 'conv8_2_relu' ;
finalLayer = 'conv9_2_relu' ;
channelsIn = 256 ;
bottleneck = 128 ;
channelsOut = 256 ;
kernelSizes = [1 3] ;
paddings = [0 0 0 0 ; 0 0 0 0] ;
strides = [ 1 1 ; 1 1 ] ;
net = addConvStack(net, prefix, inLayer, channelsIn, bottleneck, ...
channelsOut, kernelSizes, paddings, strides) ;
if addExtraConv
prefix = 'conv10' ;
inLayer = 'conv9_2_relu' ;
finalLayer = 'conv10_2_relu' ;
channelsIn = 256 ;
bottleneck = 128 ;
channelsOut = 256 ;
kernelSizes = [1 4] ;
paddings = [0 0 0 0 ; 1 1 1 1] ;
strides = [ 1 1 ; 1 1 ] ;
net = addConvStack(net, prefix, inLayer, channelsIn, bottleneck, ...
channelsOut, kernelSizes, paddings, strides) ;
end
% Add normalization layer
layerName = 'conv4_3_norm' ;
initialScale = single(20) ;
layer = dagnn.Normalize() ;
inputs = net.layers(net.getLayerIndex('relu4_3')).outputs ;
outputs = layerName ;
params = {'conv4_3_norm_scale'} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
net.params(net.getParamIndex(params)).value = ones(1,1,512) * initialScale ;
% -------------------------------------
% Compute multibox prior parameters
% -------------------------------------
% minimum dimension of input image
minDim = imSize(1) ;
switch opts.modelOpts.architecture
case 300
% The feature maps which from which the prior box layers are
% constructed have the following sizes:
sourceLayers = {'conv4_3_norm', ... % 38 x 38
'fc7', ... % 19 x 19
'conv6_2', ... % 10 x 10
'conv7_2', ... % 5 x 5
'conv8_2', ... % 3 x 3
'conv9_2'} ; % 1 x 1
% These ratios are expressed as percentages
minRatio = 20 ;
maxRatio = 90 ;
% Following the paper, the scale for conv4_3 is handled separately
% when training on VOC0712, so we can compute the step as follows
step = floor((maxRatio - minRatio) / (numel(sourceLayers(2:end)) - 1)) ;
minSizes = zeros(numel(sourceLayers), 1) ;
maxSizes = zeros(numel(sourceLayers), 1) ;
effectiveMax = minRatio + numel(sourceLayers(2:end)) * step ;
ratios = [10 minRatio:step:maxRatio effectiveMax] ;
for i = 1:numel(ratios) - 1
minSizes(i) = minDim * ratios(i) / 100 ;
maxSizes(i) = minDim * ratios(i + 1) / 100 ;
end
% note: certain layers use fewer aspect ratios (just 1, 1/2, 2/1)
aspectRatios = { [2], ...
[2, 3], ...
[2, 3], ...
[2, 3], ...
[2], ...
[2] } ;
steps = [8, 16, 32, 64, 100, 300] ;
case 512
% The feature maps which from which the prior box layers are
% constructed have the following sizes:
sourceLayers = {'conv4_3_norm', ... % 64 x 64
'fc7', ... % 32 x 32
'conv6_2', ... % 16 x 16
'conv7_2', ... % 8 x 8
'conv8_2', ... % 4 x 4
'conv9_2', ... % 2 x 2
'conv10_2'} ; % 1 x 1
% These ratios are expressed as percentages
minRatio = 15 ;
maxRatio = 90 ;
step = floor((maxRatio - minRatio) / (numel(sourceLayers(2:end)) - 1)) ;
minSizes = zeros(numel(sourceLayers), 1) ;
maxSizes = zeros(numel(sourceLayers), 1) ;
effectiveMax = minRatio + numel(sourceLayers(2:end)) * step ;
ratios = [7 minRatio:step:maxRatio effectiveMax] ;
for i = 1:numel(ratios) - 1
minSizes(i) = minDim * ratios(i) / 100 ;
maxSizes(i) = minDim * ratios(i + 1) / 100 ;
end
aspectRatios = { [2], ...
[2, 3], ...
[2, 3], ...
[2, 3], ...
[2, 3], ...
[2], ...
[2] } ;
steps = [8, 16, 32, 64, 128, 256, 512] ;
end
flip = true ;
clip = opts.modelOpts.clipPriors ;
variances = [0.1 0.1 0.2 0.2]' ;
% an offset is used to centre each prior box between
% activations in the feature map (see Sec 2.2. of the
% SSD paper)
offset = 0.5 ;
% Since the computed prior boxes are identical for a fixed size
% input, we can cahce them after the first forward pass
usePriorCaching = true ;
% -------------------------------------
% Construct multibox prior units
% -------------------------------------
unit = 1 ;
prefix = 'conv4_3_norm' ;
inLayerName = 'conv4_3_norm' ;
channelsIn = 512 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
unit = 2 ;
prefix = 'fc7' ;
inLayerName = 'relu7' ;
channelsIn = 1024 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
unit = 3 ;
prefix = 'conv6_2' ;
inLayerName = 'conv6_2_relu' ;
channelsIn = 512 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
unit = 4 ;
prefix = 'conv7_2' ;
inLayerName = 'conv7_2_relu' ;
channelsIn = 256 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
unit = 5 ;
prefix = 'conv8_2' ;
inLayerName = 'conv8_2_relu' ;
channelsIn = 256 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
unit = 6 ;
prefix = 'conv9_2' ;
inLayerName = 'conv9_2_relu' ;
channelsIn = 256 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
if addExtraConv
unit = 7 ;
prefix = 'conv10_2' ;
inLayerName = 'conv10_2_relu' ;
channelsIn = 256 ;
[confOut, locOut] = getOutSize(maxSizes(unit), aspectRatios{unit}, opts) ;
net = addMultiBoxLayers(net, prefix, inLayerName, minSizes(unit), ...
maxSizes(unit), aspectRatios{unit}, flip, ...
clip, steps(unit), offset, variances, ...
channelsIn, confOut, locOut, usePriorCaching) ;
end
% -------------------------------------
% Fuse predictions
% -------------------------------------
layerName = 'mbox_loc' ;
fuseType = 'loc_flat' ;
axis = 3 ;
net = addFusionLayer(net, layerName, fuseType, sourceLayers, axis) ;
layerName = 'mbox_conf' ;
fuseType = 'conf_flat' ;
axis = 3 ;
net = addFusionLayer(net, layerName, fuseType, sourceLayers, axis) ;
layerName = 'mbox_priorbox' ;
fuseType = 'priorbox' ;
axis = 1 ;
net = addFusionLayer(net, layerName, fuseType, sourceLayers, axis) ;
% ----------------------------------------------------------------
% Decoder layer
% ----------------------------------------------------------------
% Decoder layer -> converts predictions into happiness and rainbows
layerName = 'mbox_coder' ;
layer = dagnn.MultiboxCoder('backgroundLabel', 1, ...
'negOverlap', 0.5, ...
'overlapThreshold', 0.5, ...
'negPosRatio', 3, ...
'numClasses', opts.modelOpts.numClasses) ;
inputLayers = {'mbox_loc', 'mbox_conf', 'mbox_priorbox'} ;
inputs = cellfun(@(x) net.layers(net.getLayerIndex(x)).outputs{1}, ...
inputLayers, 'UniformOutput', false) ;
inputs = horzcat(inputs, 'targets', 'labels') ;
outputs = {'loc_preds', 'loc_labels', 'conf_preds', ...
'conf_labels', 'loc_weights', 'conf_weights'} ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
% ----------------------------------------------------------------
% Loss layers
% ----------------------------------------------------------------
% Two losses are used
layerName = 'class_loss' ;
layer = dagnn.UnnormalizedLoss() ;
inputs = { 'conf_preds', 'conf_labels', 'conf_weights'} ;
outputs = {'class_loss'} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
layerName = 'loc_loss' ;
layer = dagnn.HuberLoss() ;
inputs = { 'loc_preds', 'loc_labels', 'loc_weights'} ;
outputs = {'loc_loss'} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
layerName = 'mbox_loss' ;
layer = dagnn.MultiboxLoss() ;
inputs = { 'class_loss', 'loc_loss'} ;
outputs = {'mbox_loss'} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
% ----------------------------------------------
function net = matchCaffeBiases(net, param)
% ----------------------------------------------
% set the learning rate and weight decay of the
% convolution biases to match caffe
net.params(net.getParamIndex(param)).learningRate = 2 ;
net.params(net.getParamIndex(param)).weightDecay = 0 ;
% -------------------------------------------------------
function [confOut, locOut] = getOutSize(maxSize, aspectRatios, opts)
% -------------------------------------------------------
% THe filters must produce a prediction for each of the prior
% boxes associated with a source feature layer. The number of
% prior boxes per feature is explained in detail in the SSD paper
% (essentially it is computed according to the number of specified
% aspect ratios)
numBBoxOffsets = 4 ;
priorsPerFeature = 1 + logical(maxSize) + numel(aspectRatios) * 2 ;
confOut = opts.modelOpts.numClasses * priorsPerFeature ;
locOut = numBBoxOffsets * priorsPerFeature ;
% -----------------------------------------------------------------------------
function net = addConvStack(net, prefix, prevLayer, channelsIn, bottleneck, ...
channelsOut, kernelSizes, paddings, strides)
% -----------------------------------------------------------------------------
layerName = sprintf('%s_1', prefix) ;
ks = kernelSizes(1) ;
sz = [ks ks channelsIn bottleneck] ;
layer = dagnn.Conv('size', sz, ...
'pad', paddings(1,:), ...
'stride', strides(1,:), ...
'hasBias', true) ;
inputs = net.layers(net.getLayerIndex(prevLayer)).outputs ;
outputs = layerName ;
params = {sprintf('%s_1f', prefix), sprintf('%s_1b', prefix)} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
net = init_weights(net, layerName, ks, channelsIn, bottleneck) ;
prevLayer = layerName ;
layerName = sprintf('%s_1_relu', prefix) ;
layer = dagnn.ReLU() ;
inputs = net.layers(net.getLayerIndex(prevLayer)).outputs ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
prevLayer = layerName ;
layerName = sprintf('%s_2', prefix) ;
ks = kernelSizes(2) ;
sz = [ks ks bottleneck channelsOut] ;
layer = dagnn.Conv('size', sz, ...
'pad', paddings(2,:), ...
'stride', strides(2,:), ...
'hasBias', true) ;
inputs = net.layers(net.getLayerIndex(prevLayer)).outputs ;
outputs = layerName ;
params = {sprintf('%s_12', prefix), sprintf('%s_2b', prefix)} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
net = init_weights(net, layerName, ks, bottleneck, channelsOut) ;
prevLayer = layerName ;
layerName = sprintf('%s_2_relu', prefix) ;
layer = dagnn.ReLU() ;
inputs = net.layers(net.getLayerIndex(prevLayer)).outputs ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
% -------------------------------------------------------------------
function net = addMultiBoxLayers(net, prefix, prevLayerName, minSize, ...
maxSize, aspectRatios, flip, clip, ...
step, offset, variances, channelsIn, ...
confOut, locOut, usePriorCaching)
% ------------------------------------------------------------------
%ADDMULTIBOXLAYERS adds a set of multibox layers to a dagnn
% ADDMULTIBOXLAYERS adds the collection of network layers
% required to construct a MultiBox Prior "unit". A unit
% consistss of seven layers:
%
% A PriorBox reference layer defining the default
% reference boxes, followed by
% Convolution -> Permute -> Flatten
% (for prior box locations)
% Convolution -> Permute -> Flatten
% (for prior box class scores)
%
% ARGUMENTS:
% `net`: dagnn.DagNN net object under construction
% `prefix`: (string) name used to prefix each layer name in unit
% `prevLayerName`: (string) name of input feature layer
% `minSize`: (float) minimum size of prior boxes
% `maxSize`: (float) maximum size of prior boxes
% `aspectRatios`: (float) array of aspect ratios used for prior boxes
% `flip`: (logical) add flipped versions of each aspect ratio
% `clip`: (logical) clip prior boxes to lie inside feature map
% `step`: (int) number of pixel steps taken in image to match a pixel
% step in the feature map
% `offset`: (float) offset applied to centre each feature location
% `variances`: (4x1 array) variances used to scale prior boxes
% `channelsIn`: (int) number of channels in the input layer
% `confOut`: (int) number of filters used to predict class confidences
% `locOut`: (int) number of filters used to predict box location updates
% `usePriorCaching`: (logical) cache the prior boxes and re-use after
% the first pass
% store the layer on which the multibox layers will be based
rootLayerName = prevLayerName ;
layerName = sprintf('%s_mbox_priorbox', prefix) ;
layer = dagnn.PriorBox('minSize', minSize, ...
'maxSize', maxSize, ...
'aspectRatios', aspectRatios, ...
'flip', flip, ...
'clip', clip, ...
'pixelStep', step, ...
'offset', offset, ...
'usePriorCaching', true, ...
'variance', variances) ;
inputs = { net.layers(net.getLayerIndex(rootLayerName)).outputs{1} 'data' };
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
layerName = sprintf('%s_mbox_loc', prefix) ;
ks = 3 ;
sz = [ks ks channelsIn locOut] ;
layer = dagnn.Conv('size', sz, 'pad', 1, 'stride', 1, 'hasBias', true) ;
inputs = net.layers(net.getLayerIndex(rootLayerName)).outputs ;
outputs = layerName ;
params = {sprintf('%s_mbox_locf', prefix), sprintf('%s_mbox_locb', prefix)} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
net = init_weights(net, layerName, ks, channelsIn, locOut) ;
prevLayerName = layerName ;
layerName = sprintf('%s_mbox_loc_perm', prefix) ;
layer = dagnn.Permute('order', [3 2 1 4]);
inputs = net.layers(net.getLayerIndex(prevLayerName)).outputs ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
prevLayerName = layerName ;
layerName = sprintf('%s_mbox_loc_flat', prefix) ;
layer = dagnn.Flatten('axis', 3) ;
inputs = net.layers(net.getLayerIndex(prevLayerName)).outputs ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
layerName = sprintf('%s_mbox_conf', prefix) ;
ks = 3 ;
sz = [ks ks channelsIn confOut] ;
layer = dagnn.Conv('size', sz, 'pad', 1, 'stride', 1, 'hasBias', true) ;
inputs = net.layers(net.getLayerIndex(rootLayerName)).outputs ;
outputs = layerName ;
params = {sprintf('%s_mbox_conff', prefix), sprintf('%s_mbox_confb', prefix)} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
net = init_weights(net, layerName, ks, channelsIn, confOut) ;
prevLayerName = layerName ;
layerName = sprintf('%s_mbox_conf_perm', prefix) ;
layer = dagnn.Permute('order', [3 2 1 4]);
inputs = net.layers(net.getLayerIndex(prevLayerName)).outputs ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
prevLayerName = layerName ;
layerName = sprintf('%s_mbox_conf_flat', prefix) ;
layer = dagnn.Flatten('axis', 3) ;
inputs = net.layers(net.getLayerIndex(prevLayerName)).outputs ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
% --------------------------------------------------------------------------
function net = addFusionLayer(net, layerName, fuseType, sourcePrefixes, axis)
% --------------------------------------------------------------------------
%ADDFUSIONLAYER adds a layer to concatenate source layers
% ADDFUSIONLAYER adds a concatenation layer fusing inputs of a
% particular type
%
% ARGUMENTS:
% `layerName` name of created layer
% `fuseType` types to be fused (can be 'loc', 'conf' or
% 'priorbox')
% `sourcPrefixes` cell array of prefix strings of layers to
% be fused
% `axis` dimension of concatenation
layer = dagnn.Concat('dim', axis) ;
inputLayers = cellfun(@(x) sprintf('%s_mbox_%s', x, fuseType), ...
sourcePrefixes, 'UniformOutput', false) ;
inputs = cellfun(@(x) net.layers(net.getLayerIndex(x)).outputs{1}, ...
inputLayers, 'UniformOutput', false) ;
outputs = layerName ;
params = {} ;
net.addLayer(layerName, layer, inputs, outputs, params) ;
% ------------------------------------------------------
function net = init_weights(net, layerName, ks, in, out)
% ------------------------------------------------------
% xavier initialize weights and set initial learning rates
paramNames = net.layers(net.getLayerIndex(layerName)).params ;
filterName = paramNames{1} ;
biasName = paramNames{2} ;
% mimic caffe version
sc = sqrt(1/(ks*ks*in)) ;
filters = randn(ks, ks, in, out, 'single') * sc ;
net.params(net.getParamIndex(filterName)).value = filters ;
net.params(net.getParamIndex(filterName)).learningRate = 1 ;
biases = zeros(out, 1, 'single') ;
net.params(net.getParamIndex(biasName)).value = biases ;
net.params(net.getParamIndex(biasName)).learningRate = 2 ;
net.params(net.getParamIndex(biasName)).weightDecay = 0 ;
|
github
|
vedaldi/mcnSSD-master
|
patchSampler.m
|
.m
|
mcnSSD-master/matlab/utils/patchSampler.m
| 1,636 |
utf_8
|
f8e0fbe5b2a84939aa6a355c41404674
|
function [patch, targets, labels] = patchSampler(targets, labels, opts)
% TODO: docs
strategies = {'jacc_0.1', ...
'jacc_0.3', ...
'jacc_0.5', ...
'jacc_0.7', ...
'jacc_0.9', ...
'rand_patch'} ;
targetsWH = bboxCoder(targets, 'MinMax', 'MinWH') ;
success = false ;
while ~success
sampledPatches = cellfun(@(x) runSampleStrategy(x, targetsWH, opts), ...
strategies, 'Uni', 0) ;
% add original image as the last patch strategy
sampledPatches{end + 1} = [ 0 0 1 1 ] ;
% remove failed samples
empty = cellfun(@isempty, sampledPatches) ;
sampledPatches(empty) = [] ;
% uniformly sample from patch samples :)
patch = sampledPatches{randi(length(sampledPatches), 1)} ;
%----------------------------
% DEBUG
cond = patch(:,3:4) - patch(:,1:2) > 0 ;
assert(all(cond(:)), ...
'PATCHSAMPLER:invalidPatch', ...
'patches must be in the (xmin, ymin, xmax, ymax) format') ;
%----------------------------
[success, targets, labels] = updateAnnotations(patch, targetsWH, labels, opts) ;
end
cond = targets(:,3:4) - targets(:,1:2) > 0 ;
assert(all(cond(:)), ...
'PATCHSAMPLER:invalidTargets', ...
'target boxes must be in the (xmin, ymin, xmax, ymax) format') ;
% ---------------------------------------------------------
function patch = runSampleStrategy(strategy, targetsWH, opts)
% ---------------------------------------------------------
randSource = rand(opts.numTrials, 4) ;
patch = runPatchTrials(targetsWH, strategy, randSource, opts) ;
|
github
|
vedaldi/mcnSSD-master
|
findBestEpoch.m
|
.m
|
mcnSSD-master/matlab/utils/findBestEpoch.m
| 3,047 |
utf_8
|
013d4183ef2103cc519f6bbec63ee734
|
function bestEpoch = findBestEpoch(expDir, varargin)
%FINDBESTEPOCH finds the best epoch of training
% FINDBESTEPOCH(EXPDIR) evaluates the checkpoints
% (the `net-epoch-%d.mat` files created during
% training) in EXPDIR
%
% FINDBESTEPOCH(..., 'option', value, ...) accepts the following
% options:
%
% `priorityMetric`:: 'classError'
% Determines the highest priority metric by which to rank the
% checkpoints.
%
% `prune`:: false
% Removes all saved checkpoints to save space except:
%
% 1. The checkpoint with the lowest validation error metric
% 2. The last checkpoint
opts.prune = false ;
opts.priorityMetric = 'classError' ;
opts = vl_argparse(opts, varargin) ;
lastEpoch = findLastCheckpoint(expDir);
% return if no checkpoints were found
if ~lastEpoch
return
end
bestEpoch = findBestValCheckpoint(expDir, opts.priorityMetric);
preciousEpochs = [bestEpoch lastEpoch];
if opts.prune
removeOtherCheckpoints(expDir, preciousEpochs);
fprintf('----------------------- \n');
fprintf('%s directory cleaned: \n', expDir);
fprintf('----------------------- \n');
end
% -------------------------------------------------------------------------
function removeOtherCheckpoints(expDir, preciousEpochs)
% -------------------------------------------------------------------------
list = dir(fullfile(expDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epochs = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
targets = ~ismember(epochs, preciousEpochs);
files = cellfun(@(x) fullfile(expDir, sprintf('net-epoch-%d.mat', x)), ...
num2cell(epochs(targets)), 'UniformOutput', false);
cellfun(@(x) delete(x), files)
% -------------------------------------------------------------------------
function bestEpoch = findBestValCheckpoint(expDir, priorityMetric)
% -------------------------------------------------------------------------
lastEpoch = findLastCheckpoint(expDir) ;
% handle the different storage structures/error metrics
data = load(fullfile(expDir, sprintf('net-epoch-%d.mat', lastEpoch)));
if isfield(data, 'stats')
valStats = data.stats.val;
elseif isfield(data, 'info')
valStats = data.info.val;
else
error('storage structure not recognised');
end
% find best checkpoint according to the following priority
metrics = {priorityMetric, 'top1error', 'error', 'mbox_loss', 'class_loss'} ;
for i = 1:numel(metrics)
if isfield(valStats, metrics{i})
errorMetric = [valStats.(metrics{i})] ;
break ;
end
end
assert(logical(exist('errorMetric')), 'error metrics not recognized') ;
[~, bestEpoch] = min(errorMetric);
% -------------------------------------------------------------------------
function epoch = findLastCheckpoint(expDir)
% -------------------------------------------------------------------------
list = dir(fullfile(expDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epoch = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
epoch = max([epoch 0]) ;
|
github
|
vedaldi/mcnSSD-master
|
printPascalResults.m
|
.m
|
mcnSSD-master/matlab/utils/printPascalResults.m
| 5,238 |
utf_8
|
84ec5f37d3be267ee3307feedeb0b60f
|
function printPascalResults(cacheDir, varargin)
%PRINTPASCALRESULTS prints out results as formatted tables
% PRINTRESULTS(CACHEDIR) searches the cache directory of
% pascal VOC evaluations and prints out a formatted summary
% CACHEDIR is a string specifying the absolute path of the
% directory holding the cached results
%
% PRINTPASCALRESULTS(..., 'option', value, ...) takes
% the following options:
%
% `orientation`:: 'portrait'
% The orientation in which the table is printed. Can be
% either 'landscape' or 'portrait'. Landscape is useful
% when you have a wide monitor.
%
% Copyright (C) 2017 Samuel Albanie
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
opts.orientation = 'portrait' ;
opts = vl_argparse(opts, varargin) ;
[valResList, testResList] = getResultsList(cacheDir) ;
valResults = cellfun(@(x) getResult(x), valResList, 'Uni', false) ;
testResults = cellfun(@(x) getResult(x), testResList, 'Uni', false) ;
valResults = cell2mat(valResults) ;
testResults = cell2mat(testResults) ;
if ~isempty(valResults)
fprintf('\nVal Set Results:\n') ;
prettyPrintTable(valResults, opts) ;
end
if ~isempty(testResults)
fprintf('\nTest Set Results:\n') ;
prettyPrintTable(testResults, opts) ;
end
% -------------------------------------------------------------------------
function [valList, testList] = getResultsList(cacheDir)
% -------------------------------------------------------------------------
files = ignoreSystemFiles(dir(fullfile(cacheDir, '*.mat'))) ;
names = {files.name} ;
[penSuffixes, suffixes] = cellfun(@(x) getSuffixes(x), names, 'Uni', false) ;
valList = fullfile(cacheDir, names(strcmp(suffixes, 'results') & ...
strcmp(penSuffixes, 'val'))) ;
testList = fullfile(cacheDir, names(strcmp(suffixes, 'results') & ...
strcmp(penSuffixes, 'test'))) ;
% -------------------------------------------------------------------------
function [penSuffix, suffix] = getSuffixes(filename)
% -------------------------------------------------------------------------
[~,filename,~] = fileparts(filename) ;
tokens = strsplit(filename, '-') ;
penSuffix = tokens{end -1} ;
suffix = tokens{end} ;
% -------------------------------------------------------------------------
function result = getResult(resultFile)
% -------------------------------------------------------------------------
[~,fname,~] = fileparts(resultFile) ;
tokens = strsplit(fname,'-') ;
model = strjoin(tokens(1:end - 2), '-') ;
result.model= model;
result.subset = tokens{end - 1} ;
data = load(resultFile) ;
aps = data.results * 100;
pascalClasses = {'aeroplane', 'bicycle', 'bird', 'boat', ...
'bottle', 'bus', 'car', 'cat', 'chair', ...
'cow', 'diningtable', 'dog', 'horse', ...
'motorbike', 'person', 'pottedplant', ...
'sheep', 'sofa', 'train', 'tvmonitor'} ;
for i = 1:numel(pascalClasses)
f = pascalClasses{i} ;
result.(f) = aps(i) ;
end
result.mean = mean(aps) ;
%---------------------------------------
function prettyPrintTable(results, opts)
%---------------------------------------
switch opts.orientation
case 'portrait'
table = struct2table(results);
numCols = size(table, 1) ;
% format the column widths
leftCol = 14 ;
if ischar(table.model)
table.model = {table.model} ;
end
dataCol = max(cellfun(@length, table.model)) ;
% print the table headers
columnWidths = horzcat(leftCol, repmat(dataCol, 1, numCols)) ;
dividerFormatter = strcat(repmat('%s ', 1, numCols + 1), '\n') ;
dividerStrings = arrayfun(@(x) repmat('-', 1, x), columnWidths, ...
'Uni', false) ;
fprintf(dividerFormatter, dividerStrings{:}) ;
headerFormatter = strcat(sprintf('%%-%ds', leftCol), ...
repmat(sprintf(' %%-%ds', dataCol), ...
1, numCols), '\n') ;
headerStrings = horzcat(' ', table.model') ;
fprintf(headerFormatter, headerStrings{:}) ;
fprintf(dividerFormatter, dividerStrings{:}) ;
% print the main table
categories = setdiff(fieldnames(table), ...
{'Properties', 'subset', 'model'}) ;
dataFormatter = strcat(sprintf('%%-%ds', leftCol), ...
repmat(sprintf(' %%-%d.2f', dataCol), ...
1, numCols), '\n') ;
for i = 1:numel(categories);
c = categories{i} ;
ap = table.(c) ;
fprintf(dataFormatter, c, ap(:)) ;
end
fprintf(dividerFormatter, dividerStrings{:}) ;
ap = table.('mean') ;
fprintf(dataFormatter, 'mean', ap(:)) ;
fprintf(dividerFormatter, dividerStrings{:}) ;
case 'landscape'
table = struct2table(results);
disp(table) ;
otherwise
error('table orientation must be either landscape or portrait') ;
end
|
github
|
vedaldi/mcnSSD-master
|
pruneCheckpoints.m
|
.m
|
mcnSSD-master/matlab/utils/pruneCheckpoints.m
| 1,808 |
utf_8
|
decdd56329b5b620f8bbdb243d1a945e
|
function varargout = pruneCheckpoints(expDir, varargin)
%PRUNECHECKPOINTS removes unnecessary checkpoint files
% PRUNECHECKPOINTS(EXPDIR) evaluates the checkpoints
% (the `net-epoch-%d.mat` files created during
% training) in EXPDIR and removes all checkpoints except:
%
% 1. The checkpoint with the lowest validation error metric
% 2. The last checkpoint
%
% If an output argument is provided, PRUNECHECKPOINTS returns the
% epoch with the lowest validation error.
%
% PRUNECHECKPOINTS(..., 'option', value, ...) accepts the following
% options:
%
% `priorityMetric`:: 'classError'
% Determines the highest priority metric by which to rank the
% checkpoints for pruning.
opts.priorityMetric = 'classError' ;
opts = vl_argparse(opts, varargin) ;
lastEpoch = findLastCheckpoint(expDir);
% return if no checkpoints were found
if ~lastEpoch
return
end
bestEpoch = findBestCheckpoint(expDir, opts.priorityMetric);
preciousEpochs = [bestEpoch lastEpoch];
removeOtherCheckpoints(expDir, preciousEpochs);
fprintf('----------------------- \n');
fprintf('%s directory cleaned: \n', expDir);
fprintf('----------------------- \n');
if nargout == 1
varargout{1} = bestEpoch ;
end
% -------------------------------------------------------------------------
function removeOtherCheckpoints(expDir, preciousEpochs)
% -------------------------------------------------------------------------
list = dir(fullfile(expDir, 'net-epoch-*.mat')) ;
tokens = regexp({list.name}, 'net-epoch-([\d]+).mat', 'tokens') ;
epochs = cellfun(@(x) sscanf(x{1}{1}, '%d'), tokens) ;
targets = ~ismember(epochs, preciousEpochs);
files = cellfun(@(x) fullfile(expDir, sprintf('net-epoch-%d.mat', x)), ...
num2cell(epochs(targets)), 'UniformOutput', false);
cellfun(@(x) delete(x), files)
|
github
|
vedaldi/mcnSSD-master
|
matchPriors.m
|
.m
|
mcnSSD-master/matlab/utils/matchPriors.m
| 2,838 |
utf_8
|
b2eb3ece2444e7a7f991742c046e05f5
|
function [matches, overlaps, ignored] = matchPriors(gtBoxes, pBoxes, varargin)
% MATCHPRIORS
%
% TODO: docs
%
opts.overlapThreshold = 0.5 ;
opts.ignoreXBoundaryBoxes = false ;
opts = vl_argparse(opts, varargin, 'nonrecursive') ;
if opts.ignoreXBoundaryBoxes
boundaryBoxes = pBoxes(:,1) < 0 ...
| pBoxes(:,2) < 0 ...
| pBoxes(:,3) > 1 ...
| pBoxes(:,4) > 1 ;
ignored = find(boundaryBoxes) ;
pBoxes = updateBoundaryPreds(pBoxes, ignored) ;
else
ignored = zeros(size(pBoxes, 1), 1) ;
end
% re-encode bboxes to [xmin ymin width height]
gtMinWH = bboxCoder(gtBoxes, 'MinMax', 'MinWH') ;
pMinWH = bboxCoder(pBoxes, 'MinMax', 'MinWH') ;
% first the best overlapping priors with gt boxes
overlaps = bboxOverlapRatio(gtMinWH, pMinWH, 'Union') ;
[~, bestOverlapIdx] = max(overlaps, [], 2) ;
% find any remaining priors with greater than the overlap threshold
boxIdx = 1:size(gtMinWH, 1) ;
allMatches_ = arrayfun(@(x, i) ...
unique([x find(overlaps(i, :) > opts.overlapThreshold)]), ...
bestOverlapIdx', boxIdx, ...
'UniformOutput', false) ;
% Each prior box that has matched needs to be assigned to a specific
% ground truth. This process is done in two steps.
% 1. Initially, all priors are assigned to the gts with which
% they have greatest overlap
% 2. Then (to ensure that each gt is assigned at least one
% prior) each gt is assigned the prior box which has the
% highest overlap with it. If multiple gts have their
% highest overlap with the same prior, it is assigned
% to the gt with which it has greatest overlap and
% the other gts get their 'second choice' of prior etc.
matchSizes = cellfun(@numel, allMatches_) ;
uniqueMatches = unique(horzcat(allMatches_{:}))' ;
uniqueMatchOverlaps = overlaps(:,uniqueMatches)' ;
[~, assignments] = max(uniqueMatchOverlaps, [], 2) ;
for i = 1:size(gtBoxes, 1)
[r,c] = maxMatrixElement(uniqueMatchOverlaps) ;
assignments(r) = c ;
uniqueMatchOverlaps(r,:) = -Inf ;
uniqueMatchOverlaps(:,c) = -Inf ;
end
matches = arrayfun(@(x) uniqueMatches(x == assignments)', ...
1:size(gtBoxes), 'Uni', false) ;
% ----------------------------------------------------
function pBoxes = updateBoundaryPreds(pBoxes, ignored)
% ---------------------------------------------------
% replace predictions that lie on the boundary
% with boxes that cannot be matched by priors
% choose an unreachable value
x = max(pBoxes(:)) + 1 ;
% update the predictions
pBoxes(ignored,:) = repmat([ x x x+1 x+1 ], numel(ignored), 1) ;
% ---------------------------------------------
function [row, col] = maxMatrixElement(matrix)
% ---------------------------------------------
[maxVal,ind] = max(matrix(:)) ;
[row,col] = ind2sub(size(matrix),ind) ;
|
github
|
vedaldi/mcnSSD-master
|
confirmConfig.m
|
.m
|
mcnSSD-master/matlab/utils/confirmConfig.m
| 1,953 |
utf_8
|
e0d793b88b3c3802c4ff89e950d28208
|
function confirmConfig(expDir, opts)
%DOCS: todo - pretty obvs
if ~opts.confirmConfig
return ;
end
[~,expName] = fileparts(expDir) ;
fprintf('Experiment name: %s\n', expName) ;
fprintf('------------------------------------\n') ;
fprintf('Training set: %s\n', opts.dataOpts.trainData) ;
fprintf('Testing set: %s\n', opts.dataOpts.testData) ;
fprintf('------------------------------------\n') ;
fprintf('Prune checkpoints: %d\n', opts.pruneCheckpoints) ;
fprintf('GPU: %d\n', opts.train.gpus) ;
fprintf('Batch size: %d\n', opts.train.batchSize) ;
fprintf('------------------------------------\n') ;
fprintf('Train + val: %d\n', opts.dataOpts.useValForTraining) ;
fprintf('Flip: %d\n', opts.dataOpts.flipAugmentation) ;
fprintf('Patches: %d\n', opts.dataOpts.patchAugmentation) ;
fprintf('Zoom: %d\n', opts.dataOpts.zoomAugmentation) ;
fprintf('Distort: %d\n', opts.dataOpts.distortAugmentation) ;
fprintf('------------------------------------\n') ;
printSchedule(opts) ;
fprintf('------------------------------------\n') ;
waiting = true ;
prompt = 'Run experiment with these parameters? `y` or `n`\n' ;
while waiting
str = input(prompt,'s') ;
switch str
case 'y'
return ;
case 'n'
throw(exception) ;
otherwise
fprintf('input %s not recognised, please use `y` or `n`\n', str) ;
end
end
% -------------------------
function printSchedule(opts)
% -------------------------
% format learning rates (assumes monotonically
% decreasing after the first warmup epochs)
fprintf('Learning Rate Schedule: \n') ;
lr = opts.train.learningRate ;
warmup = lr(1:2) ;
fprintf('%g %g (warmup)\n', warmup(1), warmup(2)) ;
schedule = lr(3:end) ;
[tiers, uIdx] = unique(schedule) ;
[~, order] = sort(uIdx) ;
for i = 1:numel(order)
idx = uIdx(order)' ;
tierLength = [ idx(2:end) numel(schedule) + 1] - idx ;
fprintf('%g for %d epochs\n', tiers(order(i)), tierLength(i)) ;
end
|
github
|
vedaldi/mcnSSD-master
|
nnmultiboxcoder.m
|
.m
|
mcnSSD-master/matlab/xtest/suite/nnmultiboxcoder.m
| 2,571 |
utf_8
|
e4acc4d7263d1d0466acd069824ff7b0
|
classdef nnmultiboxcoder < nntest
methods (Test)
function basic(test)
batchSize = 5 ;
numPriors = 7 ;
numLocPreds = numPriors * 4 ;
numConfPreds = numPriors * 21 ;
labelRange = [1 21] ;
for i = 1:batchSize
numBoxes = randi(10, 1) ;
xmin = rand(numBoxes, 1) ;
ymin = rand(numBoxes, 1) ;
xmax = xmin + (1 - xmin) .* rand(numBoxes, 1) ;
ymax = ymin + (1 - ymin) .* rand(numBoxes, 1) ;
gt{i} = [ xmin ymin xmax ymax] ;
l{i} = randi(21, 1, numBoxes) ;
end
% we need to encode some viable prior boxes to pass through
% the saftey checks
vars = [0.1 0.1 0.2 0.2] ;
priorBoxes = [ 0.4 0.2 0.7 0.7 ;
0.1 0.1 0.4 0.41 ;
0.1 0.1 0.8 0.8 ;
0.1 0.1 0.8 0.9 ;
0.1 0.1 0.9 0.8 ;
0.2 0.1 0.9 0.8 ;
0.26 0.26 0.75 0.75 ]' ;
priorVars = repmat(vars', [numPriors 1]) ;
x = randn(1,1,numLocPreds, batchSize,'single') ;
v = randn(1,1,numConfPreds, batchSize,'single') ;
p = cat(3, priorBoxes(:), priorVars) ;
y = vl_nnmultiboxcoder(x, v, p, gt, l) ;
posMatches = y{5} ;
negMatches = y{6} ;
%check derivatives with numerical approximation
derLocs = test.randn(size(y{1})) / 100 ;
derConfs = test.randn(size(y{3})) / 100 ;
dzdy = { derLocs, derConfs } ;
dzdxv = vl_nnmultiboxcoder(x, v, p, gt, l, dzdy, ...
'matchingPosIndices', posMatches, ...
'matchingNegIndices', negMatches) ;
dzdx = dzdxv{1} ;
dzdv = dzdxv{2} ;
test.der(@(x) forward_wrapper(x,v,p,gt,l,'locPreds'), x, ...
dzdy{1}, dzdx, test.range * 1e-3) ;
% NOTE: the delta on this test must be small to avoid "flipping" the
% hard negatives
test.der(@(v) forward_wrapper(x,v,p,gt,l,'confPreds'), v, ...
dzdy{2}, dzdv, test.range * 1e-5) ;
end
end
end
% ------------------------------------------------------
function y = forward_wrapper(x,v,p,gt,l,target)
% ------------------------------------------------------
y = vl_nnmultiboxcoder(x,v,p,gt,l) ;
switch target
case 'locPreds'
y = y{1} ;
case 'confPreds'
y = y{3} ;
otherwise
error('unrecognized derivative') ;
end
end
|
github
|
vedaldi/mcnSSD-master
|
ssd_pascal_train.m
|
.m
|
mcnSSD-master/pascal/ssd_pascal_train.m
| 5,582 |
utf_8
|
6f40b91f660e510dcc290777ac0f3023
|
function ssd_pascal_train(varargin)
opts.gpus = [1] ;
opts.continue = true ;
opts.confirmConfig = true ;
opts.pruneCheckpoints = true ;
opts.architecture = 300 ;
opts.use_vl_imreadjpeg = false ;
opts = vl_argparse(opts, varargin) ;
% ---------------------------
% configure training options
% ---------------------------
train.batchSize = 32 ;
train.gpus = opts.gpus ;
train.continue = opts.continue ;
train.parameterServer.method = 'tmove' ;
train.numSubBatches = ceil(4 / max(numel(train.gpus), 1)) ;
% Since losses in each batch are computed as a function of ground truth
% matches rather than batch size, we scale up the final derivative to "undo"
% the derivative normalisation performed in cnn_train_dag
derScale = train.batchSize / (train.numSubBatches * numel(opts.gpus)) ;
train.derOutputs = {'mbox_loss', derScale} ;
% -------------------------
% configure dataset options
% -------------------------
dataOpts.name = 'pascal' ;
dataOpts.trainData = '0712' ;
dataOpts.testData = '07' ;
dataOpts.flipAugmentation = true ;
dataOpts.zoomAugmentation = false ;
dataOpts.patchAugmentation = true ;
dataOpts.useValForTraining = true ;
dataOpts.distortAugmentation = true ;
dataOpts.zoomScale = 4 ;
dataOpts.getImdb = @getPascalImdb ;
dataOpts.prepareImdb = @prepareImdb ;
dataOpts.dataRoot = fullfile(vl_rootnn, 'data', 'datasets') ;
% -------------------------
% configure model options
% -------------------------
modelOpts.type = 'ssd' ;
modelOpts.numClasses = 21 ;
modelOpts.clipPriors = false ;
modelOpts.net_init = @ssd_init ;
modelOpts.deploy_func = @ssd_deploy ;
modelOpts.batchSize = train.batchSize ;
modelOpts.get_batch = @ssd_train_get_batch ;
modelOpts.architecture = opts.architecture ;
% -------------------------
% Set learning rates
% -------------------------
warmup = 0.0001 ;
steadyLR = 0.001 ;
gentleLR = 0.0001 ;
vGentleLR = 0.00001 ;
if dataOpts.zoomAugmentation
numSteadyEpochs = 155 ;
numGentleEpochs = 38 ;
numVeryGentleEpochs = 38 ;
else
numSteadyEpochs = 75 ;
numGentleEpochs = 35 ;
numVeryGentleEpochs = 0 ;
end
steady = steadyLR * ones(1, numSteadyEpochs) ;
gentle = gentleLR * ones(1, numGentleEpochs) ;
veryGentle = vGentleLR * ones(1, numVeryGentleEpochs) ;
train.learningRate = [warmup steady gentle veryGentle] ;
train.numEpochs = numel(train.learningRate) ;
% ----------------------------
% configure batch opts
% ----------------------------
batchOpts.clipTargets = true ;
batchOpts.imageSize = repmat(modelOpts.architecture, 1, 2) ;
batchOpts.patchOpts.use = dataOpts.patchAugmentation ;
batchOpts.patchOpts.numTrials = 50 ;
batchOpts.patchOpts.minPatchScale = 0.3 ;
batchOpts.patchOpts.maxPatchScale = 1 ;
batchOpts.patchOpts.minAspect = 0.5 ;
batchOpts.patchOpts.maxAspect = 2 ;
batchOpts.patchOpts.clipTargets = batchOpts.clipTargets ;
batchOpts.flipOpts.use = dataOpts.flipAugmentation ;
batchOpts.flipOpts.prob = 0.5 ;
batchOpts.zoomOpts.use = dataOpts.zoomAugmentation ;
batchOpts.zoomOpts.prob = 0.5 ;
batchOpts.zoomOpts.minScale = 1 ;
batchOpts.zoomOpts.maxScale = dataOpts.zoomScale ;
batchOpts.distortOpts.use = dataOpts.distortAugmentation ;
batchOpts.distortOpts.brightnessProb = 0.5 ;
batchOpts.distortOpts.contrastProb = 0.5 ;
batchOpts.distortOpts.saturationProb = 0.5 ;
batchOpts.distortOpts.hueProb = 0.5 ;
batchOpts.distortOpts.brightnessDelta = 32 ;
batchOpts.distortOpts.contrastLower = 0.5 ;
batchOpts.distortOpts.contrastUpper = 1.5 ;
batchOpts.distortOpts.hueDelta = 18 ;
batchOpts.distortOpts.saturationLower = 0.5 ;
batchOpts.distortOpts.saturationUpper = 1.5 ;
batchOpts.distortOpts.randomOrderProb = 0 ;
batchOpts.numThreads = 2 ;
batchOpts.prefetch = false ;
batchOpts.useGpu = numel(train.gpus) > 0 ;
batchOpts.use_vl_imreadjpeg = opts.use_vl_imreadjpeg ;
batchOpts.resizeMethods = {'bilinear', 'box', 'nearest', 'bicubic', 'lanczos2'} ;
% determine experiment name
expName = getExpName(modelOpts, dataOpts) ;
expDir = fullfile(vl_rootnn, 'data', dataOpts.name, expName) ;
% -------------------------
% configure paths
% -------------------------
dataOpts.imdbPath = fullfile(vl_rootnn, 'data', dataOpts.name, ...
'/standard_imdb/imdb.mat') ;
modelOpts.deployPath = fullfile(expDir, 'deployed', ...
sprintf('local-%s-%s-%d-%%d.mat', modelOpts.type, ...
dataOpts.name, modelOpts.architecture)) ;
% -------------------------
% configure meta options
% -------------------------
opts.train = train ;
opts.dataOpts = dataOpts ;
opts.modelOpts = modelOpts ;
opts.batchOpts = batchOpts ;
opts.eval_func = @ssd_pascal_evaluation ;
% run
ssd_train(expDir, opts) ;
% ---------------------------------------------------
function [opts, imdb] = prepareImdb(imdb, opts)
% ---------------------------------------------------
% set path to VOC 2007 devkit directory
switch opts.dataOpts.trainData
case '07'
% to restrict to 2007, remove training 2012 data
imdb.images.set(imdb.images.year == 2012 & imdb.images.set == 1) = -1 ;
case '12'
% to restrict to 2012, remove 2007 training data
imdb.images.set(imdb.images.year == 2007 & imdb.images.set == 1) = -1 ;
case '0712'
; % do nothing ( use full dataset)
otherwise
error(sprintf('Training data %s not recognized', ...
opts.dataOpts.trainData)) ;
end
opts.train.val = find(imdb.images.set == 2) ;
if opts.dataOpts.useValForTraining
opts.train.train = find(imdb.images.set == 2 | imdb.images.set == 1) ;
end
|
github
|
vedaldi/mcnSSD-master
|
ssd_pascal_evaluation.m
|
.m
|
mcnSSD-master/pascal/ssd_pascal_evaluation.m
| 5,925 |
utf_8
|
4fb44fc4c94fd54bbcc87268d62ba3ff
|
function ssd_pascal_evaluation(varargin)
%SSD_PASCAL_EVALUATION evaluate SSD detector on pascal VOC
opts.net = [] ;
opts.gpus = 2 ;
opts.evalVersion = 'fast' ;
opts.modelName = 'ssd-pascal-vggvd-300' ;
% configure batch opts
opts.batchOpts.batchSize = 8 ;
opts.batchOpts.numThreads = 4 ;
opts.batchOpts.use_vl_imreadjpeg = true ;
opts.batchOpts.scaleInputs = 0.007843 ;
opts.batchOpts.imMean = [123, 117, 104] ;
opts = vl_argparse(opts, varargin) ;
% load network
if isempty(opts.net)
net = ssd_zoo(opts.modelName) ;
else
net = opts.net ;
end
% evaluation options
opts.testset = 'test' ;
opts.prefetch = true ;
opts.fixedSizeInputs = false ;
% cache configuration
cacheOpts.refreshPredictionCache = false ;
cacheOpts.refreshDecodedPredCache = false ;
cacheOpts.refreshEvaluationCache = true ;
cacheOpts.refreshFigures = true ;
% configure model options
modelOpts.predVar = 'detection_out' ;
modelOpts.get_eval_batch = @ssd_eval_get_batch ;
% batch options
opts.batchOpts.imageSize = net.meta.normalization.imageSize ;
% configure dataset options
dataOpts.name = 'pascal' ;
dataOpts.decoder = 'serial' ;
dataOpts.getImdb = @getPascalImdb ;
dataOpts.eval_func = @pascal_eval_func ;
dataOpts.evalVersion = opts.evalVersion ;
dataOpts.displayResults = @displayPascalResults ;
dataOpts.dataRoot = fullfile(vl_rootnn, 'data', 'datasets') ;
dataOpts.imdbPath = fullfile(vl_rootnn, 'data/pascal/standard_imdb/imdb.mat') ;
dataOpts.configureImdbOpts = @configureImdbOpts ;
dataOpts.resultsFormat = 'minMax' ;
% configure paths
tail = fullfile('evaluations', dataOpts.name, opts.modelName) ;
expDir = fullfile(vl_rootnn, 'data', tail) ;
resultsFile = sprintf('%s-%s-results.mat', opts.modelName, opts.testset) ;
rawPredsFile = sprintf('%s-%s-raw-preds.mat', opts.modelName, opts.testset) ;
decodedPredsFile = sprintf('%s-%s-decoded.mat', opts.modelName, opts.testset) ;
evalCacheDir = fullfile(expDir, 'eval_cache') ;
if ~exist(evalCacheDir, 'dir')
mkdir(evalCacheDir) ;
mkdir(fullfile(evalCacheDir, 'cache')) ;
end
cacheOpts.rawPredsCache = fullfile(evalCacheDir, rawPredsFile) ;
cacheOpts.decodedPredsCache = fullfile(evalCacheDir, decodedPredsFile) ;
cacheOpts.resultsCache = fullfile(evalCacheDir, resultsFile) ;
cacheOpts.evalCacheDir = evalCacheDir ;
% configure meta options
opts.dataOpts = dataOpts ;
opts.modelOpts = modelOpts ;
opts.cacheOpts = cacheOpts ;
ssd_evaluation(expDir, net, opts) ;
% ------------------------------------------------------------------
function aps = pascal_eval_func(modelName, decodedPreds, imdb, opts)
% ------------------------------------------------------------------
numClasses = numel(imdb.meta.classes) - 1 ; % exclude background
aps = zeros(numClasses, 1) ;
for c = 1:numClasses
className = imdb.meta.classes{c + 1} ; % offset for background
results = eval_voc(className, ...
decodedPreds.imageIds{c}, ...
decodedPreds.bboxes{c}, ...
decodedPreds.scores{c}, ...
opts.dataOpts.VOCopts, ...
'evalVersion', opts.dataOpts.evalVersion) ;
fprintf('%s %.1\n', className, 100 * results.ap) ;
aps(c) = results.ap_auc ;
end
save(opts.cacheOpts.resultsCache, 'aps') ;
% -----------------------------------------------------------
function opts = configureImdbOpts(expDir, opts)
% -----------------------------------------------------------
% configure VOC options
% (must be done after the imdb is in place since evaluation
% paths are set relative to data locations)
opts.dataOpts = configureVOC(expDir, opts.dataOpts, 'test') ;
%-----------------------------------------------------------
function dataOpts = configureVOC(expDir, dataOpts, testset)
%-----------------------------------------------------------
% LOADPASCALOPTS Load the pascal VOC database options
%
% NOTE: The Pascal VOC dataset has a number of directories
% and attributes. The paths to these directories are
% set using the VOCdevkit code. The VOCdevkit initialization
% code assumes it is being run from the devkit root folder,
% so we make a note of our current directory, change to the
% devkit root, initialize the pascal options and then change
% back into our original directory
VOCRoot = fullfile(dataOpts.dataRoot, 'VOCdevkit2007') ;
VOCopts.devkitCode = fullfile(VOCRoot, 'VOCcode') ;
% check the existence of the required folders
assert(logical(exist(VOCRoot, 'dir')), 'VOC root directory not found') ;
assert(logical(exist(VOCopts.devkitCode, 'dir')), 'devkit code not found') ;
currentDir = pwd ; cd(VOCRoot) ; addpath(VOCopts.devkitCode) ;
VOCinit ; % VOCinit loads database options into a variable called VOCopts
dataDir = fullfile(VOCRoot, '2007') ;
VOCopts.localdir = fullfile(dataDir, 'local') ;
VOCopts.imgsetpath = fullfile(dataDir, 'ImageSets/Main/%s.txt') ;
VOCopts.imgpath = fullfile(dataDir, 'ImageSets/Main/%s.txt') ;
VOCopts.annopath = fullfile(dataDir, 'Annotations/%s.xml') ;
VOCopts.cacheDir = fullfile(expDir, '2007/Results/Cache') ;
VOCopts.drawAPCurve = false ;
VOCopts.testset = testset ;
detDir = fullfile(expDir, 'VOCdetections') ;
% create detection and cache directories if required
requiredDirs = {VOCopts.localdir, VOCopts.cacheDir, detDir} ;
for i = 1:numel(requiredDirs)
reqDir = requiredDirs{i} ;
if ~exist(reqDir, 'dir') , mkdir(reqDir) ; end
end
VOCopts.detrespath = fullfile(detDir, sprintf('%%s_det_%s_%%s.txt', 'test')) ;
dataOpts.VOCopts = VOCopts ;
cd(currentDir) ; % return to original directory
% ---------------------------------------------------------------------------
function displayPascalResults(modelName, aps, opts)
% ---------------------------------------------------------------------------
fprintf('\n============\n') ;
fprintf(sprintf('%s set performance of %s:', opts.testset, modelName)) ;
fprintf('%.1f (mean ap) \n', 100 * mean(aps)) ;
fprintf('\n============\n') ;
|
github
|
vedaldi/mcnSSD-master
|
vocSetup.m
|
.m
|
mcnSSD-master/pascal/vocSetup.m
| 10,820 |
utf_8
|
b83de8160d7f7d8d2127d3722f17144c
|
function imdb = vocSetup(varargin)
opts.edition = '12' ;
opts.dataDir = fullfile(vl_rootnn, 'data','datasets', 'voc07') ;
opts.archiveDir = fullfile(vl_rootnn, 'data', 'archives') ;
opts.includeDetection = false ;
opts.includeDevkit = false ;
opts.includeSegmentation = false ;
opts.includeTest = true ;
opts = vl_argparse(opts, varargin) ;
% Download data
if ~exist(fullfile(opts.dataDir,'Annotations'))
download(opts) ;
end
% Source images and classes
imdb.paths.image = esc(fullfile(opts.dataDir, 'JPEGImages', '%s.jpg')) ;
imdb.sets.id = uint8([1 2 3]) ;
imdb.sets.name = {'train', 'val', 'test'} ;
imdb.classes.id = uint8(1:20) ;
imdb.classes.name = {...
'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', ...
'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', ...
'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'} ;
imdb.classes.images = cell(1,20) ;
imdb.images.id = [] ;
imdb.images.name = {} ;
imdb.images.set = [] ;
index = containers.Map() ;
[imdb, index] = addImageSet(opts, imdb, index, 'train', 1) ;
[imdb, index] = addImageSet(opts, imdb, index, 'val', 2) ;
if opts.includeTest
[imdb, index] = addImageSet(opts, imdb, index, 'test', 3) ;
end
% Source segmentations
if opts.includeSegmentation
n = numel(imdb.images.id) ;
imdb.paths.objectSegmentation = esc(fullfile(opts.dataDir, ...
'SegmentationObject', '%s.png')) ;
imdb.paths.classSegmentation = esc(fullfile(opts.dataDir, ...
'SegmentationClass', '%s.png')) ;
imdb.images.segmentation = false(1, n) ;
[imdb, index] = addSegmentationSet(opts, imdb, index, 'train', 1) ;
[imdb, index] = addSegmentationSet(opts, imdb, index, 'val', 2) ;
if opts.includeTest
[imdb, index] = addSegmentationSet(opts, imdb, index, 'test', 3) ;
end
end
% Compress data types
imdb.images.id = uint32(imdb.images.id) ;
imdb.images.set = uint8(imdb.images.set) ;
for i=1:20
imdb.classes.images{i} = uint32(imdb.classes.images{i}) ;
end
% Source detections
if opts.includeDetection
imdb.aspects.id = uint8(1:5) ;
imdb.aspects.name = {'front', 'rear', 'left', 'right', 'misc'} ;
imdb = addDetections(opts, imdb) ;
end
% Check images on disk and get their size
imdb = getImageSizes(imdb) ;
% -------------------------------------------------------------------------
function download(opts)
% -------------------------------------------------------------------------
baseUrl = 'http://host.robots.ox.ac.uk:8080' ;
switch opts.edition
case '07',
endpoint = sprintf('%s/pascal/VOC/voc2007', baseUrl) ;
url = sprintf('%s/VOCtrainval_06-Nov-2007.tar', endpoint) ;
testUrl = sprintf('%s/VOCtest_06-Nov-2007.tar', endpoint) ;
devkitUrl = sprintf('%s/VOCdevkit_08-Jun-2007.tar', endpoint) ;
case '08',
url='' ;
case '09'
url='' ;
case '10'
url=sprintf('%s/pascal_trainval/VOCtrainval_03-May-2010.tar', baseUrl) ;
case '11'
url=sprintf('%s/pascal_trainval/VOCtrainval_25-May-2011.tar', baseUrl) ;
case '12'
url=sprintf('%s/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar', baseUrl) ;
end
trainvalData = sprintf('VOC20%strainval.tar', opts.edition) ;
testData = sprintf('VOC20%stest.tar', opts.edition) ;
devkit = sprintf('VOC20%sdevkit.tar', opts.edition) ;
if ~exist(opts.archiveDir),
mkdir(opts.archiveDir) ;
end
archivePath = fullfile(opts.archiveDir, trainvalData) ;
if ~exist(archivePath)
fprintf('%s: downloading %s to %s\n', mfilename, url, archivePath) ;
urlwrite(url, archivePath) ;
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, opts.dataDir) ;
if opts.includeDevkit
devkitDir = fileparts(opts.dataDir) ;
archivePath = fullfile(opts.archiveDir, devkit) ;
if ~exist(archivePath)
fprintf('%s: downloading %s to %s\n', mfilename, devkitUrl, archivePath) ;
urlwrite(devkitUrl, archivePath) ;
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, devkitDir) ;
movefile(fullfile(devkitDir, 'VOCdevkit', '*'), devkitDir) ;
rmdir(fullfile(devkitDir, 'VOCdevkit')) ;
end
if opts.includeTest
archivePath = fullfile(opts.archiveDir, testData) ;
if ~exist(archivePath)
try
fprintf('attempting download %s to %s\n', testUrl, archivePath) ;
urlwrite(testUrl, archivePath) ;
catch
error(strcat('Cannot download the test data automatically. Please ', ...
' download the file %s manually from the PASCAL test server.'), ...
archivePath) ;
end
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, opts.dataDir) ;
end
switch opts.edition
case '11'
movefile(fullfile(opts.dataDir, 'Test', 'VOCdevkit', ...
sprintf('VOC20%s',opts.edition), '*'), opts.dataDir) ;
rmdir(fullfile(opts.dataDir, 'Test'),'s') ;
otherwise
movefile(fullfile(opts.dataDir, 'VOCdevkit', ...
sprintf('VOC20%s',opts.edition), '*'), opts.dataDir) ;
rmdir(fullfile(opts.dataDir, 'VOCdevkit'),'s') ;
end
% -------------------------------------------------------------------------
function [imdb, index] = addImageSet(opts, imdb, index, setName, setCode)
% -------------------------------------------------------------------------
j = length(imdb.images.id) ;
for ci = 1:length(imdb.classes.name)
className = imdb.classes.name{ci} ;
annoPath = fullfile(opts.dataDir, 'ImageSets', 'Main', ...
[className '_' setName '.txt']) ;
fprintf('%s: reading %s\n', mfilename, annoPath) ;
[names,labels] = textread(annoPath, '%s %f') ;
for i=1:length(names)
if ~index.isKey(names{i})
j = j + 1 ;
index(names{i}) = j ;
imdb.images.id(j) = j ;
imdb.images.set(j) = setCode ;
imdb.images.name{j} = names{i} ;
imdb.images.classification(j) = true ;
else
j = index(names{i}) ;
end
if labels(i) > 0, imdb.classes.images{ci}(end+1) = j ; end
end
end
% -------------------------------------------------------------------------
function [imdb, index] = addSegmentationSet(opts, imdb, index, setName, setCode)
% -------------------------------------------------------------------------
segAnnoPath = fullfile(opts.dataDir, 'ImageSets', 'Segmentation', [setName '.txt']) ;
fprintf('%s: reading %s\n', mfilename, segAnnoPath) ;
segNames = textread(segAnnoPath, '%s') ;
j = numel(imdb.images.id) ;
for i=1:length(segNames)
if index.isKey(segNames{i})
k = index(segNames{i}) ;
imdb.images.segmentation(k) = true ;
imdb.images.set(k) = setCode ;
else
j = j + 1 ;
index(segNames{i}) = j ;
imdb.images.id(j) = j ;
imdb.images.set(j) = setCode ;
imdb.images.name{j} = segNames{i} ;
imdb.images.classification(j) = false ;
imdb.images.segmentation(j) = true ;
end
end
% -------------------------------------------------------------------------
function imdb = getImageSizes(imdb)
% -------------------------------------------------------------------------
for j=1:numel(imdb.images.id)
info = imfinfo(sprintf(imdb.paths.image, imdb.images.name{j})) ;
imdb.images.size(:,j) = uint16([info.Width ; info.Height]) ;
fprintf('%s: checked image %s [%d x %d]\n', ...
mfilename, imdb.images.name{j}, info.Height, info.Width) ;
end
% -------------------------------------------------------------------------
function imdb = addDetections(opts, imdb)
% -------------------------------------------------------------------------
rois = {} ;
k = 0 ;
fprintf('%s: getting detections for %d images\n', mfilename, ...
numel(imdb.images.id)) ;
for j=1:numel(imdb.images.id)
fprintf('.') ; if mod(j,80)==0,fprintf('\n') ; end
name = imdb.images.name{j} ;
annoPath = fullfile(opts.dataDir, 'Annotations', [name '.xml']) ;
if ~exist(annoPath, 'file')
if imdb.images.classification(j) && imdb.images.set(j) ~= 3
warning(strcat('Could not find detection annotations for ', ...
'image ''%s''. Skipping.'), name) ;
end
continue ;
end
doc = xmlread(annoPath) ;
x = parseXML(doc, doc.getDocumentElement()) ;
% figure(1) ; clf ;
% imagesc(imread(sprintf(imdb.paths.image,imdb.images.name{j}))) ;
for q = 1:numel(x.object)
xmin = sscanf(x.object(q).bndbox.xmin,'%d') ;
ymin = sscanf(x.object(q).bndbox.ymin,'%d') ;
xmax = sscanf(x.object(q).bndbox.xmax,'%d') - 1 ;
ymax = sscanf(x.object(q).bndbox.ymax,'%d') - 1 ;
k = k + 1 ;
roi.id = k ;
roi.image = imdb.images.id(j) ;
roi.class = find(strcmp(x.object(q).name, imdb.classes.name)) ;
roi.box = [xmin;ymin;xmax;ymax] ;
roi.difficult = logical(sscanf(x.object(q).difficult,'%d')) ;
roi.truncated = logical(sscanf(x.object(q).truncated,'%d')) ;
if isfield(x.object(q),'occluded')
roi.occluded = logical(sscanf(x.object(q).occluded,'%d')) ;
else
roi.occluded = false ;
end
switch x.object(q).pose
case 'frontal', roi.aspect = 1 ;
case 'rear', roi.aspect = 2 ;
case {'sidefaceleft', 'left'}, roi.aspect = 3 ;
case {'sidefaceright', 'right'}, roi.aspect = 4 ;
case {'','unspecified'}, roi.aspect = 5 ;
otherwise, error(sprintf('Unknown view ''%s''', x.object(q).pose)) ;
end
rois{k} = roi ;
end
end
fprintf('\n') ;
rois = horzcat(rois{:}) ;
imdb.objects = struct(...
'id', uint32([rois.id]), ...
'image', uint32([rois.image]), ...
'class', uint8([rois.class]), ...
'box', single([rois.box]), ...
'difficult', [rois.difficult], ...
'truncated', [rois.truncated], ...
'occluded', [rois.occluded], ...
'aspect', uint8([rois.aspect])) ;
% -------------------------------------------------------------------------
function value = parseXML(doc, x)
% -------------------------------------------------------------------------
text = {''} ;
opts = struct ;
if x.hasChildNodes
for c = 1:x.getChildNodes().getLength()
y = x.getChildNodes().item(c-1) ;
switch y.getNodeType()
case doc.TEXT_NODE
text{end+1} = lower(char(y.getData())) ;
case doc.ELEMENT_NODE
param = lower(char(y.getNodeName())) ;
if strcmp(param, 'part'), continue ; end
value = parseXML(doc, y) ;
if ~isfield(opts, param)
opts.(param) = value ;
else
opts.(param)(end+1) = value ;
end
end
end
if numel(fieldnames(opts)) > 0
value = opts ;
else
value = strtrim(horzcat(text{:})) ;
end
end
% -------------------------------------------------------------------------
function str=esc(str)
% -------------------------------------------------------------------------
str = strrep(str, '\', '\\') ;
|
github
|
vedaldi/mcnSSD-master
|
getPascalImdb.m
|
.m
|
mcnSSD-master/pascal/getPascalImdb.m
| 5,062 |
utf_8
|
6766fbe01fbab02e0b5b7b794636822c
|
function imdb = getPascalImdb(opts, varargin)
% LOADIMDB loads Pascal VOC image database
%
% Inspiration ancestry for code:
% A.Vedaldi -> R.Girshick -> S.Albanie
opts.excludeDifficult = false ;
opts = vl_argparse(opts, varargin) ;
% Although the 2012 data can be used during training, only
% the 2007 test data is used for evaluation
opts.VOCRoot = fullfile(opts.dataOpts.dataRoot, 'VOCdevkit2007' ) ;
opts.devkitCode = fullfile(opts.VOCRoot, 'VOCcode') ;
imdb = loadImdb(opts) ;
opts.pascalOpts = loadPascalOpts(opts) ;
% add meta information (inlcuding background class)
imdb.meta.classes = {'background' opts.pascalOpts.classes{:}} ;
classIds = 1:numel(imdb.meta.classes) ;
imdb.classMap = containers.Map(imdb.meta.classes, classIds) ;
imdb.images.ext = 'jpg' ;
imdb.meta.sets = {'train', 'val', 'test'} ;
%-----------------------------------------
function pascalOpts = loadPascalOpts(opts)
%-----------------------------------------
% LOADPASCALOPTS Load the pascal VOC database options
%
% NOTE: The Pascal VOC dataset has a number of directories
% and attributes. The paths to these directories are
% set using the VOCdevkit code. The VOCdevkit initialization
% code assumes it is being run from the devkit root folder,
% so we make a note of our current directory, change to the
% devkit root, initialize the pascal options and then change
% back into our original directory
% check the existence of the required folders
assert(logical(exist(opts.VOCRoot, 'dir')), 'VOC root directory not found') ;
assert(logical(exist(opts.devkitCode, 'dir')), 'devkit code not found') ;
currentDir = pwd ;
cd(opts.VOCRoot) ;
addpath(opts.devkitCode) ;
% VOCinit loads database options into a variable called VOCopts
VOCinit ;
% Note - loads the options
pascalOpts = VOCopts ;
cd(currentDir) ;
%-----------------------------
function imdb = loadImdb(opts)
%-----------------------------
cache07 = '/tmp/07.mat' ;
if ~exist(cache07, 'file')
dataDir07 = fullfile(opts.dataOpts.dataRoot, 'VOCdevkit2007', '2007') ;
imdb07 = vocSetup('edition', '07', ...
'dataDir', dataDir07, ...
'archiveDir', dataDir07, ...
'includeDevkit', true, ...
'includeTest', true, ...
'includeDetection', true, ...
'includeSegmentation', false) ;
save(cache07, '-struct', 'imdb07') ;
else
imdb07 = load(cache07) ;
end
cache12 = '/tmp/12.mat' ;
if ~exist(cache12, 'file')
dataDir12 = fullfile(opts.dataOpts.dataRoot, 'VOCdevkit2012', '2012') ;
imdb12 = vocSetup('edition', '12', ...
'dataDir', dataDir12, ...
'archiveDir', dataDir12, ...
'includeTest', false, ...
'includeDetection', true, ...
'includeSegmentation', false) ;
save(cache12, '-struct', 'imdb12') ;
else
imdb12 = load(cache12) ;
end
imdb = combineImdbs(imdb07, imdb12, opts) ;
% ------------------------------------------------
function imdb = combineImdbs(imdb07, imdb12, opts)
% ------------------------------------------------
imdb.images.name = horzcat(imdb07.images.name, ...
imdb12.images.name) ;
imdb.images.set = horzcat(imdb07.images.set, ...
imdb12.images.set) ;
imdb.images.year = horzcat(ones(1,numel(imdb07.images.name)) * 2007, ...
ones(1,numel(imdb12.images.name)) * 2012) ;
imageSizes = horzcat(imdb07.images.size, imdb12.images.size ) ;
paths = vertcat(repmat(imdb07.paths.image, numel(imdb07.images.name), 1), ...
repmat(imdb12.paths.image, numel(imdb12.images.name), 1)) ;
imdb.images.paths = arrayfun(@(x) paths(x,:), 1:size(paths, 1),'Uni', 0) ;
% for consistency, store in Height-Width order
imdb.images.imageSizes = arrayfun(@(x) imageSizes([2 1],x)', ...
1:size(imageSizes, 2), 'Uni', 0) ;
annot07 = loadAnnotations(imdb07, opts) ;
annot12 = loadAnnotations(imdb12, opts) ;
imdb.annotations = horzcat(annot07, annot12) ;
% ------------------------------------------------
function annotations = loadAnnotations(imdb, opts)
% ------------------------------------------------
annotations = cell(1, numel(imdb.images.name)) ;
for i = 1:numel(imdb.images.name)
match = find(imdb.objects.image == i) ;
% normalize annotation
if opts.excludeDifficult
keep = ~[imdb.objects.difficult(match)] ;
else
keep = 1:numel(match) ;
end
match = match(keep) ;
boxes = imdb.objects.box(:,match) ;
classes = imdb.objects.class(match) ;
% normalize annotation
imSize = repmat(imdb.images.size(:, i)', [1 2]) ;
gt.boxes = bsxfun(@rdivide, boxes', single(imSize)) ;
gt.classes = classes + 1 ; % add offset for background
assert(all(2 <= gt.classes) && all(gt.classes <= 21), ...
'pascal class labels do not lie in the expected range') ;
annotations{i} = gt ;
fprintf('Loading annotaton %d \n', i) ;
end
|
github
|
vedaldi/mcnSSD-master
|
eval_voc.m
|
.m
|
mcnSSD-master/pascal/helpers/eval_voc.m
| 3,611 |
utf_8
|
bec81a2c9c611348c2df08b282fec8df
|
function res = eval_voc(cls, imageIds, bboxes, scores, VOCopts, varargin)
% EVAL_VOC evaluate detections on Pascal VOC
% RES = EVAL_VOC(CLS, IMAGEIDS, BBOXES, SCORES, VOCOPTS) evalutes a set of
% detections specified by BBOXES and SCORES for the given class, CLS.
% IMAGEIDS is a cell array containing the ids of the images associated
% with each score and bounding box.
%
% EVAL_VOC takes the following options:
% `suffix` :: ''
% A suffix which is appended to the result file generated by the script.
%
% `evalVersion` :: 'official'
% A string denoting the evaluation script to be used to produced results.
% 'official' indicates that the original script released with the pascal
% challnege should be used. However, since this runs extremely slowly,
% the option 'fast' may be used in development.
%
% `useResSalt` :: true
% If true, then a random string (known as a salt) is added to the end of the
% results file name (prevents concurrent evaluations from wreaking havoc by
% over-writing each other)
%
% `rmResults` :: true
% Delete results files after AP computations have completed
%
% `drawCurve` :: true
% plot a curve for the current class
%
% `compId` :: 'comp4'
% The identifier of the competition (comp4 indicates the use of outside
% data).
%
% Author: Samuel Albanie, based directly on Ross Girshick's R-CNN code
% (copyright licence inlcuded below)
%
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------
opts.suffix = '' ;
opts.useResSalt = true ;
opts.rmResults = true ;
opts.compId = 'comp4' ;
opts.drawCurve = true ;
opts.evalVersion = 'official' ;
[opts, ~] = vl_argparse(opts, varargin) ;
if ~strcmp(opts.suffix, ''), suffix = ['_' opts.suffix] ; end
if useResSalt
prev_rng = rng ; rng shuffle ; salt = sprintf('%d', randi(100000)) ;
res_id = [opts.compId '-' salt] ; rng(prev_rng) ;
else
res_id = opts.compId ;
end
resPath = sprintf(VOCopts.detrespath, res_id, cls) ;
fid = fopen(resPath, 'w') ; % write out detections in PASCAL format and score
for i = 1:numel(imageIds)
fprintf(fid, '%s %f %.3f %.3f %.3f %.3f\n', imageIds{i}, scores(i), bboxes(i,:));
end
fclose(fid) ;
tic ; % Bug in VOCevaldet requires that tic has been called first
switch opts.evalVersion
case 'official'
[recall, prec, ap] = VOCevaldet(VOCopts, res_id, cls, opts.drawCurve) ;
case 'fast'
[recall, prec, ap] = x10VOCevaldet(VOCopts, res_id, cls, opts.drawCurve) ;
otherwise
error('Evaluation version %s not recognised', opts.evalVersion) ;
end
ap_auc = VOCap07(recall, prec) ; % use 2007 evaluation
ylim([0 1]) ; xlim([0 1]) ; % fix plot limits
tail = sprintf('%s_pr_%s.jpg', cls, suffix) ;
print(gcf, '-djpeg', '-r0', fullfile(VOCopts.cacheDir, tail)) ;
fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc) ;
args = {'recall', 'prec', 'ap', 'ap_auc'} ;
save(fullfile(VOCopts.cacheDir, sprintf('%s_pr_%s',cls, suffix)), args) ;
res.recall = recall ; res.prec = prec ; res.ap = NaN ; res.ap_auc = ap_auc ;
if opts.rmResults, delete(resPath) ; end
% -----------------------------
function ap = VOCap07(rec,prec)
% -----------------------------
% From the PASCAL VOC 2007 devkit
ap = 0 ;
for t=0:0.1:1
p=max(prec(rec>=t)) ;
if isempty(p)
p=0 ;
end
ap=ap+p/11 ;
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
get_scaled_csi.m
|
.m
|
lip-motion-csi-master/get_scaled_csi.m
| 1,842 |
utf_8
|
25f6ee30c68e10fbfaaeff35624ab758
|
%GET_SCALED_CSI Converts a CSI struct to a channel matrix H.
%
% (c) 2008-2011 Daniel Halperin <[email protected]>
%
function ret = get_scaled_csi(csi_st)
% Pull out CSI
csi = csi_st.csi;
% Calculate the scale factor between normalized CSI and RSSI (mW)
csi_sq = csi .* conj(csi);
csi_pwr = sum(csi_sq(:));
rssi_pwr = dbinv(get_total_rss(csi_st));
% Scale CSI -> Signal power : rssi_pwr / (mean of csi_pwr)
scale = rssi_pwr / (csi_pwr / 30);
% Thermal noise might be undefined if the trace was
% captured in monitor mode.
% ... If so, set it to -92
if (csi_st.noise == -127)
noise_db = -92;
else
noise_db = csi_st.noise;
end
thermal_noise_pwr = dbinv(noise_db);
% Quantization error: the coefficients in the matrices are
% 8-bit signed numbers, max 127/-128 to min 0/1. Given that Intel
% only uses a 6-bit ADC, I expect every entry to be off by about
% +/- 1 (total across real & complex parts) per entry.
%
% The total power is then 1^2 = 1 per entry, and there are
% Nrx*Ntx entries per carrier. We only want one carrier's worth of
% error, since we only computed one carrier's worth of signal above.
quant_error_pwr = scale * (csi_st.Nrx * csi_st.Ntx);
% Total noise and error power
total_noise_pwr = thermal_noise_pwr + quant_error_pwr;
% Ret now has units of sqrt(SNR) just like H in textbooks
ret = csi * sqrt(scale / total_noise_pwr);
if csi_st.Ntx == 2
ret = ret * sqrt(2);
elseif csi_st.Ntx == 3
% Note: this should be sqrt(3)~ 4.77 dB. But, 4.5 dB is how
% Intel (and some other chip makers) approximate a factor of 3
%
% You may need to change this if your card does the right thing.
ret = ret * sqrt(dbinv(4.5));
end
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
PCACleanCSI.m
|
.m
|
lip-motion-csi-master/PCACleanCSI.m
| 591 |
utf_8
|
ecabbb827a2fae88ce726a3665df522c
|
%%PCA the filter csi
%%input:filter the csi data
%%output:PCA csi data
function maincomponents=PCACleanCSI(filtercsi,num)
if (nargin<2)
num=3;%%select the component num
end
warning('off');
startc=2;%%start component
endc=startc+num-1;%%end component
[length,sender,receiver,~]=size(filtercsi);
maincomponents=zeros(length,sender,receiver,num);
for i=1:1:sender
for j=1:1:receiver
a=squeeze(filtercsi(:,i,j,:));
%[coef,score,latent,t2] = pca(a);
coef=pca(a);
maincomponents(:,i,j,:)=a*coef(:,startc:endc);
end
end
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
GetRawCSI.m
|
.m
|
lip-motion-csi-master/GetRawCSI.m
| 614 |
utf_8
|
b3dd515295a2a5a5e187f627fe080de3
|
%%get the raw CSI(not clean)
%file='csi-lip-6-23-train//6-23-all-train//6-23-all-1.dat';
%%input:filename,length:the collect csi data filename,csi length you need
%%output:raw csi data---4-D complex data
function csi=GetRawCSI(file,sender,receiver)
csi_trace=read_bf_file(file);%%read_csi
[length,~]=size(csi_trace);
channel=30;%%channel
csi=zeros(length,sender,receiver,channel);%%initialize the raw csi
for i=1:1:length
csi_entry=csi_trace{i};
a=get_scaled_csi(csi_entry);%%get the scaled csi
for k=1:1:sender
csi(i,k,:,:)=a(k,:,:);
end
end
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
FilterCSI.m
|
.m
|
lip-motion-csi-master/FilterCSI.m
| 921 |
utf_8
|
4ca0a62b1a326e6ce7518cafb5cb4b91
|
%%filter the noise from the csi signal
%%input:remove the multiple path csi signal
%%output:filter the csi
function filtercsi=FilterCSI(removedCSIInformation)
load SpeakHd2.mat;%%butterwords bandpass filter 0-5hz
[length,sender,receiver,channel]=size(removedCSIInformation);
amptitude=zeros(length,sender,receiver,channel);
filtercsi=zeros(length,sender,receiver,channel);
%%csi=squeeze(csi);
%%t=1:1:30;
%%abs(csi(1,1,:))
%%figure;
%for i=1:1:2
% for j=1:1:3
% plot(t,squeeze(db(abs(csi(i,j,:)))));
% hold on;
% end
% end
% hold off;
%for k=1:1:length
%for i=1:1:sender
% for j=1:1:receiver
% amptitude(k,i,j,:)=db(abs(removedCSIInformation(k,i,j,:)));
% end
%end
%end
amptitude(:,:,:,:)=(abs(removedCSIInformation(:,:,:,:)));
for i=1:1:sender
for j=1:1:receiver
for k=1:1:channel
filtercsi(:,i,j,k)=filter(SpeakHd2,amptitude(:,i,j,k));
end
end
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
DWTCSI.m
|
.m
|
lip-motion-csi-master/DWTCSI.m
| 861 |
utf_8
|
044d9eb3345b98e5366894ef05adc1ad
|
%%DWT the maincomponents
%%input:maincomponents
%%output:Dwtcomponents
function Dwtcomponents=DWTCSI(maincomponents,dwtnum)
if (nargin<2)
dwtnum=3;%%select the component num
end
warning('off');
[~,sender,receiver,num]=size(maincomponents);
[C,L] = wavedec(maincomponents(:,1,1,1),dwtnum,'db4');%%DWT3
tmp = appcoef(C,L,'db4',3);
[m,~]=size(tmp);
dwtcomponents=zeros(m,sender,receiver,num);
for i=1:1:sender
for j=1:1:receiver
for k=1:1:num
[C,L] = wavedec(maincomponents(:,i,j,k),dwtnum,'db4');
cA3 = appcoef(C,L,'db4',dwtnum);
dwtcomponents(:,i,j,k)=cA3;
end
end
end
Dwtcomponents=zeros(m,sender*receiver*num);
x=1;
for i=1:1:sender
for j=1:1:receiver
for k=1:1:num
Dwtcomponents(:,x)=squeeze(dwtcomponents(:,i,j,k));
x=x+1;
end
end
end
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
read_bf_file.m
|
.m
|
lip-motion-csi-master/read_bf_file.m
| 2,577 |
utf_8
|
3046107c2e85bb02155fda059099b086
|
%READ_BF_FILE Reads in a file of beamforming feedback logs.
% This version uses the *C* version of read_bfee, compiled with
% MATLAB's MEX utility.
%
% (c) 2008-2011 Daniel Halperin <[email protected]>
%
function ret = read_bf_file(filename)
%% Input check
error(nargchk(1,1,nargin));
%% Open file
f = fopen(filename, 'rb');
if (f < 0)
error('Couldn''t open file %s', filename);
return;
end
status = fseek(f, 0, 'eof');
if status ~= 0
[msg, errno] = ferror(f);
error('Error %d seeking: %s', errno, msg);
fclose(f);
return;
end
len = ftell(f);
status = fseek(f, 0, 'bof');
if status ~= 0
[msg, errno] = ferror(f);
error('Error %d seeking: %s', errno, msg);
fclose(f);
return;
end
%% Initialize variables
ret = cell(ceil(len/95),1); % Holds the return values - 1x1 CSI is 95 bytes big, so this should be upper bound
cur = 0; % Current offset into file
count = 0; % Number of records output
broken_perm = 0; % Flag marking whether we've encountered a broken CSI yet
triangle = [1 3 6]; % What perm should sum to for 1,2,3 antennas
%% Process all entries in file
% Need 3 bytes -- 2 byte size field and 1 byte code
while cur < (len - 3)
% Read size and code
field_len = fread(f, 1, 'uint16', 0, 'ieee-be');
code = fread(f,1);
cur = cur+3;
% If unhandled code, skip (seek over) the record and continue
if (code == 187) % get beamforming or phy data
bytes = fread(f, field_len-1, 'uint8=>uint8');
cur = cur + field_len - 1;
if (length(bytes) ~= field_len-1)
fclose(f);
return;
end
else % skip all other info
fseek(f, field_len - 1, 'cof');
cur = cur + field_len - 1;
continue;
end
if (code == 187) %hex2dec('bb')) Beamforming matrix -- output a record
count = count + 1;
ret{count} = read_bfee(bytes);
perm = ret{count}.perm;
Nrx = ret{count}.Nrx;
if Nrx == 1 % No permuting needed for only 1 antenna
continue;
end
if sum(perm) ~= triangle(Nrx) % matrix does not contain default values
if broken_perm == 0
broken_perm = 1;
fprintf('WARN ONCE: Found CSI (%s) with Nrx=%d and invalid perm=[%s]\n', filename, Nrx, int2str(perm));
end
else
ret{count}.csi(:,perm(1:Nrx),:) = ret{count}.csi(:,1:Nrx,:);
end
end
end
ret = ret(1:count);
%% Close file
fclose(f);
end
|
github
|
liweiwang1993/lip-motion-csi-master
|
RemoveMultiplePath.m
|
.m
|
lip-motion-csi-master/RemoveMultiplePath.m
| 1,206 |
utf_8
|
19f1188b685b7ab3599866547c3973a7
|
%%remove the multiple path distortion to clean the csi
%%input:raw csi---4-D complex data
%%output:remove the multiple path csi---4-D complex data
function removedCSIInformation=RemoveMultiplePath(csi)
warning('off');
[length,sender,receiver,channel] = size(csi);
removedCSIInformation=zeros(length,sender,receiver,channel);
interval = 20/30;%%Frequency interval
Sf=2433;%%starting frequency
Ef=2453;%%Ending frequency
for i=1:1:length
for j=1:1:sender
for k=1:1:receiver
a=csi(i,j,k,:);
b=a(:,:);
%figure
%plot(abs(csi));
%hold on
% approximate interval of subcarriers
%freq: 2431-2453 MHz
%number of zeros before CSI
numZeros = ceil(Sf/interval);
%make up carrier frequency response
cfr = [zeros(1,numZeros),b];
%slot of ifft
N = numZeros + channel;
%get approximate channel impluse response
cir = ifft(cfr,N);
t = 0:1/(Ef*2):1;
[~,tm]=size(t);
%%delay=0.5ms
RemovedCir=cir(1:round(tm/2));
RemovedCSI=fft(RemovedCir);
RemovedCSI=RemovedCSI((Sf+interval):interval:Ef);
removedCSIInformation(i,j,k,:)=RemovedCSI;
end
end
end
|
github
|
timlautk/BCoAPG-plus-master
|
scad_prox.m
|
.m
|
BCoAPG-plus-master/Tools/scad_prox.m
| 966 |
utf_8
|
9b021761670680d4cb732bd12f754068
|
function p = scad_prox(u,gamma,lambda)
p = zeros(size(u));
p1 = sign(u).*min(lambda,max(0,abs(u)-lambda));
p2 = sign(u).*min(gamma*lambda,max(lambda,(abs(u)*(gamma-1)-gamma*lambda)/(gamma-2)));
p3 = sign(u).*max(gamma*lambda,abs(u));
p((h(p1) < h(p2)) & (h(p1) < h(p3))) = p1((h(p1) < h(p2)) & (h(p1) < h(p3)));
p((h(p2) < h(p1)) & (h(p2) < h(p3))) = p2((h(p2) < h(p1)) & (h(p2) < h(p3)));
p((h(p3) < h(p1)) & (h(p3) < h(p2))) = p3((h(p3) < h(p1)) & (h(p3) < h(p2)));
function val = h(x)
val = zeros(size(x));
h1 = 0.5*(x-u).^2+lambda*abs(x);
h2 = 0.5*(x-u).^2+(2*gamma*lambda*abs(x)-x.^2-lambda^2)/(gamma-1);
h3 = 0.5*(x-u).^2+lambda^2*(gamma^2-1)/(2*(gamma-1));
val(abs(x) <= lambda) = h1(abs(x) <= lambda);
val(abs(x) > lambda & abs(x) <= gamma*lambda) = h2(abs(x) > lambda & abs(x) <= gamma*lambda);
val(abs(x) > gamma*lambda) = h3(abs(x) > gamma*lambda);
end
end
|
github
|
tskarhed/Space-Engineer-Notes-master
|
bikewheel.m
|
.m
|
Space-Engineer-Notes-master/MATLAB/bikewheel.m
| 3,926 |
utf_8
|
86ccbea3e5ae2d5385edc4e1174d5852
|
function bikewheel(radius, v, angle)
%Takes the radius of a circle (bikewheel) which rotates at a velocity v and
%calculates the trajectory for particles at angle
%Make a single variable so we don't have to retype
center = [radius radius];
%Draw the circle
drawCircle(radius, center);
hold on;
%points = randi(100, 1, 20);
%points = linspace(0, 2*pi);
%Rename variable becase of previous tests
points = angle;
index = 1;
%Rows 1:angles 2:slopes 3:length 4:height
%Good for debug etc.
attributes = zeros(4, numel(points));
%Make calculations for evey point
for alpha = points
%Generate point which are displaced 0.1radians from the initial point
%and calculate the slope between these two. That is the derivative in
%our point.
[ point1x, point1y ] = getCirclePoint(radius, alpha-0.1, center);
[ point2x, point2y ] = getCirclePoint(radius, alpha+0.1, center);
slope = (point2y-point1y)/(point2x-point1x);
%Save slope to matrix
attributes(2, index) = slope;
%Redistribute alpha to get in the interval [0, 2*pi]
redAlpha = wrapTo2Pi(alpha);
%-pi for angles gives us a positive angle in the opposite direction. It
%works ;)
if (pi < redAlpha) && (redAlpha < 2*pi)
attributes(1, index) = atan(slope)-pi;
else
attributes(1, index) = atan(slope);
end
%Draw the trajectory
[startX, startY] = getCirclePoint(radius, alpha, center);
%Set values for length and height in the matrix
[attributes(3, index), attributes(4, index)] = drawTrajectory(attributes(1, index), v, [startX startY]);
%Set index
index = index +1;
end
%Titles and labels
axis equal
title('Cykelstänk', 'fontsize', 20);
xlabel('Längd [m]', 'fontsize', 18);
ylabel('Höjd [m]', 'fontsize', 18);
%Get the longest trajectory
maxLength = max(attributes(3, :));
%Get the shortest trajectory
minLength = min(attributes(3, :));
%Draw ground and grass
plot([minLength maxLength], [0 0], 'LineWidth', 6, 'Color', 'g');
fill([minLength minLength maxLength maxLength], [0 -1 -1 0], [0.7 0.7 0.7], 'EdgeColor', 'none');
axis([-Inf Inf -1 Inf]);
hold off;
%Tell the command window that we are done!
disp('Done!');
end
function [ x, y ] = getCirclePoint( radius, angle, center )
%Returns a point at a give angle with a given radius
% Form center as coordinate vector center = [x y]
% Detailed explanation goes here
%y displacement of r
y = center(2)+sin(angle)*radius;
x = center(1)+cos(angle)*radius;
end
function drawCircle( radius, center )
%Draws a circle
angles = linspace(0, 2*pi);
[x, y] = getCirclePoint(radius, angles, center);
plot(x, y);
axis equal;
end
function [length, height] = drawTrajectory( angle, velocity, startPoint )
%Draws the trajectory of a particle which starts att [x y] = startPoint
%with an angle and a velocity.
% Detailed explanation goes here
%Gravity
g = 9.82;
%When the particle hits the ground
y = @(t) startPoint(2) + velocity*sin(angle)*t - (g*t.^2)/2;
%Find trajectory end
%Loop over y(t) and try values until they are equal to 0 (hit the ground).
%This solution is not good for big values of velocity, but realistically it
%would probably not exceed 20m/s
t=0;
y0 = y(t);
while y0 >= 0
y0 = y(t);
%Increase time with a very small step to have a good resolution of the
%answer
t = t+0.00001;
end
%%%THIS STUFF WORKS, BUT IT IS SLOW%%%
%syms altT; %Creates a "placeholder" variable
%equation = startPoint(2) + velocity*sin(angle)*altT-(g*altT^2)/2;%Equation where it hits the ground
%times = double(solve(equation, altT));%Solve the equation and give it a numerical value
%t = max(times); %Select the positive value
%Return the length/height of the parabola (in meters)
length = startPoint(1) + velocity*cos(angle)*t;
height = startPoint(2) + velocity*sin(angle)*t-(g*t^2)/2;
points = linspace(0, t);
x = @(t) startPoint(1) + velocity*cos(angle)*t;
plot(x(points), y(points));
end
|
github
|
paulmmacey/lmgs-master
|
cspm_lmgs.m
|
.m
|
lmgs-master/cspm_lmgs.m
| 17,957 |
utf_8
|
8ee7e17d952207b9823eedc9620c412b
|
function cspm_lmgs(Pin,overwrite,prefix,display,GM)
% CSPM_LMGS - Detrend fMRI image series using LMGS method.
% CSPM_LMGS(P, OVERWRITE, PREFIX, DISPLAY, GRANDMEAN )
% P is array of images returned by spm, e.g. (SPM2):
% P = spm_get(Inf, '.img',{'Please select images for detrending'});
% You will be prompted for the files if the argument is omitted.
% To pass multiple sessions, set P as a cell array with each cell the
% files for one session, i.e. (SPM5):
% P{1} = = spm_select([3 Inf],'image','Select images for detrending (1st session)');
% P{2} = = spm_select([3 Inf],'image','Select images for detrending (2nd session)');
% P{3} = = spm_select([3 Inf],'image','Select images for detrending (3rd session)');
% OVERWRITE (optional) - defaults to true; if false and detrended
% images exist, detrending is skipped.
% PREFIX (optional) - prefix for detrended files; defaults to "d".
% DISPLAY (optional) - if true, global trends of raw and detrended
% data are plotted; defaults to false.
% GRANDMEAN (optional) - scale series to this mean (e.g., 100); default 0 (no scaling);
%
% The procedure applies the detrending to the time-series of files P, and writes
% detrended files prepended with PREFIX (defaults to "d").
%
% To run in interactive mode, type
% >>cspm_lmgs
% Interactive mode defaults to overwrite TRUE and prefix "d".
%
% If at least one input argument is provided (P), the routine will run in batch
% mode and use the defaults of any arguments not passed.
%
%
% LMGS (Linear Model of Global Signal) detrending is described in:
% P.M. Macey, K.E. Macey, R. Kumar, and R.M. Harper. A method for removal of
% global effects from fMRI time series. NeuroImage 22 (2004) 360-366.
%
% Works with SPM5+ and SPM2.
%
% cspm_lmgs.m 1.4 Paul Macey 2017-08-23
% Thanks to Marko Wilke for the batch mode and grand mean scaling suggestions.
disp('========================================================================')
disp('LMGS-Detrending')
disp(' ')
% Check inputs
% Images
if nargin == 0
overwrite = 1;
prefix = 'd';
num_sessions = spm_input('Number of sessions to detrend', 1, 'n', 1);
Pall = cell(1,num_sessions);
for i = 1:num_sessions
if strcmp(spm('ver'),'SPM99') || strcmp(spm('ver'),'SPM2')
Pall{i} = spm_get([3 Inf], '.img',['Select images for detrending (session ',...
int2str(i),')']);
else
Pall{i} = spm_select([3 Inf],'image',['Select images for detrending (session ',...
int2str(i),')']);
end
% Couple of checks
if isempty(Pall{i}), return, end
if length(Pall{i}) < 3
msgbox('Detrending requires a time-series of images (multiple volumes)',...
'LMGS',...
'warn')
i = i-1; %#ok<FXSET>
if num_sessions == 1
return
end
end
end
display = spm_input('Show graphical results ?','+1','b',(' Yes| No'),[1 0],0);
disp('Grand Mean scaling sets session mean to GM')
GM = spm_input('Grand mean session scaling (0 = none)', '+1', 'e', 0);
else
% batch or silent mode
if iscell(Pin)
% Check case of cell array of filenames (i.e., one session)
if min(size(Pin{1})) == 1
Pall{1} = char(Pin);
else
Pall = Pin;
end
else
% One session only
Pall{1} = Pin;
end
num_sessions = length(Pall);
% Flags, etc.
if nargin < 2 || isempty(overwrite)
overwrite = 1;
end
if nargin < 3 || isempty(prefix)
prefix = 'd';
else
if ~ischar(prefix)
msgbox('Invalid "Prefix" argument - need character',...
'LMGS','error')
help cspm_lmgs
return
end
end
if nargin < 4
display = 0;
end
if nargin < 5
GM = 0;
end
end
for i = 1:num_sessions
if num_sessions > 1
disp(['Detrending session ',int2str(i)])
end
detrend_onesession(Pall{i},overwrite,prefix,display,GM,i,num_sessions)
end
disp('LMGS-Detrending complete.')
disp(' ')
end
% =========================================================================
function detrend_onesession(P,overwrite,prefix,display,GM,sn,num_sessions)
% Number of scans
nscan = size(P,1);
% Check for 4D
is4D = 0;
[pth,nm,ext] = fileparts(P(1,:));
I = find(ext==',',1,'first');
if ~isempty(I)
V = spm_vol([pth,filesep,nm,ext(1:I-1)]);
if length(V) > 1
is4D = 1;
disp('4D file - assuming all images belong to same 4D file')
end
end
% Finish now if overwrite flag is false and files exist
if ~overwrite
skip = 1;
% Check for existing files - if 4D only have one file
if is4D
thiscount = 1;
else
thiscount = nscan;
end
for i = 1:thiscount
[pth,nm,ext] = fileparts(P(i,:));
% Detrended
I = find(ext==',',1,'first');
if ~isempty(I)
ext = ext(1:I-1);
end
newfname = [pth,filesep,prefix,nm,ext];
if ~exist(newfname,'file')
skip = 0;
break
end
end
if skip, return, end
end
% Map volumes
V = spm_vol(P);
% Check similar dimensions, etc. (Taken from spm_imcalc_ui.)
flagDimOK = true;
if (strcmp(spm('ver'),'SPM99') || strcmp(spm('ver'),'SPM2'))
if any(any(diff(cat(1,V.dim),1,1),1)&[1,1,1,0])
flagDimOK = false;
end
elseif any(any(diff(cat(1,V.dim),1,1),1))
flagDimOK = false;
elseif any(any(any(diff(cat(3,V.mat),1,3),3)))
flagDimOK = false;
end
if ~flagDimOK
msgbox('Images don''t have same dimmensions, orientation and voxel size - detrending cancelled.',...
'LMGS','error')
return
end
% Number of voxels
num_vox = prod(V(1).dim(1:3));
% Initialize - create independent variable X for model
% Global values
gt = cspm_globaltrend(P,0,0,0)';
% Remove offset
X = detrend(gt,'constant');
% Add Constant
X = [X ones(nscan,1)];
% Create output images
% Preallocate
Vout = repmat( V(1), 1, nscan );
for i = 1:nscan
Vnew = V(i);
Vnew.dt(1) = spm_type('float32');
[pth,nm,ext] = fileparts(Vnew.fname);
I = find(ext==',',1,'first');
if ~isempty(I)
ext = ext(1:I-1);
end
if is4D
str = ['3D',num2str(i,'%03d')];
Vnew.n(1) = 1;
else
str = '';
end
Vnew.fname = [pth,filesep,prefix,nm,str,ext];
if strcmp(spm('ver'),'SPM99')
Vout(i) = spm_create_image(Vnew);
else
Vout(i) = spm_create_vol(Vnew);
end
end
adjustcount = 0;
num_vox_per_plane = num_vox / V(1).dim(3);
dim1 = V(1).dim(1);
dim2 = V(1).dim(2);
dim3 = V(1).dim(3);
dim12 = V(1).dim(1:2);
% Loop through planes
fprintf('\n%-60s','Detrending')
for z = 1:dim3
fprintf('%s%-60s',char(sprintf('\b')*ones(1,60)),...
['Detrending plane ',int2str(z),' / ',int2str(dim3)])
% Get raw data for plane across all volumes.
yn = zeros(dim1,dim2,nscan);
for i = 1:nscan
yn(:,:,i) = spm_slice_vol(V(i),spm_matrix([0 0 z]),dim12,0);
end
% Use 2-D array to speed processing.
yadj = reshape(yn,num_vox_per_plane,nscan)';
s = warning; warning off
% Perform detrending voxel-by-voxel in this plane
for v = 1:num_vox_per_plane
yvox = yadj(:,v);
if any(yvox)
b = regression(yvox,X);
% The following would require the statistics toolbox:
% [b,bint,r,rint,stats] = regress(yvox,X,0.05);
% Test for positive effect - b(1);
% Test for significance as p-value - - stats(3);
% Test for correlation (R^2) - stats(1)
% Optional: skip voxels that do not meet thresholds
% if b(1) <= 0 | stats(3) > 0.8 | stats(1) < 0.3
% continue
% end
% Another option: remove only voxels that show positive correlations
% if b(1) <= 0
% continue
% end
yvoxmodel = b(1)*X(:,1);
% Adjust time-series
adjustcount = adjustcount + 1;
yadj(:,v) = yvox - yvoxmodel;
end
end
warning(s)
yadj = reshape(yadj',dim1,dim2,nscan);
% Write adjusted data
for i = 1:nscan
Vout(i) = spm_write_plane(Vout(i),yadj(:,:,i),z);
end
end % End loop through planes
fprintf('%s%-60s',char(sprintf('\b')*ones(1,60)),'Detrending')
fprintf('%-60s\n','Done')
disp(['Adjusted ', int2str(adjustcount),...
' non-zero voxels (',int2str(num_vox),' total).'])
disp(' ')
% Save file names if displaying or scaling (or if 4D, saving back to single 4D
% file)
if display || GM > 0 || is4D
Pd = cell(nscan,1);
for i = 1:nscan
% Pin{i} = V(i).fname;
Pd{i} = Vout(i).fname;
end
end
% Close volumes, if SPM2
if strcmp(spm('ver'),'SPM2')
spm_close_vol(V);
spm_close_vol(Vout);
end
% Grand mean scaling
if GM > 0
% Calculate required scale to set session mean to GM
scale = GM/(mean(cspm_globaltrend(Pd,0,0,0)));
% Scale each volume by this amount
for i = 1:nscan
V = spm_vol(Pd{i});
V.pinfo(1:2,:) = V.pinfo(1:2,:)*scale;
V = spm_create_vol(V);
if strcmp(spm('ver'),'SPM2')
spm_close_vol(V);
end
end
end
% Show in percent change the pre- and post-detrending global timetrends
if display
% Get trends
t1 = gt'; % Variable gt was calculated earlier.
t2 = cspm_globaltrend(Pd,0,0,0)';
b1 = mean(t1(1:end));
b2 = mean(t2(1:end));
% Percent change
t1pc = 100*(t1 - b1)/b1;
t2pc = 100*(t2 - b2)/b2;
% For x-axis
x = 1:length(gt);
% Figure
if num_sessions > 1
titlestr = ['Effect of adjustment (session ',int2str(sn),')'];
else
titlestr = 'Effect of adjustment';
end
figure('NumberTitle','off','Name',titlestr)
subplot(2,1,1)
plot(x,t1,'b.-',x,t2,'r.-')
title ('Raw values: Original and detrended images')
legend('Raw (blue)','Adjusted (red)')
subplot(2,1,2)
plot(x,t1pc,'b.-',x,t2pc,'r.-')
title ('Percent change: Original and detrended images (%)')
legend('Raw (blue)','Adjusted (red)')
end
% Save output back into 4D file
if is4D
[pth,nm,ext] = fileparts(P(1,:));
I = find(ext==',',1,'first');
if ~isempty(I)
ext = ext(1:I-1);
end
cspm_im_3Dto4D( char(Pd), [pth,filesep,'d',nm,ext] )
end
end
% =========================================================================
function gt = cspm_globaltrend( P, pc, usespm, display )
% CSPM_GLOBALTREND - Calculate and display global time trend of images.
% T = CSPM_GLOBALTREND( P, PC, SPM, DISPLAY)
% P - cell array of files, e.g.,
% P = spm_get(Inf, '.img',{'Please select images for detrending'});
% PC - flag 1 = percent change relative to mean (default),
% 0 = absolute value
% SPM - flag 1 = use spm_global (all voxels above 1/8 of maximum
% intensity; not very accurate)
% 0 = avearge of all voxels in volume (default)
% DISPLAY - flag 1 = make figure (default)
% 0 = no figure
% Output: T - global time trend
% @(#)cspm_globaltrend.m 1.0 Paul Macey 2005-08-01
% Calculate global trend of series of images
if nargin < 1
if strcmp(spm('ver'),'SPM99') || strcmp(spm('ver'),'SPM2')
P = spm_get(Inf, '.img','Select images for global trend calculation');
else
P = spm_select(Inf,'image','Select images for global trend calculation');
end
if isempty(P), return, end
end
if iscell(P)
P = char(P);
end
if nargin < 2
pc = 1;
end
if nargin < 3
usespm = 0;
end
if nargin < 4
display = 1;
end
V = spm_vol(P);
nscan = length(V);
gt = zeros(1,nscan); % preallocate
for i = 1:nscan
if usespm
% Note: spm_global estimates the mean after discounting voxels outside
% the object using a criteria of greater than > (global mean)/8.
% However, for large global signal changes, this does not accurately
% estimate the global signal and LMGS detrending based on spm_global
% does not remove all gobal components.
gt(i) = spm_global(V(i));
else
Y = spm_read_vols(V(i));
Y = Y(~isnan(Y));
Y = Y(Y ~= 0);
gt(i) = mean(mean(mean(Y)));
end
end
if strcmp(spm('ver'),'SPM2')
spm_close_vol(V);
end
if pc
bl = mean(gt);
gt = 100*(gt-bl)/bl;
pstr = ' (% change)';
else
pstr = ' (raw)';
end
if display
figure('Name',['Global timetrend for ',int2str(length(V)),' files',pstr])
plot(gt)
ylabel(['Signal Intensity',pstr])
xlabel('Scan Number')
end
if nargout == 0
clear gt
end
end
% =========================================================================
function b = regression(y,X)
% The following checks are omitted within LMGS (since we know what is being
% passed to this function).
%
% Check that matrix (X) and left hand side (y) have compatible dimensions
% [n,p] = size(X);
% [n1,collhs] = size(y);
% if n ~= n1,
% error('The number of rows in Y must equal the number of rows in X.');
% end
%
% if collhs ~= 1,
% error('Y must be a vector, not a matrix');
% end
% Remove missing values, if any
wasnan = (isnan(y) | any(isnan(X),2));
if (any(wasnan))
y(wasnan) = [];
X(wasnan,:) = [];
end
% Find the least squares solution.
[Q, R]=qr(X,0);
b = R\(Q'*y);
end
% =========================================================================
function cspm_im_3Dto4D(P, outfile)
% Convert series of 3D images to single 4D image volume (SPM5 only)
% based on spm_config_3Dto4D, with some lint-informed changes.
if nargin == 0
P = spm_select(Inf,'image','Select images to group into 4D file');
if isempty(P), return, end
nfiles = size(P,1);
Pnew = cell(1,nfiles); % preallocate
for i = 1:nfiles
[pth,nm,ext] = fileparts(P(i,:));
I = find(ext==',');
if ~isempty(I)
ext = ext(1:I-1);
end
Pnew{i} = [pth,filesep,nm,ext];
end
P = char(Pnew);
elseif iscell(P)
P = char(P);
end
if size(P,1) == 1
msgbox('Only one image - selected multiple images for 4D file',...
upper(mfilename),'warn')
return
end
if nargin < 2
[pth,nm,ext] = fileparts(P(1,:));
[f,p] = uiputfile([pth,filesep,nm,'4D',ext],'Save as 4D file');
if f == 0, return, end
outfile = [p,f];
end
V = spm_vol(P);
ind = cat(1,V.n);
N = cat(1,V.private);
mx = -Inf;
mn = Inf;
for i=1:numel(V)
dat = V(i).private.dat(:,:,:,ind(i,1),ind(i,2));
dat = dat(isfinite(dat));
mx = max(mx,max(dat(:)));
mn = min(mn,min(dat(:)));
end
data_type = V(1).dt(1);
r = spm_type(data_type,'maxval') - spm_type(data_type,'minval');
if isfinite(r)
sf = max(mx,-mn)/ r;
else
sf = 1;
end
ni = nifti;
ni.dat = file_array(outfile,[V(1).dim numel(V)],data_type,0,sf,0);
ni.mat = N(1).mat;
ni.mat0 = N(1).mat;
ni.descrip = '4D image';
create(ni);
for i=1:size(ni.dat,4)
ni.dat(:,:,:,i) = N(i).dat(:,:,:,ind(i,1),ind(i,2));
spm_get_space([ni.dat.fname ',' num2str(i)], V(i).mat);
end
% Tidy up - delete 3D files
for i=1:numel(V)
delete(V(i).fname)
end
end
|
github
|
lanl-ansi/OPFRecourse.jl-master
|
nesta_case30_ieee.m
|
.m
|
OPFRecourse.jl-master/test/data/nesta_case30_ieee.m
| 17,949 |
utf_8
|
a80e55940e636ed49d716d79ca744eb9
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% %%%%%
%%%% NICTA Energy System Test Case Archive (NESTA) - v0.5.0 %%%%%
%%%% Optimal Power Flow - Typical Operation %%%%%
%%%% 01 - August - 2015 %%%%%
%%%% %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Power flow data for IEEE 30 bus test case.
% This data was converted from IEEE Common Data Format
% (ieee30cdf.txt) on 20-Sep-2004 by cdf2matp, rev. 1.11
%
% Converted from IEEE CDF file from:
% http://www.ee.washington.edu/research/pstca/
%
% CDF Header:
% 08/20/93 UW ARCHIVE 100.0 1961 W IEEE 30 Bus Test Case
%
function mpc = nesta_case30_ieee
mpc.version = '2';
mpc.baseMVA = 100.0;
%% bus data
% bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin
mpc.bus = [
1 3 0.0 0.0 0.0 0.0 1 1.06000 -0.00000 132.0 1 1.06000 0.94000;
2 2 21.7 12.7 0.0 0.0 1 1.03591 -4.11149 132.0 1 1.06000 0.94000;
3 1 2.4 1.2 0.0 0.0 1 1.01502 -6.85372 132.0 1 1.06000 0.94000;
4 1 7.6 1.6 0.0 0.0 1 1.00446 -8.44574 132.0 1 1.06000 0.94000;
5 2 94.2 19.0 0.0 0.0 1 0.99748 -13.13219 132.0 1 1.06000 0.94000;
6 1 0.0 0.0 0.0 0.0 1 1.00170 -10.15671 132.0 1 1.06000 0.94000;
7 1 22.8 10.9 0.0 0.0 1 0.99208 -11.91706 132.0 1 1.06000 0.94000;
8 2 30.0 30.0 0.0 0.0 1 1.00241 -10.93461 132.0 1 1.06000 0.94000;
9 1 0.0 0.0 0.0 0.0 1 1.03671 -13.26615 1.0 1 1.06000 0.94000;
10 1 5.8 2.0 0.0 19.0 1 1.03220 -14.89730 33.0 1 1.06000 0.94000;
11 2 0.0 0.0 0.0 0.0 1 1.06000 -13.26615 11.0 1 1.06000 0.94000;
12 1 11.2 7.5 0.0 0.0 1 1.04625 -14.18878 33.0 1 1.06000 0.94000;
13 2 0.0 0.0 0.0 0.0 1 1.06000 -14.18878 11.0 1 1.06000 0.94000;
14 1 6.2 1.6 0.0 0.0 1 1.03103 -15.09457 33.0 1 1.06000 0.94000;
15 1 8.2 2.5 0.0 0.0 1 1.02621 -15.17834 33.0 1 1.06000 0.94000;
16 1 3.5 1.8 0.0 0.0 1 1.03259 -14.75320 33.0 1 1.06000 0.94000;
17 1 9.0 5.8 0.0 0.0 1 1.02726 -15.07475 33.0 1 1.06000 0.94000;
18 1 3.2 0.9 0.0 0.0 1 1.01602 -15.79032 33.0 1 1.06000 0.94000;
19 1 9.5 3.4 0.0 0.0 1 1.01317 -15.95831 33.0 1 1.06000 0.94000;
20 1 2.2 0.7 0.0 0.0 1 1.01714 -15.75153 33.0 1 1.06000 0.94000;
21 1 17.5 11.2 0.0 0.0 1 1.01982 -15.35269 33.0 1 1.06000 0.94000;
22 1 0.0 0.0 0.0 0.0 1 1.02041 -15.33860 33.0 1 1.06000 0.94000;
23 1 3.2 1.6 0.0 0.0 1 1.01532 -15.56400 33.0 1 1.06000 0.94000;
24 1 8.7 6.7 0.0 4.3 1 1.00930 -15.72597 33.0 1 1.06000 0.94000;
25 1 0.0 0.0 0.0 0.0 1 1.00621 -15.29138 33.0 1 1.06000 0.94000;
26 1 3.5 2.3 0.0 0.0 1 0.98833 -15.72053 33.0 1 1.06000 0.94000;
27 1 0.0 0.0 0.0 0.0 1 1.01294 -14.75624 33.0 1 1.06000 0.94000;
28 1 0.0 0.0 0.0 0.0 1 0.99824 -10.79567 132.0 1 1.06000 0.94000;
29 1 2.4 0.9 0.0 0.0 1 0.99288 -16.01182 33.0 1 1.06000 0.94000;
30 1 10.6 1.9 0.0 0.0 1 0.98128 -16.91371 33.0 1 1.06000 0.94000;
];
%% generator data
% bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf
mpc.gen = [
1 218.839 9.372 10.0 0.0 1.06 100.0 1 784 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; % COW
2 80.05 24.589 50.0 -40.0 1.03591 100.0 1 100 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; % NG
5 0.0 32.487 40.0 -40.0 0.99748 100.0 1 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; % SYNC
8 0.0 40.0 40.0 -10.0 1.00241 100.0 1 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; % SYNC
11 0.0 11.87 24.0 -6.0 1.06 100.0 1 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; % SYNC
13 0.0 10.414 24.0 -6.0 1.06 100.0 1 0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; % SYNC
];
%% generator cost data
% 2 startup shutdown n c(n-1) ... c0
mpc.gencost = [
2 0.0 0.0 3 0.000000 0.521378 0.000000; % COW
2 0.0 0.0 3 0.000000 1.135166 0.000000; % NG
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC
];
%% branch data
% fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax
mpc.branch = [
1 2 0.0192 0.0575 0.0528 138 138 138 0.0 0.0 1 -30.0 30.0;
1 3 0.0452 0.1652 0.0408 152 152 152 0.0 0.0 1 -30.0 30.0;
2 4 0.057 0.1737 0.0368 139 139 139 0.0 0.0 1 -30.0 30.0;
3 4 0.0132 0.0379 0.0084 135 135 135 0.0 0.0 1 -30.0 30.0;
2 5 0.0472 0.1983 0.0418 144 144 144 0.0 0.0 1 -30.0 30.0;
2 6 0.0581 0.1763 0.0374 139 139 139 0.0 0.0 1 -30.0 30.0;
4 6 0.0119 0.0414 0.009 148 148 148 0.0 0.0 1 -30.0 30.0;
5 7 0.046 0.116 0.0204 127 127 127 0.0 0.0 1 -30.0 30.0;
6 7 0.0267 0.082 0.017 140 140 140 0.0 0.0 1 -30.0 30.0;
6 8 0.012 0.042 0.009 148 148 148 0.0 0.0 1 -30.0 30.0;
6 9 0.0 0.208 0.0 142 142 142 0.978 0.0 1 -30.0 30.0;
6 10 0.0 0.556 0.0 53 53 53 0.969 0.0 1 -30.0 30.0;
9 11 0.0 0.208 0.0 142 142 142 0.0 0.0 1 -30.0 30.0;
9 10 0.0 0.11 0.0 267 267 267 0.0 0.0 1 -30.0 30.0;
4 12 0.0 0.256 0.0 115 115 115 0.932 0.0 1 -30.0 30.0;
12 13 0.0 0.14 0.0 210 210 210 0.0 0.0 1 -30.0 30.0;
12 14 0.1231 0.2559 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
12 15 0.0662 0.1304 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
12 16 0.0945 0.1987 0.0 30 30 30 0.0 0.0 1 -30.0 30.0;
14 15 0.221 0.1997 0.0 20 20 20 0.0 0.0 1 -30.0 30.0;
16 17 0.0524 0.1923 0.0 38 38 38 0.0 0.0 1 -30.0 30.0;
15 18 0.1073 0.2185 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
18 19 0.0639 0.1292 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
19 20 0.034 0.068 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
10 20 0.0936 0.209 0.0 30 30 30 0.0 0.0 1 -30.0 30.0;
10 17 0.0324 0.0845 0.0 33 33 33 0.0 0.0 1 -30.0 30.0;
10 21 0.0348 0.0749 0.0 30 30 30 0.0 0.0 1 -30.0 30.0;
10 22 0.0727 0.1499 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
21 22 0.0116 0.0236 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
15 23 0.1 0.202 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
22 24 0.115 0.179 0.0 26 26 26 0.0 0.0 1 -30.0 30.0;
23 24 0.132 0.27 0.0 29 29 29 0.0 0.0 1 -30.0 30.0;
24 25 0.1885 0.3292 0.0 27 27 27 0.0 0.0 1 -30.0 30.0;
25 26 0.2544 0.38 0.0 25 25 25 0.0 0.0 1 -30.0 30.0;
25 27 0.1093 0.2087 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
28 27 0.0 0.396 0.0 75 75 75 0.968 0.0 1 -30.0 30.0;
27 29 0.2198 0.4153 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
27 30 0.3202 0.6027 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
29 30 0.2399 0.4533 0.0 28 28 28 0.0 0.0 1 -30.0 30.0;
8 28 0.0636 0.2 0.0428 140 140 140 0.0 0.0 1 -30.0 30.0;
6 28 0.0169 0.0599 0.013 149 149 149 0.0 0.0 1 -30.0 30.0;
];
% INFO : === Translation Options ===
% INFO : Phase Angle Bound: 30.0 (deg.)
% INFO : Line Capacity Model: stat
% INFO : Gen Active Capacity Model: stat
% INFO : Gen Reactive Capacity Model: am50ag
% INFO : Gen Active Cost Model: stat
% INFO : AC OPF Solution File: nesta_case30_ieee.dat.opf.sol
% INFO : Line Capacity PAB: 15.0 (deg.)
% INFO :
% INFO : === Generator Classification Notes ===
% INFO : SYNC 4 - 0.00
% INFO : COW 1 - 86.68
% INFO : NG 1 - 13.32
% INFO :
% INFO : === Generator Active Capacity Stat Model Notes ===
% INFO : Gen at bus 1 - COW : Pg=260.2, Pmax=360.2 -> Pmax=784 samples: 13
% INFO : Gen at bus 2 - NG : Pg=40.0, Pmax=140.0 -> Pmax=100 samples: 1
% INFO : Gen at bus 5 - SYNC : Pg=0.0, Pmax=100.0 -> Pmax=0 samples: 0
% INFO : Gen at bus 8 - SYNC : Pg=0.0, Pmax=100.0 -> Pmax=0 samples: 0
% INFO : Gen at bus 11 - SYNC : Pg=0.0, Pmax=100.0 -> Pmax=0 samples: 0
% INFO : Gen at bus 13 - SYNC : Pg=0.0, Pmax=100.0 -> Pmax=0 samples: 0
% INFO :
% INFO : === Generator Reactive Capacity Atmost Max 50 Percent Active Model Notes ===
% INFO :
% INFO : === Generator Active Cost Stat Model Notes ===
% INFO : Updated Generator Cost: COW - 0.0 20.0 0.038432 -> 0 0.521377501002 0
% INFO : Updated Generator Cost: NG - 0.0 20.0 0.25 -> 0 1.13516647936 0
% INFO : Updated Generator Cost: SYNC - 0.0 40.0 0.01 -> 0 0.0 0
% INFO : Updated Generator Cost: SYNC - 0.0 40.0 0.01 -> 0 0.0 0
% INFO : Updated Generator Cost: SYNC - 0.0 40.0 0.01 -> 0 0.0 0
% INFO : Updated Generator Cost: SYNC - 0.0 40.0 0.01 -> 0 0.0 0
% INFO :
% INFO : === Line Capacity Stat Model Notes ===
% INFO : Updated Thermal Rating: on line 1-2 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 138
% INFO : Updated Thermal Rating: on line 1-3 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 152
% INFO : Updated Thermal Rating: on line 2-4 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 139
% INFO : Updated Thermal Rating: on line 3-4 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 135
% WARNING : Updated Thermal Rating Stat Model was larger than UB Model: on 2-5 : 161 , 143
% INFO : Updated Thermal Rating: on line 2-5 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 144
% INFO : Updated Thermal Rating: on line 2-6 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 139
% INFO : Updated Thermal Rating: on line 4-6 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 148
% INFO : Updated Thermal Rating: on line 5-7 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 127
% INFO : Updated Thermal Rating: on line 6-7 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 140
% INFO : Updated Thermal Rating: on line 6-8 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 148
% WARNING : Missing data for branch flow stat model on line 6-9 using max current model : from_basekv=132.0 to_basekv=1.0 r=0.0 x=0.208
% INFO : Updated Thermal Rating: on transformer 6-9 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 142
% WARNING : Missing data for branch flow stat model on line 6-10 using max current model : from_basekv=132.0 to_basekv=33.0 r=0.0 x=0.556
% INFO : Updated Thermal Rating: on transformer 6-10 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 53
% WARNING : Missing data for branch flow stat model on line 9-11 using max current model : from_basekv=1.0 to_basekv=11.0 r=0.0 x=0.208
% INFO : Updated Thermal Rating: on line 9-11 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 142
% WARNING : Missing data for branch flow stat model on line 9-10 using max current model : from_basekv=1.0 to_basekv=33.0 r=0.0 x=0.11
% INFO : Updated Thermal Rating: on line 9-10 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 267
% WARNING : Missing data for branch flow stat model on line 4-12 using max current model : from_basekv=132.0 to_basekv=33.0 r=0.0 x=0.256
% INFO : Updated Thermal Rating: on transformer 4-12 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 115
% WARNING : Missing data for branch flow stat model on line 12-13 using max current model : from_basekv=33.0 to_basekv=11.0 r=0.0 x=0.14
% INFO : Updated Thermal Rating: on line 12-13 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 210
% INFO : Updated Thermal Rating: on line 12-14 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 12-15 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 12-16 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 30
% INFO : Updated Thermal Rating: on line 14-15 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 20
% INFO : Updated Thermal Rating: on line 16-17 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 38
% INFO : Updated Thermal Rating: on line 15-18 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 18-19 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 19-20 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 10-20 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 30
% INFO : Updated Thermal Rating: on line 10-17 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 33
% INFO : Updated Thermal Rating: on line 10-21 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 30
% INFO : Updated Thermal Rating: on line 10-22 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 21-22 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 15-23 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 22-24 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 26
% INFO : Updated Thermal Rating: on line 23-24 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 29
% INFO : Updated Thermal Rating: on line 24-25 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 27
% INFO : Updated Thermal Rating: on line 25-26 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 25
% INFO : Updated Thermal Rating: on line 25-27 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 28
% WARNING : Missing data for branch flow stat model on line 28-27 using max current model : from_basekv=132.0 to_basekv=33.0 r=0.0 x=0.396
% INFO : Updated Thermal Rating: on transformer 28-27 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 75
% INFO : Updated Thermal Rating: on line 27-29 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 28
% INFO : Updated Thermal Rating: on line 27-30 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 28
% INFO : Updated Thermal Rating: on line 29-30 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 28
% WARNING : Updated Thermal Rating Stat Model was larger than UB Model: on 8-28 : 140 , 139
% INFO : Updated Thermal Rating: on line 8-28 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 140
% INFO : Updated Thermal Rating: on line 6-28 : Rate A, Rate B, Rate C , 9900.0, 0.0, 0.0 -> 149
% INFO :
% INFO : === Voltage Setpoint Replacement Notes ===
% INFO : Bus 1 : V=1.06, theta=0.0 -> V=1.06, theta=-0.0
% INFO : Bus 2 : V=1.043, theta=-5.48 -> V=1.03591, theta=-4.11149
% INFO : Bus 3 : V=1.021, theta=-7.96 -> V=1.01502, theta=-6.85372
% INFO : Bus 4 : V=1.012, theta=-9.62 -> V=1.00446, theta=-8.44574
% INFO : Bus 5 : V=1.01, theta=-14.37 -> V=0.99748, theta=-13.13219
% INFO : Bus 6 : V=1.01, theta=-11.34 -> V=1.0017, theta=-10.15671
% INFO : Bus 7 : V=1.002, theta=-13.12 -> V=0.99208, theta=-11.91706
% INFO : Bus 8 : V=1.01, theta=-12.1 -> V=1.00241, theta=-10.93461
% INFO : Bus 9 : V=1.051, theta=-14.38 -> V=1.03671, theta=-13.26615
% INFO : Bus 10 : V=1.045, theta=-15.97 -> V=1.0322, theta=-14.8973
% INFO : Bus 11 : V=1.082, theta=-14.39 -> V=1.06, theta=-13.26615
% INFO : Bus 12 : V=1.057, theta=-15.24 -> V=1.04625, theta=-14.18878
% INFO : Bus 13 : V=1.071, theta=-15.24 -> V=1.06, theta=-14.18878
% INFO : Bus 14 : V=1.042, theta=-16.13 -> V=1.03103, theta=-15.09457
% INFO : Bus 15 : V=1.038, theta=-16.22 -> V=1.02621, theta=-15.17834
% INFO : Bus 16 : V=1.045, theta=-15.83 -> V=1.03259, theta=-14.7532
% INFO : Bus 17 : V=1.04, theta=-16.14 -> V=1.02726, theta=-15.07475
% INFO : Bus 18 : V=1.028, theta=-16.82 -> V=1.01602, theta=-15.79032
% INFO : Bus 19 : V=1.026, theta=-17.0 -> V=1.01317, theta=-15.95831
% INFO : Bus 20 : V=1.03, theta=-16.8 -> V=1.01714, theta=-15.75153
% INFO : Bus 21 : V=1.033, theta=-16.42 -> V=1.01982, theta=-15.35269
% INFO : Bus 22 : V=1.033, theta=-16.41 -> V=1.02041, theta=-15.3386
% INFO : Bus 23 : V=1.027, theta=-16.61 -> V=1.01532, theta=-15.564
% INFO : Bus 24 : V=1.021, theta=-16.78 -> V=1.0093, theta=-15.72597
% INFO : Bus 25 : V=1.017, theta=-16.35 -> V=1.00621, theta=-15.29138
% INFO : Bus 26 : V=1.0, theta=-16.77 -> V=0.98833, theta=-15.72053
% INFO : Bus 27 : V=1.023, theta=-15.82 -> V=1.01294, theta=-14.75624
% INFO : Bus 28 : V=1.007, theta=-11.97 -> V=0.99824, theta=-10.79567
% INFO : Bus 29 : V=1.003, theta=-17.06 -> V=0.99288, theta=-16.01182
% INFO : Bus 30 : V=0.992, theta=-17.94 -> V=0.98128, theta=-16.91371
% INFO :
% INFO : === Generator Setpoint Replacement Notes ===
% INFO : Gen at bus 1 : Pg=260.2, Qg=-16.1 -> Pg=218.839, Qg=9.372
% INFO : Gen at bus 1 : Vg=1.06 -> Vg=1.06
% INFO : Gen at bus 2 : Pg=40.0, Qg=50.0 -> Pg=80.05, Qg=24.589
% INFO : Gen at bus 2 : Vg=1.045 -> Vg=1.03591
% INFO : Gen at bus 5 : Pg=0.0, Qg=37.0 -> Pg=0.0, Qg=32.487
% INFO : Gen at bus 5 : Vg=1.01 -> Vg=0.99748
% INFO : Gen at bus 8 : Pg=0.0, Qg=37.3 -> Pg=0.0, Qg=40.0
% INFO : Gen at bus 8 : Vg=1.01 -> Vg=1.00241
% INFO : Gen at bus 11 : Pg=0.0, Qg=16.2 -> Pg=0.0, Qg=11.87
% INFO : Gen at bus 11 : Vg=1.082 -> Vg=1.06
% INFO : Gen at bus 13 : Pg=0.0, Qg=10.6 -> Pg=0.0, Qg=10.414
% INFO : Gen at bus 13 : Vg=1.071 -> Vg=1.06
% INFO :
% INFO : === Writing Matpower Case File Notes ===
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JLd.m
|
.m
|
IEforAR-master/extract_feature_JLd.m
| 4,296 |
utf_8
|
1b604e72cee456b300ee63e67b4c3df3
|
function [features] = extract_feature_JLd(skeleton_input)
index = get_JLd_index01;
% index = get_JLd_index02;
% index = get_JLd_index03;
pts1 = skeleton_input(index(:,1),:,:,:);
pts2 = skeleton_input(index(:,2),:,:,:);
pts3 = skeleton_input(index(:,3),:,:,:);
features = squeeze((sum(cross(pts2-pts1,pts3-pts1,2).^2,2).^(1/2))./(sum((pts3-pts2).^2,2).^(1/2)));
end
function index = get_JLd_index01
line_index = get_line_index01;
len_line = length(line_index);
index = zeros(897,3); %[J, (J1,J2)]
cnt = 0;
for i = 1:25
for j = 1:len_line
if i ~= line_index(j,1) && i ~= line_index(j,2)
cnt = cnt + 1;
index(cnt,:) = [i line_index(j,:)];
end
end
end
end
function index = get_JLd_index02
line_index = get_line_index01;
neib_index = get_neighbour_index;
len_line = length(line_index);
index = [];
cnt = 0;
for i = 1:len_line
neib_joints = [neib_index(line_index(i,1)).neib neib_index(line_index(i,2)).neib];
neib_joints = unique(neib_joints);
neib_joints(neib_joints== line_index(i,1) | neib_joints== line_index(i,2)) = [];
for j = neib_joints
cnt = cnt + 1;
index(cnt,:) = [j line_index(i,:)];
end
end
end
function index = get_JLd_index03
joints = [3 4 5 6 7 8 9 10 11 12 13 14 15 17 18 19];
nb_index = get_neighbour_index;
line_index_temp = [];
for j = joints
nb_joints = [nb_index(j).neib]';
line_temp = [repmat(j,length(nb_joints),1) nb_joints];
line_index_temp = [line_index_temp;line_temp];
end
line_index(:,1) = min(line_index_temp,[],2);
line_index(:,2) = max(line_index_temp,[],2);
[~,I] = sort(line_index(:,1));
line_index = line_index(I,:);
line_index = unique(line_index,'rows');
len_line = length(line_index);
index=[];
cnt = 1;
for i = 1:len_line
nb_joints = [nb_index(line_index(i,1)).neib nb_index(line_index(i,2)).neib]';
nb_joints = unique(nb_joints);
nb_joints(nb_joints== line_index(i,1) | nb_joints== line_index(i,2)) = [];
len = length(nb_joints);
index(cnt:cnt+len-1,:) = [nb_joints repmat(line_index(i,:),len,1)];
cnt = cnt+len;
end
end
function index = get_line_index01
%case 1: directly adjacent (calculated from 1 to 25, deep first)
index = [1 2;
1 13;
1 17;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
8 22;
8 23;
9 10;
9 21;
10 11;
11 12;
12 24;
12 25;
13 14;
14 15;
15 16;
17 18;
18 19;
19 20;
%case 2: J1 at end, J2 two steps away (End:4,8,12,15,19)
4 21;
8 5;
12 9;
15 13;
19 17;
%case 3: J1 and J2 are at end (End:4,8,12,15,19)
4 8;
4 12;
4 15;
4 19;
8 12;
8 15;
8 19;
12 15;
12 19;
15 19];
end
function index = get_line_index02
%case 1: directly adjacent (calculated from 1 to 25, deep first)
index = [1 2;
1 13;
1 17;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
8 22;
8 23;
9 10;
9 21;
10 11;
11 12;
12 24;
12 25;
13 14;
14 15;
15 16;
17 18;
18 19;
19 20;
%case 2: J1 at end, J2 two steps away (End:4,8,12,15,19)
4 21;
8 5;
12 9;
15 13;
19 17;
%case 3: J1 and J2 are at end (End:4,8,12,15,19)
4 8;
4 12;
4 15;
4 19;
8 12;
8 15;
8 19;
12 15;
12 19;
15 19
%case 4: two steps away at four body ends
5 7;
6 8;
9 11;
10 12;
13 16;
17 20
];
end
function index = get_neighbour_index
index = [];
index(1).neib = [2 13 14 17 18 21];
index(2).neib = [1 3 5 9 13 17 21];
index(3).neib = [2 4 5 9 21];
index(4).neib = [3 21];
index(5).neib = [2 3 6 7 9 21];
index(6).neib = [5 7 8 21];
index(7).neib = [5 6 8 22 23];
index(8).neib = [6 7 22 23];
index(9).neib = [2 3 5 10 11 21];
index(10).neib = [9 11 12 21];
index(11).neib = [9 10 12 24 25];
index(12).neib = [10 11 24 25];
index(13).neib = [1 2 14 15 17];
index(14).neib = [1 13 15 16];
index(15).neib = [13 14 16];
index(16).neib = [14 15];
index(17).neib = [1 2 13 18 19];
index(18).neib = [1 17 19 20];
index(19).neib = [17 18 20];
index(20).neib = [18 19];
index(21).neib = [1 2 3 4 5 6 9 10];
index(22).neib = [7 8 23];
index(23).neib = [7 8 22];
index(24).neib = [11 12 25];
index(25).neib = [11 12 24];
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_LLa.m
|
.m
|
IEforAR-master/extract_feature_LLa.m
| 1,282 |
utf_8
|
93762664bd183badcd6223f6f25ef4ff
|
function [features] = extract_feature_LLa(skeleton_input)
index = get_LLa_index01;
lines1 = skeleton_input(index(:,2),:,:,:) - skeleton_input(index(:,1),:,:,:);
lines2 = skeleton_input(index(:,4),:,:,:) - skeleton_input(index(:,3),:,:,:);
features = squeeze(acos(dot(lines1,lines2,2) ...\
./(sum(lines1.^2,2).^(1/2)) ...\
./(sum(lines2.^2,2).^(1/2))));%use matrix calculation for efficiency
end
function index_out = get_LLa_index01
index = get_line_index01;
index_out = zeros(741,4);
n = 0;
for i = 1:38
for j = i+1:39
n = n + 1;
index_out(n,:) = [index(i,1) index(i,2) index(j,1) index(j,2)];
end
end
end
function index = get_line_index01
%case 1: directly adjacent (calculated from 1 to 25, deep first)
index = [1 2;
1 17;
1 13;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
8 22;
8 23;
9 10;
9 21;
10 11;
11 12;
12 24;
12 25;
13 14;
14 15;
15 16;
17 18;
18 19;
19 20;
%case 2: J1 at end, J2 two steps away (End:4,7,11,15,19)
4 21;
7 5;
11 9;
15 13;
19 17;
%case 3: J1 and J2 are at end (End:4,7,11,15,19)
4 7;
4 11;
4 15;
4 19;
7 11;
7 15;
7 19;
11 15;
11 19;
15 19];
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method9.m
|
.m
|
IEforAR-master/transform_method9.m
| 609 |
utf_8
|
3eb5f96647c624ee797e178a73b86bed
|
function image_output = transform_method9(features,img_size)
global cb;%claimed in main file
features = imresize(features,img_size,'bilinear');
[dim,frame,~] = size(features);
color_index = ones(dim,frame);
for f = 1:frame
min_value = min(features(:,1:f,1),[],2);
range = max(features(:,1:f,1)-min_value,[],2);
color_index(:,f) = ceil(256*(features(:,f,1)-min_value)./range);
end
color_index(color_index < 1 ) = 1;
color_index(color_index > 256) = 256;
color_index(isnan(color_index) ) = 1;
temp = cb(color_index,:);
image = reshape(temp,dim,frame,3);
image_output = image;
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJd.m
|
.m
|
IEforAR-master/extract_feature_JJd.m
| 2,236 |
utf_8
|
7b73db695bde272f8e98750651ab2b7f
|
function features = extract_feature_JJd(skeleton_input)
% index = get_JJd_index01;
% index = get_JJd_index02;
% index = get_JJd_index03;
index = get_JJd_index04;
joints = skeleton_input;
vec = joints(index(:,2),:,:,:) - joints(index(:,1),:,:,:);
features = squeeze(sum(vec.^2,2).^(1/2));
end
function index = get_JJd_index01
%
index = zeros(300,2);
n = 0;
for i = 1:24
for j = i+1:25
n = n + 1;
index(n,:) = [i j];
end
end
end
function index = get_JJd_index02
%
index = zeros(300,2);
n = 0;
for i = 1:24
for j = i+1:25
n = n + 1;
index(n,:) = [i j];
end
end
connected = [
%remove directly connected
1 2;
1 13;
1 17;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
8 22;
8 23;
9 10;
9 21;
10 11;
11 12;
12 24;
12 25;
13 14;
14 15;
15 16;
17 18;
18 19;
19 20
];
con_index = zeros(length(connected),1);
for i = 1:length(connected)
idx = index == connected(i,:);
con_index(i) = find(idx(:,1) ==1 &idx(:,2)==1);
end
index(con_index,:) = [];
end
%16 joints
function index = get_JJd_index03
joint_num = [1 4 6 7 8 10 11 12 14 15 18 19 22 23 24 25];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%16 joints
function index = get_JJd_index04
joint_num = [1 4 5 7 8 9 11 12 14 15 16 18 19 20 24 25];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%12 joints
function index = get_JJd_index05
joint_num = [2 4 5 7 9 11 13 15 17 19 22 24];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%11 joints
function index = get_JJd_index06
joint_num = [1 4 6 8 10 12 14 16 18 20 21];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method1.m
|
.m
|
IEforAR-master/transform_method1.m
| 310 |
utf_8
|
28e6ffff361be7a8228a8859d45731b1
|
%linear transform
%specifically for JJo which has 3 dimensional features
function image_output = transform_method1(features,img_size)
features = imresize(features,img_size,'bilinear');
min_value = min(features,[],2);
range = max(features,[],2) - min_value;
image_output = (features- min_value)./range;
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJd01.m
|
.m
|
IEforAR-master/extract_feature_JJd01.m
| 1,170 |
utf_8
|
74b608dd2b792e512c333299c397f1d6
|
function features = extract_feature_JJd01(skeleton_input)
[joint_num,cor_dim,frame,body_num] = size(skeleton_input);
index = get_JJd_index01;
% index = get_JJd_index02;
joints = zeros(2*joint_num,cor_dim,frame);
joints(1:joint_num,:,:) = skeleton_input(:,:,:,1);
if body_num == 1
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,1);
else
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,2);
end
vec = joints(index(:,2),:,:) - joints(index(:,1),:,:);
features = squeeze(sum(vec.^2,2).^(1/2));
end
%12 joints, two bodies
function index = get_JJd_index01
joint_num = [2 4 5 7 9 11 13 15 17 19 22 24];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%11 joints, two bodies
function index = get_JJd_index02
joint_num = [1 4 6 8 10 12 14 16 18 20 21];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
create_list.m
|
.m
|
IEforAR-master/create_list.m
| 2,545 |
utf_8
|
720b47076443cfef8e3e82163b3d8c6e
|
% train and test list for two evaluations
% cross subject and cross view
function [cross_sub_V2Tr1Te0_index, cross_view_V2Tr1Te0_index] = create_list(skeleton_file_list, target_folder)
mkdir(target_folder);
labels = str2num(skeleton_file_list(:,18:20));
%% cross subject training and test list
performer_list = str2num(skeleton_file_list(:,10:12));
training_subjects = [1 2 4 5 8 9 13 14 15 16 17 18 19 25 27 28 31 34 35 38]';
train_index = zeros(length(performer_list),1);
for i = 1:length(training_subjects)
train_index = train_index | (performer_list == training_subjects(i));
end
val_subjects = [2 4 9 14 17 19 25 28 34 38]';
val_index = zeros(length(performer_list),1);
for i = 1:length(val_subjects)
val_index = val_index | (performer_list == val_subjects(i));
end
index = train_index + val_index; % 2 for val, 1 for train, 0 for test
print_list(skeleton_file_list, labels, index, [target_folder 'cross_subject/']);
cross_sub_V2Tr1Te0_index = index;
%% cross view training and test list
camera_list = str2num(skeleton_file_list(:,6:8));
training_cameras = [2 3]';
train_index = zeros(length(camera_list),1);
for i = 1:length(training_cameras)
train_index = train_index | (camera_list == training_cameras(i));
end
train_index_list = find(train_index == 1);
val_index = zeros(length(train_index),1);
temp = randperm(length(train_index_list));
val_index(train_index_list(temp(1:length(train_index_list)/2))) = 1;
index = train_index + val_index;
print_list(skeleton_file_list,labels, index, [target_folder 'cross_view/']);
cross_view_V2Tr1Te0_index = index;
%%
disp('Cross_subject & Cross_view lists created.')
end
function print_list(skeleton_file_list, labels, index, target_folder)
mkdir(target_folder);
train_fid = fopen([target_folder 'train.txt'],'w');
val_fid = fopen([target_folder 'val.txt'],'w');
test_fid = fopen([target_folder 'test.txt'],'w');
for i = 1:length(skeleton_file_list)
if index(i) ~= 0
%train 1
fprintf(train_fid, [skeleton_file_list(i,17:20) '/' skeleton_file_list(i,1:20) '.jpg']);
fprintf(train_fid, ' %d\n', labels(i)-1);
if index(i) == 2% val 2
fprintf(val_fid, [skeleton_file_list(i,17:20) '/' skeleton_file_list(i,1:20) '.jpg']);
fprintf(val_fid, ' %d\n', labels(i)-1);
end
else %test 0
fprintf(test_fid, [skeleton_file_list(i,17:20) '/' skeleton_file_list(i,1:20) '.jpg']);
fprintf(test_fid, ' %d\n', labels(i)-1);
end
end
fclose(train_fid);
fclose(val_fid);
fclose(test_fid);
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method8.m
|
.m
|
IEforAR-master/transform_method8.m
| 601 |
utf_8
|
2685988e6ba5c23acfff76e96361e8fd
|
%temporal information included
%active function
function image_output = transform_method8(features)
global cb;%claimed in main file
[dim,frame,~] = size(features);
main_feature = features(:,:,1);
min_value = min(main_feature(:));
range = max(main_feature(:)) - min_value;
% f = (main_feature - min_value)./range;
alpha = 50;
f = atan(alpha*(main_feature - min_value)./range - alpha/2)/2/atan(alpha/2) + 1/2;
color_index = ceil(256*f);
color_index(color_index == 0 ) = 1;
color_index(isnan(color_index) ) = 1;
temp = cb(color_index,:);
image = reshape(temp,dim,frame,3);
image_output = image;
end
|
github
|
dzwallkilled/IEforAR-master
|
preprocess_skeleton_data.m
|
.m
|
IEforAR-master/preprocess_skeleton_data.m
| 4,026 |
utf_8
|
b39d4b54fd0cdca8144d8c56fddd71e5
|
function [skeleton_output, body_num] = preprocess_skeleton_data(skeleton_input)
%align the skeleton data according to body_ID
%meanwhile normalizing the joint xyz corrdinates based on chain distances
[skeleton_output, body_cnt] = enhance_skeleton(skeleton_input);
% visualize_skeleton(skeleton_output);
%translate (actually there is no need for JLd, JJd and LLa, which are relative features)
% skeleton_output = translate_skeleton(skeleton_output);
%select a main body
[skeleton_output,body_num] = select_main_body(skeleton_output,body_cnt);
end
% if spread X /spread Y is larger than 0.8, then dismissed
% method from 'NTU RGB+D: A Large Scale Dataset for 3D Human Activity Analysis'
function [skeleton_output,body_num] = select_main_body(skeleton_input,body_cnt)
body_num = size(skeleton_input,4);
if body_num > 1
skeleton_tran = translate_skeleton(skeleton_input);
spread = max(skeleton_tran,[],1)-min(skeleton_tran,[],1);
ratio = squeeze(spread(1,1,:,:)./spread(1,2,:,:));
ratio(isnan(ratio)) = 0;
avg_ratio1 = sum(ratio)./body_cnt';
spread = max(skeleton_input,[],1)-min(skeleton_input,[],1);
ratio = squeeze(spread(1,1,:,:)./spread(1,2,:,:));
ratio(isnan(ratio)) = 0;
avg_ratio2 = sum(ratio)./body_cnt';
avg_ratio = (avg_ratio1+avg_ratio2)/2;
if min(avg_ratio) < 0.8
skeleton_output = skeleton_input(:,:,:,avg_ratio <= 0.8);
body_cnt(avg_ratio > 0.8) = [];
skeleton_tran(:,:,:,avg_ratio > 0.8) = [];
else
skeleton_output = skeleton_input(:,:,:,avg_ratio == min(avg_ratio));
body_cnt(avg_ratio ~= min(avg_ratio)) = [];
skeleton_tran(:,:,:,avg_ratio ~= min(avg_ratio)) = [];
end
if size(skeleton_output,4) > 1
if max(body_cnt) == min(body_cnt)
variation = squeeze(sum(sum(var(skeleton_tran,0,3),2),1));
[~,I] = sort(variation,'descend');
else
[~,I] = sort(body_cnt,'descend');
end
skeleton_output = skeleton_output(:,:,:,I);
end
else
skeleton_output = skeleton_input;
end
end
function [skeleton_output, body_cnt] = enhance_skeleton(skeleton_input)
frame = length(skeleton_input);
max_body_num = 0;
body_ID = int64(0);
body_index = zeros(7,frame);
for f = 1:frame
body_num = length(skeleton_input(f).bodies);
for b = 1:body_num
body_id = skeleton_input(f).bodies(b).bodyID;
if isempty(find(body_id == body_ID, 1))
max_body_num = max_body_num + 1;
body_ID(max_body_num) = body_id;
end
idx = find(body_id == body_ID, 1);
body_index(idx,f) = 1;
end
end
joints = zeros(25,3,frame,max_body_num);
for f = 1:frame
body_num = length(skeleton_input(f).bodies);
for b = 1:body_num
idx = find(skeleton_input(f).bodies(b).bodyID == body_ID, 1);
for j = 1:25
joints(j,:,f,idx) = [skeleton_input(f).bodies(b).joints(j).x ...\
skeleton_input(f).bodies(b).joints(j).y ...\
skeleton_input(f).bodies(b).joints(j).z];
end
end
end
%normalization
%method from 'On Geometric Features for Skeleton-Based Action Recognition
% using Multilayer LSTM Networks'
index = get_chain_index; %the index that defines chains according to joint numbers
chains = joints(index(:,2),:,:,:) - joints(index(:,1),:,:,:);
skeleton_output = 100 * joints./repmat(sum(sum(chains.^2,2).^(0.5),1),25,3);
% skeleton_output = joints;
body_index(max_body_num+1:end,:) = [];
body_cnt = sum(body_index,2);
body_index(body_cnt < max(body_cnt)/2,:) = 0;
skeleton_output(:,:,sum(body_index,1) == 0,:) = [];
skeleton_output(:,:,:,body_cnt<max(body_cnt)/2) = [];
body_cnt(body_cnt<max(body_cnt)/2) = [];
end
function index = get_chain_index
% % spine based to spine
% index = [1 21];
% all connected chains
index = [1 2;
1 17;
1 13;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
9 10;
9 21;
10 11;
11 12;
13 14;
14 15;
17 18;
18 19];
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JLd01.m
|
.m
|
IEforAR-master/extract_feature_JLd01.m
| 4,847 |
utf_8
|
3601954b68d43129dca09c1e14fa4d45
|
%use this for computation efficiency speed = 0.079215 seconds
function [features] = extract_feature_JLd01(skeleton_input)
[joint_num,cor_dim,frame,body_num] = size(skeleton_input);
% index = get_JLd_index01;
% index = get_JLd_index02;
index = get_JLd_index03;
dim = length(index);
joints = zeros(2*joint_num,cor_dim,frame);
joints(1:joint_num,:,:) = skeleton_input(:,:,:,1);
if body_num == 1
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,1);
else
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,2);
end
pts1 = joints(index(:,1),:,:,:);
pts2 = joints(index(:,2),:,:,:);
pts3 = joints(index(:,3),:,:,:);
features = squeeze((sum(cross(pts2-pts1,pts3-pts1,2).^2,2).^(1/2))./(sum((pts3-pts2).^2,2).^(1/2)));
end
function index = get_JLd_index01
line_index = get_line_index01;
len_line = length(line_index);
index = zeros(897,3); %[J, (J1,J2)]
cnt = 0;
for i = 1:25
for j = 1:len_line
if i ~= line_index(j,1) && i ~= line_index(j,2)
cnt = cnt + 1;
index(cnt,:) = [i line_index(j,:)];
end
end
end
end
function index = get_JLd_index02
line_index = get_line_index01;
neib_index = get_neighbour_index;
len_line = length(line_index);
index_temp = [];
cnt = 0;
for i = 1:len_line
neib_joints = [neib_index(line_index(i,1)).neib neib_index(line_index(i,2)).neib];
neib_joints = unique(neib_joints);
neib_joints(neib_joints== line_index(i,1) | neib_joints== line_index(i,2)) = [];
for j = neib_joints
cnt = cnt + 1;
index_temp(cnt,:) = [j line_index(i,:)];
end
end
index1 = [[3:25]' repmat(26:27,23,1)];
index2 = [[1:4 6:8 10:25]' repmat([30 34],23,1)];
index = [index_temp;index1;index2];
end
function index = get_JLd_index03
joints = [4 6 7 8 10 11 12 14 15 18 19];
% joints = [joints joints+25];
nb_index = get_neighbour_index;
line_index_temp = [];
for j = joints
nb_joints = [nb_index(j).neib nb_index(j).neib + 25]';
line_temp = [repmat(j,length(nb_joints),1) nb_joints];
line_index_temp = [line_index_temp;line_temp];
end
line_index(:,1) = min(line_index_temp,[],2);
line_index(:,2) = max(line_index_temp,[],2);
[~,I] = sort(line_index(:,1));
line_index = line_index(I,:);
line_index = unique(line_index,'rows');
len_line = length(line_index);
index=[];
cnt = 1;
for i = 1:len_line
nb_joints = [nb_index(line_index(i,1)).neib]';
nb_joints = [nb_joints;nb_joints+25];
nb_joints = unique(nb_joints);
nb_joints(nb_joints== line_index(i,1) | nb_joints== line_index(i,2)) = [];
len = length(nb_joints);
index(cnt:cnt+len-1,:) = [nb_joints repmat(line_index(i,:),len,1)];
cnt = cnt+len;
end
end
function index = get_line_index01
%case 1: directly adjacent (calculated from 1 to 25, deep first)
index = [1 2;
1 13;
1 17;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
8 22;
8 23;
9 10;
9 21;
10 11;
11 12;
12 24;
12 25;
13 14;
14 15;
15 16;
17 18;
18 19;
19 20;
%case 2: J1 at end, J2 two steps away (End:4,8,12,15,19)
4 21;
8 5;
12 9;
15 13;
19 17;
%case 3: J1 and J2 are at end (End:4,8,12,15,19)
4 8;
4 12;
4 15;
4 19;
8 12;
8 15;
8 19;
12 15;
12 19;
15 19];
end
function index = get_line_index02
%case 1: directly adjacent (calculated from 1 to 25, deep first)
index = [1 2;
1 13;
1 17;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
8 22;
8 23;
9 10;
9 21;
10 11;
11 12;
12 24;
12 25;
13 14;
14 15;
15 16;
17 18;
18 19;
19 20;
%case 2: J1 at end, J2 two steps away (End:4,8,12,15,19)
4 21;
8 5;
12 9;
15 13;
19 17;
%case 3: J1 and J2 are at end (End:4,8,12,15,19)
4 8;
4 12;
4 15;
4 19;
8 12;
8 15;
8 19;
12 15;
12 19;
15 19
%case 4: two steps away at four body ends
5 7;
6 8;
9 11;
10 12;
13 16;
17 20
];
end
function index = get_neighbour_index
index = [];
index(1).neib = [2 13 14 17 18 21];
index(2).neib = [1 3 5 9 13 17 21];
index(3).neib = [2 4 5 9 21];
index(4).neib = [3 21];
index(5).neib = [2 3 6 7 9 21];
index(6).neib = [5 7 8 21];
index(7).neib = [5 6 8 22 23];
index(8).neib = [6 7 22 23];
index(9).neib = [2 3 5 10 11 21];
index(10).neib = [9 11 12 21];
index(11).neib = [9 10 12 24 25];
index(12).neib = [10 11 24 25];
index(13).neib = [1 2 14 15 17];
index(14).neib = [1 13 15 16];
index(15).neib = [13 14 16];
index(16).neib = [14 15];
index(17).neib = [1 2 13 18 19];
index(18).neib = [1 17 19 20];
index(19).neib = [17 18 20];
index(20).neib = [18 19];
index(21).neib = [1 2 3 4 5 6 9 10];
index(22).neib = [7 8 23];
index(23).neib = [7 8 22];
index(24).neib = [11 12 25];
index(25).neib = [11 12 24];
end
|
github
|
dzwallkilled/IEforAR-master
|
translate_skeleton.m
|
.m
|
IEforAR-master/translate_skeleton.m
| 743 |
utf_8
|
3469b7f8aab3e71f30b0ccffd165df34
|
%method following 'On Geometric Features for Skeleton-Based Action Recognition using Multilayer
%LSTM Networks'
%including traslating and rotation
function skeleton_output = translate_skeleton(skeleton_input)
[~,~,frame,body_num] = size(skeleton_input);
skeleton_output = zeros(25,3,frame,body_num);
for f = 1:frame
for b = 1:body_num
u = skeleton_input(5,:,f,b) - skeleton_input(9,:,f,b);%x
u = u'/norm(u);
v = skeleton_input(21,:,f,b) - skeleton_input(1,:,f,b);%y
v = v'/norm(v);
w = cross(u,v);%z
w = w/norm(w);
u = cross(v,w);%orthogonal for xyz
skeleton_output(:,:,f,b) = (skeleton_input(:,:,f,b) - repmat(skeleton_input(1,:,f,b),25,1)) * [u v w];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method3.m
|
.m
|
IEforAR-master/transform_method3.m
| 571 |
utf_8
|
bbff146b7c9ed4a9bb65f5c9158f7c78
|
%specifically for Features like JLd and LLa which have many dimensions,
%which could be mapped into three channels of RGB
function image_output = transform_method3(features,img_size)
dim = size(features,1);
features = imresize(features,[dim img_size(2)],'bilinear');
main_feature = features(:,:,1);
min_value = min(main_feature,[],2);
range = max(main_feature - min_value,[],2);
main_feature = (main_feature - min_value)./range;
image = reshape(main_feature,dim/3,3,img_size(2));
image = permute(image,[1 3 2]);
image_output = imresize(image,img_size,'bilinear');
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method4.m
|
.m
|
IEforAR-master/transform_method4.m
| 616 |
utf_8
|
ed4ae61059983b0b84ff2075fcc0c96b
|
function image_output = transform_method4(features)
global cb;%claimed in main file
[dim,frame,body_num] = size(features);
new_features = zeros(2*dim,frame);
new_features(1:2:end,:) = features(:,:,1);
if body_num == 1
new_features(2:2:end,:) = features(:,:,1);
else
new_features(2:2:end,:) = features(:,:,2);
end
min_value = min(new_features,[],2)/1;
range = max(new_features,[],2) - min_value;
color_index = ceil(256*(new_features - min_value)./range);
color_index(color_index == 0 ) = 1;
color_index(isnan(color_index) ) = 1;
temp = cb(color_index,:);
image_output = reshape(temp,2*dim,frame,3);
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJo01.m
|
.m
|
IEforAR-master/extract_feature_JJo01.m
| 1,209 |
utf_8
|
8ba3bd991d61abc8edafc86241e51575
|
function features = extract_feature_JJo01(skeleton_input)
[joint_num,cor_dim,frame,body_num] = size(skeleton_input);
% index = get_JJo_index01;
index = get_JJo_index02;
joints = zeros(2*joint_num,cor_dim,frame);
joints(1:joint_num,:,:) = skeleton_input(:,:,:,1);
if body_num == 1
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,1);
else
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,2);
end
vec = joints(index(:,2),:,:,1) - joints(index(:,1),:,:,1);
features = vec./(sum(vec.^2,2).^(1/2));
features = permute(features,[1 3 2]);
end
%12 joints, two bodies
function index = get_JJo_index01
joint_num = [2 4 5 7 9 11 13 15 17 19 22 24];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%11 joints, two bodies
function index = get_JJo_index02
joint_num = [1 4 6 8 10 12 14 16 18 20 21];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
visualize_skeleton.m
|
.m
|
IEforAR-master/visualize_skeleton.m
| 628 |
utf_8
|
b6769c2058c7a054693356b8ee4f479b
|
function visualize_skeleton(skeleton_input)
[~,~,frame,body_num] = size(skeleton_input);
index = get_chain_index;
figure;
for f=1:frame
for b=1:body_num
figure(b);
for l = 1:18
points = skeleton_input(index(l,:)',:,f,b);
plot3(points(:,1),points(:,2),points(:,3));
hold on
end
end
% hold off
pause(0.1);
end
end
function index = get_chain_index
index = [1 2;
1 17;
1 13;
2 21;
3 4;
3 21;
5 6;
5 21;
6 7;
7 8;
9 10;
9 21;
10 11;
11 12;
13 14;
14 15;
17 18;
18 19];
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method5.m
|
.m
|
IEforAR-master/transform_method5.m
| 364 |
utf_8
|
8cdf1a756b49bf563b8e02ff149e2b56
|
%3 channels for JJd, JLd, LLa
%part of the method is implemented in the begin of this file, i.e. in
% the file-name function
function image_output = transform_method5(features,img_size)
features = imresize(features, img_size,'bilinear');
min_value = min(features,[],2);
range = max(features,[],2) - min_value;
image_output = (features - min_value)./range;
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method2.m
|
.m
|
IEforAR-master/transform_method2.m
| 692 |
utf_8
|
456bd13f1e22d19cb8a73bf4007cd0d9
|
%linear transform (modified from method1 which has some problems)
function image_output = transform_method2(features,img_size)
features = imresize(features,img_size);
[dim,frame,body_num] = size(features);
image_output = zeros(dim,frame,3);
min_value = min(features,[],2);
range = max(features,[],2) - min_value;
image_output(:,:,1) = (features(:,:,1)- repmat(min_value(:,1),1,frame))./repmat(range(:,1),1,frame);
if body_num == 1
image_output(:,:,2) = 1-image_output(:,:,1);%one body
else
image_output(:,:,2) = (features(:,:,2)-repmat(min_value(:,2),1,frame))./repmat(range(:,2),1,frame);%two bodies
end
image_output(:,:,3) = 4*image_output(:,:,2) .* image_output(:,:,1);
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_skeleton_feature.m
|
.m
|
IEforAR-master/extract_skeleton_feature.m
| 413 |
utf_8
|
63df637562e07aba87cb7e8975bb33cf
|
%the codes have been optimised for speed
function features = extract_skeleton_feature(skeleton_input, flags)
%Joint Joint Distances (JJd)
if flags(1) == 1
features.JJd = calculate_JJd(skeleton_input);
end
%Joint Line Distances (JLd)
if flags(2) == 1
features.JLd = calculate_JLd(skeleton_input);
end
%Line Line Angle (LLa)
if flags(3) == 1
features.LLa = calculate_LLa(skeleton_input);
end
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJo.m
|
.m
|
IEforAR-master/extract_feature_JJo.m
| 411 |
utf_8
|
eaef8bc7236879fbcd8978dcf9b4d3b0
|
function features = extract_feature_JJo(skeleton_input)
index = get_JJo_index01;
joints = skeleton_input;
vec = joints(index(:,2),:,:,1) - joints(index(:,1),:,:,1);
features = vec./(sum(vec.^2,2).^(1/2));
features = permute(features,[1 3 2]);
end
function index = get_JJo_index01
%
index = zeros(300,2);
n = 0;
for i = 1:24
for j = i+1:25
n = n + 1;
index(n,:) = [i j];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJv.m
|
.m
|
IEforAR-master/extract_feature_JJv.m
| 375 |
utf_8
|
9161ef7c41e2767f1ea74611a0668b9a
|
function features = extract_feature_JJv(skeleton_input)
index = get_JJo_index01;
joints = skeleton_input;
features = joints(index(:,2),:,:,1) - joints(index(:,1),:,:,1);
features = permute(features,[1 3 2]);
end
function index = get_JJo_index01
%
index = zeros(300,2);
n = 0;
for i = 1:24
for j = i+1:25
n = n + 1;
index(n,:) = [i j];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJd02.m
|
.m
|
IEforAR-master/extract_feature_JJd02.m
| 1,447 |
utf_8
|
128336bd7e04afc3a163f359916bbebe
|
function features = extract_feature_JJd02(skeleton_input)
[joint_num,cor_dim,frame,body_num] = size(skeleton_input);
% index = get_JJd_index01;
index = get_JJd_index02;
joints = zeros(2*joint_num,cor_dim,frame);
joints(1:joint_num,:,:) = skeleton_input(:,:,:,1);
if body_num == 1
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,1);
else
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,2);
end
joints_cyl = zeros(2*joint_num,cor_dim,frame);
% [joints_cyl(:,1,:),joints_cyl(:,2,:),joints_cyl(:,3,:)] = cart2pol(joints(:,1,:),joints(:,2,:),joints(:,3,:));
[joints_cyl(:,1,:),joints_cyl(:,2,:),joints_cyl(:,3,:)] = cart2pol(joints(:,1,:),joints(:,3,:),joints(:,2,:));
vec = joints_cyl(index(:,2),:,:) - joints(index(:,1),:,:);
features = squeeze(sum(vec.^2,2).^(1/2));
end
%12 joints, two bodies
function index = get_JJd_index01
joint_num = [2 4 5 7 9 11 13 15 17 19 22 24];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%11 joints, two bodies
function index = get_JJd_index02
joint_num = [1 4 6 8 10 12 14 16 18 20 21];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
|
github
|
dzwallkilled/IEforAR-master
|
transform_method7.m
|
.m
|
IEforAR-master/transform_method7.m
| 1,043 |
utf_8
|
0b038c0de81e48878b0718f95acfa8e1
|
%temporal information included
function image_output = transform_method7(features)
[dim,frame,~] = size(features);
image = zeros(dim,frame,3);
feature_main = features(:,:,1);
min_value = min(feature_main,[],2);
range = max(feature_main,[],2) - min_value;
image(:,:,1) = ((feature_main - min_value)./range);
velocity = feature_main(:,2:end) - feature_main(:,1:end-1);
temp2 = abs(velocity);
min_value = min(temp2,[],2);
range = max(temp2,[],2) - min_value;
image(:,:,2) = [zeros(dim,1) ((temp2 - min_value)./range).^(1/2)];
%
acceleration = velocity(:,2:end,1) - velocity(:,1:end-1,1);
temp3 = abs(acceleration);
min_value = min(temp3,[],2);
range = max(temp3,[],2) - min_value;
image(:,:,3) = [zeros(dim,2) ((temp3 - min_value)./range).^(1/2)];
% if body_num > 1 %more than one body
% feature_second = features(:,:,1);
% min_value = min(feature_second,[],2);
% range = max(feature_second,[],2) - min_value;
% image(:,:,1) = (0.9*image(:,:,1) + 0.1*((feature_second - min_value)./range));
% end
image_output = image;
end
|
github
|
dzwallkilled/IEforAR-master
|
extract_feature_JJv01.m
|
.m
|
IEforAR-master/extract_feature_JJv01.m
| 1,185 |
utf_8
|
419dac66efe27e6dacc8069fb39be46d
|
function features = extract_feature_JJv01(skeleton_input)
[joint_num,cor_dim,frame,body_num] = size(skeleton_input);
% index = get_JJo_index01;
index = get_JJo_index02;
joints = zeros(2*joint_num,cor_dim,frame);
joints(1:joint_num,:,:) = skeleton_input(:,:,:,1);
if body_num == 1
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,1);
else
joints(joint_num+1:end,:,:) = skeleton_input(:,:,:,2);
end
vec = joints(index(:,2),:,:,1) - joints(index(:,1),:,:,1);
features = vec;
features = permute(features,[1 3 2]);
end
%12 joints, two bodies
function index = get_JJo_index01
joint_num = [2 4 5 7 9 11 13 15 17 19 22 24];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
%11 joints, two bodies
function index = get_JJo_index02
joint_num = [1 4 6 8 10 12 14 16 18 20 21];
joint_num = [joint_num 25+joint_num];
len = length(joint_num);
index = zeros(len*(len-1)/2,2);
n = 0;
for i = 1:len-1
for j = i+1:len
n = n + 1;
index(n,:) = [joint_num(i) joint_num(j)];
end
end
end
|
github
|
pshibby/fepll_public-master
|
operators.m
|
.m
|
fepll_public-master/operators/operators.m
| 13,038 |
utf_8
|
53fbe972cad218d67f9f7ab37ab962ed
|
function op = operators(name, M, N, varargin)
% % Function Name: operators
%
%
% Inputs:
% name : operator name
% - vignetting
% - id (denoising)
% - blur (deconvolution)
% - blur+border (deconv with masked borders)
% - motion blur
% - subresolution (super-resolution)
% - randommasking (inpainting)
% - cs (compressed sensing)
%
% M : number of rows of the image
% N : number of columns of the image
% varargin : arguments depend on the operator used (see examples)
%
% Outputs:
% op : stuct with function definitions and parameters:
% - op.isize : size of x in y = A x
% - op.osize : size of y in y = A x
% - op.A(x) : apply the operator A to x
% - op.At(y) : apply the adjoint A^t to y
% - op.AtA(x) : apply the gram matrix A^t A to x
% - op.inv_AtA_plus_tauId(x, tau)
% : apply (A^t A + tau Id)^-1
% - op.inv_AtA_plus_tauLaplacian(x, tau)
% : apply (A^t A + tau Laplacian)^-1
% - op.Tikhonov(x, tau)
% : apply (A^t A + tau Laplacian)^-1 A^t
% - op.A_norm2 : l2 norm || A ||_2
% - op.A_normF : Frobenius norm || A ||_F
% - op.AtA_normF : Gram Frobenius norm || A^t A ||_F
%
% Examples:
%
% % Gaussian blur of width 3px
% op = operators('blur', M, N, 'width', 3')
%
% % pre-defined blur
% K = fspecial('motion', 10, 45);
% op = operators('blur', M, N, 'kernel', K);
%
% % super-resolution with 0.5px Gaussian bluring, x2 subsampling
% % and Kaiser window appodization
% op = operators('subresoltuion', M, N, 'width', K, 'factor', 0.5,
% 'windowing', 'kaiser');
%
% % inpainting with 50% of missing pixels
% op = operators('randommasking', 'factor', 0.5);
%
% % compressed sensing with x2 compression rate
% op = operators('randommasking', 'factor', 0.5);
% Citation:
% If you use this code please cite:
% S. Parameswaran, C-A. Deledalle, L. Denis and T. Q. Nguyen, "Accelerating
% GMM-based patch priors for image restoration: Three ingredients for a
% 100x speed-up", arXiv.
%
% License details as in license.txt
% ________________________________________
options = makeoptions(varargin{:});
% Laplacian
laplacian = @(x) ...
-4 * x + ...
x([2:end end-1], :) + ...
x([2 1:end-1], :) + ...
x(:, [2:end end-1]) + ...
x(:, [2 1:end-1]);
[u v] = fftgrid(M, N);
klaplacian = zeros(M, N);
klaplacian(u == 0 & v == 0) = -4;
klaplacian(u == -1 & v == 0) = 1;
klaplacian(u == +1 & v == 0) = 1;
klaplacian(u == 0 & v == -1) = 1;
klaplacian(u == 0 & v == +1) = 1;
flaplacian = real(fft2(klaplacian));
op.name = name;
switch name
case 'vignetting'
op.isize = [M, N];
op.osize = [M, N];
w = 0.2+0.8*ifftshift(exp(-sqrt((u.^2/M^2 + v.^2/N^2)*6).^5));
op.A = @(x) w .* x;
op.At = @(x) w .* x;
op.AtA = @(x) w.^2 .* x;
op.inv_AtA_plus_tauId = @(x, tau) ...
x ./ (w.^2 + tau);
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
imcgs(@(x) op.AtA(x) + tau * laplacian(x), x, ...
1e-6, 8, [], [], x(:) ./ w(:));
op.Tikhonov = @(x, tau) ...
op.inv_AtA_plus_tauLaplacian(op.At(x), tau);
op.A_norm2 = max(w(:));
op.A_normF = sqrt(sum(w(:).^2));
op.AtA_normF = sqrt(sum(w(:).^4));
case 'id' % denoising
op.isize = [M, N];
op.osize = [M, N];
op.A = @(x) x;
op.At = @(x) x;
op.AtA = @(x) x;
op.inv_AtA_plus_tauId = @(x, tau) ...
x / (1 + tau);
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
imcgs(@(x) op.AtA(x) + tau * laplacian(x), x, ...
1e-6, 8);
op.Tikhonov = @(x, tau) ...
op.inv_AtA_plus_tauLaplacian(op.At(x), tau);
op.A_norm2 = 1;
op.A_normF = 1 * sqrt(M*N);
op.AtA_normF = 1 * sqrt(M*N);
case 'blur' % deconvolution
K = getoptions(options, 'kernel', []);
if isempty(K)
h = getoptions(options, 'width', 1.5);
K = exp(-(u.^2 + v.^2) / (2 * h^2));
MK = ceil(8 * h) + 1;
NK = ceil(8 * h) + 1;
sK = zeros(MK, NK);
sK(:) = ifftshift(K(-(MK-1)/2 <= u & u <= (MK-1)/2 & ...
-(NK-1)/2 <= v & v <= (NK-1)/2));
K = sK / sum(sK(:));
end
[MK, NK] = size(K);
if mod(MK, 2) == 0
MK = MK + 1;
end
if mod(NK, 2) == 0
NK = NK + 1;
end
kernel = zeros(M, N);
kernel(fftshift(-(MK-1)/2 <= u & u <= (MK-1)/2 & ...
-(NK-1)/2 <= v & v <= (NK-1)/2)) = K(:);
kernel = ifftshift(kernel);
fkernel = fft2(kernel);
mk = floor((MK-1)/2);
nk = floor((NK-1)/2);
op.taper = @(x) ...
multiedgetaper(padarray(x, [mk nk], 'replicate', 'both'), K, 3);
op.zp = @(x) [zeros(mk, N) ;
zeros(M-2*mk, nk) x zeros(M-2*mk, nk);
zeros(mk, N) ];
op.crop = @(x) x((1+mk):(end-mk), (1+nk):(end-nk));
op.isize = [M, N];
op.osize = [M, N];
op.A = @(x) real(ifft2(fkernel .* fft2(x)));
op.At = @(x) real(ifft2(conj(fkernel) .* fft2(x)));
op.AtA = @(x) real(ifft2(abs(fkernel).^2 .* fft2(x)));
op.inv_AtA_plus_tauId = @(x, tau) ...
real(ifft2(1./(abs(fkernel).^2 + tau) .* fft2(x)));
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
real(ifft2(1./(abs(fkernel).^2 - tau .* flaplacian) .* fft2(x)));
op.Tikhonov = @(x, tau) ...
real(ifft2(conj(fkernel)./(abs(fkernel).^2 - tau .* flaplacian) .* fft2(x)));
op.A_norm2 = 1;
op.A_normF = sqrt(sum(abs(fkernel(:)).^2));
op.AtA_normF = sqrt(sum(abs(fkernel(:)).^4));
case 'blur+border' % deconvolution with masked borders
K = getoptions(options, 'kernel', [], 1);
[MK NK] = size(K);
kernel = zeros(M, N);
kernel(fftshift(-(MK-1)/2 <= u & u <= (MK-1)/2 & ...
-(NK-1)/2 <= v & v <= (NK-1)/2)) = K;
kernel = ifftshift(kernel);
fkernel = fft2(kernel);
mk = ceil((MK-1)/2);
nk = ceil((NK-1)/2);
op.isize = [M, N];
op.osize = [M-2*mk, N-2*nk];
crop = @(x) x((1+mk):(end-mk), (1+nk):(end-nk));
zp = @(x) [zeros(mk, N) ;
zeros(M-2*mk, nk) x zeros(M-2*mk, nk);
zeros(mk, N) ];
op.A = @(x) crop(ifft2(fkernel .* fft2(x)));
op.At = @(x) ifft2(conj(fkernel) .* fft2(zp(x)));
op.AtA = @(x) op.At(op.A(x));
op.inv_AtA_plus_tauId = @(x, tau) ...
imcgs(@(x) op.AtA(x) + tau * x, x, ...
1e-9, 1000);
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
imcgs(@(x) op.AtA(x) - tau * laplacian(x), x, ...
1e-9, 1000, [], [], mean(x(:))*ones(size(x(:))));
op.Tikhonov = @(x, tau) ...
op.inv_AtA_plus_tauLaplacian(op.At(x), tau);
case 'motionblur'
K = fspecial('motion', 10, 45);
op = operators('blur', M, N, 'kernel', K');
op.name = name;
return
case 'subresolution' % super-resolution
h = getoptions(options, 'width', 0.5);
f = getoptions(options, 'factor', 0.7);
windowing = getoptions(options, 'windowing', 'kaiser');
% Define blur
kernel = exp(-(u.^2 + v.^2) / (2 * h^2));
kernel = kernel ./ sum(kernel(:));
fkernel = fft2(kernel);
op.isize = [M, N];
% Define subsampling mask
mask = -M/2*f <= u & u < M/2*f & ...
-N/2*f <= v & v < N/2*f;
op.osize = [sum(mask(:,1)), sum(mask(1,:))];
clip = @(x) reshape(x(mask), op.osize);
zpad = @(x) zerropadding(x, mask);
% Define anti-aliasing windowing
switch windowing
case 'hamming'
hw = mask .* max((1 - cos(2*pi*u / (M*f-1) + pi))/2 .* ...
(1 - cos(2*pi*v / (N*f-1) + pi))/2, 0);
case 'kaiser'
alpha = -log(f);
hw = mask.* (besseli(0, pi * alpha * sqrt(1 - (2*u/(M*f-1)).^2)) .* ...
besseli(0, pi * alpha * sqrt(1 - (2*v/(N*f-1)).^2)) ...
./ besseli(0, pi * alpha)^2);
otherwise
hw = 1;
end
fkernel = fkernel .* hw;
% S is the renormalization of fft2 when changing image size
S = prod(op.osize) / prod(op.isize);
% Main definitions
op.A = @(x) real(ifft2(clip(fkernel .* fft2(x))) * S);
op.At = @(x) real(ifft2(conj(fkernel) .* zpad(fft2(x))));
op.AtA = @(x) real(ifft2(abs(fkernel).^2 .* mask .* fft2(x) * S));
op.inv_AtA_plus_tauId = @(x, tau) ...
real(ifft2(1./(mask .* abs(fkernel).^2 * S + tau) .* fft2(x)));
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
real(ifft2(1 ./ (mask .* abs(fkernel).^2 * S - tau * flaplacian) .* fft2(x)));
op.Tikhonov = @(x, tau) ...
real(ifft2(conj(fkernel) ./ (mask .* abs(fkernel).^2 * S - tau * flaplacian) ...
.* zpad(fft2(x))));
op.A_norm2 = sqrt(S);
op.A_normF = sqrt(sum(mask(:) .* abs(fkernel(:)).^2) * S);
op.AtA_normF = sqrt(sum(mask(:) .* abs(fkernel(:)).^4) * S^2);
case 'randommasking' % inpainting
f = getoptions(options, 'factor', 0.5);
mask = zeros(M, N);
idx = randperm(M*N);
P = ceil(M*N*f);
mask(idx(1:P)) = 1;
op.isize = [M, N];
op.osize = [M, N];
op.mask = mask;
op.A = @(x) mask .* x;
op.At = @(x) mask .* x;
op.AtA = @(x) mask .* x;
op.inv_AtA_plus_tauId = @(x, tau) ...
x ./ (mask + tau);
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
imcgs(@(x) op.AtA(x) + tau * laplacian(x), x, ...
1e-6, 8);
op.Tikhonov = @(x, tau) ...
op.inv_AtA_plus_tauLaplacian(op.At(x), tau);
op.A_norm2 = 1;
op.A_normF = sqrt(P);
op.AtA_normF = sqrt(P);
case 'cs' % compressed sensing
f = getoptions(options, 'factor', 0.5);
Ms = ceil(M * sqrt(f));
Ns = ceil(N * sqrt(f));
p1 = [ 1, randperm(M*N-1)+1 ];
p2 = [ 1, randperm(M*N-1)+1 ];
P = Ms * Ns;
p2 = p2(1:P);
P = ceil(Ms * Ns);
f1 = @(x) reshape(x(p1), [M, N]);
f2 = @(x) x(p2);
f2 = @(x) f2(x(:));
f1t = @(x) ipa(x, M, N, p1);
f2t = @(x) ipa(x, M, N, p2);
op.isize = [M, N];
op.osize = [Ms, Ns];
r = ones(P, 1);
op.A = @(x) reshape(r .* f2(idct2(f1(dct2(x)))), [Ms Ns]);
op.At = @(x) real(idct2(f1t(dct2(f2t(r .* reshape(x, [P 1]))))));
ri = zeros(M, N); ri(p2) = r(:);
op.AtA = @(x) real(idct2(f1t(dct2(ri.^2 .* idct2(f1(dct2(x)))))));
op.inv_AtA_plus_tauId = @(x, tau) ...
real(idct2(f1t(dct2(1./(ri.^2 + tau) .* idct2(f1(dct2(x)))))));;
op.inv_AtA_plus_tauLaplacian = @(x, tau) ...
imcgs(@(x) op.AtA(x) + tau * laplacian(x), x, ...
1e-6, 8);
op.Tikhonov = @(x, tau) ...
op.inv_AtA_plus_tauLaplacian(op.At(x), tau);
op.A_norm2 = max(r);
op.A_normF = sqrt(mean(r.^2))*sqrt(P);
op.AtA_normF = sqrt(mean(r.^4))*sqrt(P);
otherwise
error(sprintf('Operator %s not implemented', name));
end
if ~isfield(op, 'A_norm2')
op.A_norm2 = estimate_norm2(op.A, op.At, op.isize);
end
if ~isfield(op, 'A_normF')
op.A_normF = estimate_normF(op.A, op.isize);
end
if ~isfield(op, 'AtA_normF')
op.AtA_normF = estimate_normF(op.AtA, op.isize);
end
function z = zerropadding(x, mask)
z = zeros(size(mask));
z(mask) = x;
function z = ipa(x, M, N, idx)
z = zeros(M*N, 1);
z(idx) = x(:);
z = reshape(z, [M, N]);
%Norm_2^2 = sqrt(max(lambdamax(A' A)))
function n2 = estimate_norm2(A, At, size)
R = 50;
vect = @(x) x(:);
z = ones(size);
for i = 1:R
z = At(A(z));
z = z / norm(z);
end
n2 = sum(vect(z .* At(A(z)))) / sum(vect(z.^2));
n2 = sqrt(n2);
%Norm_F^2 = sqrt(trace(A' A))
function n2 = estimate_normF(A, size)
R = 100;
n = zeros(R, 1);
vect = @(x) x(:);
for i = 1:R
z = sign(randn(size));
n(i) = norm(vect(A(z)))^2;
end
n2 = sqrt(mean(n));
function x = multiedgetaper(y, K, n)
x = y;
for i = 1:n
x = edgetaper(x, K);
end
|
github
|
pshibby/fepll_public-master
|
gstree_match.m
|
.m
|
fepll_public-master/fepll/gstree_match.m
| 2,286 |
utf_8
|
7aff4b07361ca7601c40ee3360b81c91
|
function labels = gstree_match(y, GStree, sig2, varargin)
% % Function Name: gstree_match
%
%
% Inputs:
% y : matrix containing image patches
% GStree : GMM-tree
% sig2 : noise variance
%
% Outputs:
% labels : index of Gaussian components each patch belongs to
% Citation:
% If you use this code please cite:
% S. Parameswaran, C-A. Deledalle, L. Denis and T. Q. Nguyen, "Accelerating
% GMM-based patch priors for image restoration: Three ingredients for a
% 100x speed-up", arXiv.
%
% License details as in license.txt
% ________________________________________
options = makeoptions(varargin{:});
truncation = getoptions(options, 'truncation', isfield(GStree, 't'));
truncation = getoptions(options, 'trunc_match', truncation);
sy2 = sum(y.^2, 1);
labels = gstree_match_rec(y, sy2, GStree, sig2, truncation);
end
function labels = gstree_match_rec(y, sy2, GStree, sig2, truncation)
[d, n] = size(y);
if ~isfield(GStree, 'child')
error('GStree must have children');
end
K = length(GStree.child);
energy = zeros(K, n);
for k = 1:K
iSPlusSig2 = 1 ./ (GStree.child{k}.S + sig2);
if ~truncation
uy = GStree.child{k}.U' * y;
energy(k, :) = gmm_distance(uy, iSPlusSig2, ...
-2 * log(GStree.child{k}.wts));
else
t = GStree.child{k}.t;
% Energy for the t-1 first dimensions
uy = GStree.child{k}.U(:,1:(t-1))' * y;
energy(k, :) = gmm_distance(uy, iSPlusSig2(1:(t-1)), ...
-2 * log(GStree.child{k}.wts));
% Energy for the d-t+1 last dimensions
uyc = sy2 - sum(uy.^2, 1);
energy(k, :) = energy(k, :) + ...
uyc * iSPlusSig2(t) - (d - t + 1) * log(iSPlusSig2(t));
end
end
[~, childidx] = min(energy, [], 1);
labels = zeros(1, n);
for k = 1:K
if sum(childidx == k) == 0
continue;
end
if ~isfield(GStree.child{k}, 'child')
labels(childidx == k) = GStree.child{k}.idx;
else
labels(childidx == k) = ...
gstree_match_rec(y(:, childidx == k), ...
sy2(:, childidx == k), ...
GStree.child{k}, sig2, truncation);
end
end
end
|
github
|
pshibby/fepll_public-master
|
gstree_sv_threshold.m
|
.m
|
fepll_public-master/fepll/gstree_sv_threshold.m
| 1,291 |
utf_8
|
f03453a4b1dd0ab6bcdd432629f255b3
|
function [GStree, GS] = gstree_sv_threshold(GStree, GS, p)
% % Function Name: gstee_sv_threshold
%
%
% Inputs:
% GStree : GMM-tree
% GS : GMM model
% p : threshold for truncation
%
% Outputs:
% GStree : GMM-tree after flat-tail approximation
% GS : GMM model after flat-tail approximation
% Citation:
% If you use this code please cite:
% S. Parameswaran, C-A. Deledalle, L. Denis and T. Q. Nguyen, "Accelerating
% GMM-based patch priors for image restoration: Three ingredients for a
% 100x speed-up", arXiv.
%
% License details as in license.txt
% ________________________________________
for k = 1:GS.nmodels
S = GS.S{k};
e = cumsum(S) / sum(S);
idx = find(e >= p);
t = min(idx);
GS.S{k}(t:end) = mean(S(t:end));
GS.Sigma{k} = GS.U{k} * diag(GS.S{k}) * GS.U{k}';
GS.t(k) = t;
end
GStree = gstree_sv_threshold_rec(GStree, p);
function GStree = gstree_sv_threshold_rec(GStree, p)
S = GStree.S;
e = cumsum(S) / sum(S);
idx = find(e >= p);
t = min(idx);
GStree.S(t:end) = mean(GStree.S(t:end));
GStree.Sigma = GStree.U * diag(GStree.S) * GStree.U';
GStree.t = t;
if isfield(GStree, 'child')
for k = 1:length(GStree.child)
GStree.child{k} = gstree_sv_threshold_rec(GStree.child{k}, p);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
build_map.m
|
.m
|
GT_mobile_robotics-master/mobile_robotics/Session 2/build_map.m
| 2,200 |
utf_8
|
3b8057bef157c70bd61c6987b12a5660
|
clear all
close all
clc
%% INTRODUCTION
% To start using a turtlebot 3 following procedure
% needs to be followed:
%
% 1) Turn the TB3 on.
% 2) Set up the putty SSH connection (IP adress is given)
% 3) Type "bringup".
% 4) You are now able to run your MATLAB code
%
% This file file will let the turtlebot drive a square pattern. Whilst
% driving, it will build an occupancy grid map. This map is saved and can
% later be used for localization.
%% MAPPING
% Connection to the ROS node system
ip = '192.168.42.1'; % This needs to be the ip adres of the ROS master
turtlebot = Turtlebot_GT(ip); % Make Turtlebot object
% initialize map
map = robotics.OccupancyGrid(15,15,20);
pose = [5;5;0];
Pcov = 0.01*eye(3);
% drive square and map environment
dist = 0.25;
angle = pi/2;
speed = 0.1;
for i=1:4
[map, pose, Pcov] = map_while_driving(turtlebot, map, dist, speed, pose, Pcov);
[map, pose, Pcov] = map_while_turning(turtlebot, map, angle, -speed*2, pose, Pcov);
end
turtlebot.stop() % stop driving
save 'map.mat' map % save map
rosshutdown % shutdown ros master
%% FUNCTION DEFINITIONS
function [map, pose, Pcov] = map_while_driving(turtlebot, map, dist, speed, pose, Pcov)
turtlebot.set_linear_angular_velocity(speed,0.0);
d = 0;
maxrange = 5;
while abs(d) <= dist
% Receive laser scan and odometry DATA
[ds,dth] = turtlebot.get_odometry();
% Predict new pose with motion model
[~, pose] = motionModel(pose, Pcov, ds, dth, 1);
d = d + ds;
% Get scan data
scan = turtlebot.get_scan();
% Add to map
insertRay(map,pose,scan.Ranges,scan.Angles,maxrange);
show(map)
end
end
function [map, pose, Pcov] = map_while_turning(turtlebot, map, angle, speed, pose, Pcov)
turtlebot.set_linear_angular_velocity(0.0,speed);
maxrange = 5;
th = 0;
while abs(th) <= angle
% Receive laser scan and odometry DATA
[ds,dth] = turtlebot.get_odometry();
% Predict new pose with motion model
[~, pose] = motionModel(pose, Pcov, ds, dth, 1);
th = th + dth;
% Get scan data
scan = turtlebot.get_scan();
% Add to map
insertRay(map,pose,scan.Ranges,scan.Angles,maxrange);
show(map)
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
protectfig.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/protectfig.m
| 881 |
utf_8
|
02ea9bf0328e3371f877b1e9e1b5be6d
|
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function protectfig(h)
if nargin == 0
h = gcf;
end
set(h, 'HandleVisibility', 'off');
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
Polygon.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/Polygon.m
| 44,407 |
utf_8
|
0f8730e021e78210d0e8ae7ff334f5e9
|
%POLYGON Polygon class
%
% A general class for manipulating polygons and vectors of polygons.
%
% Methods::
% plot Plot polygon
% area Area of polygon
% moments Moments of polygon
% centroid Centroid of polygon
% perimeter Perimter of polygon
% transform Transform polygon
% inside Test if points are inside polygon
% intersection Intersection of two polygons
% difference Difference of two polygons
% union Union of two polygons
% xor Exclusive or of two polygons
% display print the polygon in human readable form
% char convert the polgyon to human readable string
%
% Properties::
% vertices List of polygon vertices, one per column
% extent Bounding box [minx maxx; miny maxy]
% n Number of vertices
%
% Notes::
% - This is reference class object
% - Polygon objects can be used in vectors and arrays
%
% Acknowledgement::
%
% The methods: inside, intersection, difference, union, and xor are based on code
% written by:
% Kirill K. Pankratov, [email protected],
% http://puddle.mit.edu/~glenn/kirill/saga.html
% and require a licence. However the author does not respond to email regarding
% the licence, so use with care, and modify with acknowledgement.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% TODO
% split the code in two. Simple polygon functions in Polgon class, subclass with
% Pankratov code to Polygon2.
% add method to detect empty polygon, overload isempty
classdef Polygon < handle
properties
vertices
extent
end
properties (Dependent=true)
n
x
y
end
methods
function p = Polygon(v, wh)
%Polygon.Polygon Polygon class constructor
%
% P = Polygon(V) is a polygon with vertices given by V, one column per
% vertex.
%
% P = Polygon(C, WH) is a rectangle centred at C with dimensions
% WH=[WIDTH, HEIGHT].
if nargin == 0
p.n = 0;
p.vertices = [];
return;
end
if nargin < 2
if numrows(v) ~= 2
error('vertices must have two rows');
end
p.vertices = v;
end
if nargin == 2
if length(v) ~= 2
error('first argument must be polygon centre');
end
if length(wh) ~= 2
error('second arugment must be width height');
end
p.vertices = [
v(1)-wh(1)/2 v(1)+wh(1)/2 v(1)+wh(1)/2 v(1)-wh(1)/2
v(2)-wh(2)/2 v(2)-wh(2)/2 v(2)+wh(2)/2 v(2)+wh(2)/2 ];
end
% compute the extent
p.extent(1,1) = min(p.x);
p.extent(1,2) = max(p.x);
p.extent(2,1) = min(p.y);
p.extent(2,2) = max(p.y);
end
function r = get.n(p)
r = numcols(p.vertices);
end
function r = get.x(p)
r = p.vertices(1,:)';
end
function r = get.y(p)
r = p.vertices(2,:)';
end
function r = set.n(p)
error('cant set property');
end
function r = set.x(p)
error('cant set property');
end
function r = set.y(p)
error('cant set property');
end
function ss = char(p)
%Polygon.char String representation
%
% S = P.char() is a compact representation of the polgyon in human
% readable form.
ss = '';
for i=1:length(p)
if p(i).n <= 4
if length(p) > 1
s = sprintf('%2d: ', i);
else
s = '';
end
v = p(i).vertices;
for k=1:p(i).n
s = strcat(s, sprintf('(%g,%g)', v(:,k)));
if k~=p(i).n
s = strcat(s, ', ');
end
end
else
s = sprintf('... %d vertices', p.n)
end
ss =strvcat(ss, s);
end
end
function display(p)
%Polygon.display Display polygon
%
% P.display() displays the polygon in a compact human readable form.
%
% See also Polygon.char.
loose = strcmp( get(0, 'FormatSpacing'), 'loose');
if loose
disp(' ');
end
disp([inputname(1), ' = '])
if loose
disp(' ');
end
disp(char(p))
if loose
disp(' ');
end
end
function plot(plist, varargin)
%Polygon.plot Draw polygon
%
% P.plot() draws the polygon P in the current plot.
%
% P.plot(LS) as above but pass the arguments LS to plot.
%
% Notes::
% - The polygon is added to the current plot.
opt.fill = [];
[opt,args] = tb_optparse(opt, varargin);
ish = ishold;
hold all
for p=plist
% for every polygon in the list
% get the vertices
X = p.vertices(1,:)';
Y = p.vertices(2,:)';
while true
% look for NaNs which indicate disjoint vertex sets
k = find(isnan(X));
if length(k) > 0
% if a NaN chop out the segment before and after
k = k(1);
x = X(1:k-1);
y = Y(1:k-1);
X = X(k+1:end);
Y = Y(k+1:end);
else
x = X; y = Y;
end
% close the polygon
x = [x; x(1)];
y = [y; y(1)];
if opt.fill
patch(x, y, opt.fill);
else
plot(x, y, args{:});
end
if length(k) == 0
break;
end
end
end
if ~ish
hold off
end
end
function a = area(p)
%Polygon.area Area of polygon
%
% A = P.area() is the area of the polygon.
%
% See also Polygon.moments.
a = p.moments(0, 0);
end
function m = moments(p, mp, mq)
%Polygon.moments Moments of polygon
%
% A = P.moments(p, q) is the pq'th moment of the polygon.
%
% See also Polygon.area, Polygon.centroid, mpq_poly.
m = mpq_poly(p.vertices, mp, mq);
end
function q = transform(p, T)
%Polygon.transform Transform polygon vertices
%
% P2 = P.transform(T) is a new Polygon object whose vertices have
% been transformed by the SE(2) homgoeneous transformation T (3x3).
if length(T) == 3
T = se2(T);
end
q = Polygon( homtrans(T, p.vertices) );
end
function f = inside(p, points)
%Polygon.inside Test if points are inside polygon
%
% IN = P.inside(P) tests if points given by columns of P (2xN) are inside
% the polygon. The corresponding elements of IN (1xN) are either true or
% false.
f = inpolygon(points(1,:), points(2,:), p.x, p.y);
end
function c = centroid(p)
%Polygon.centroid Centroid of polygon
%
% X = P.centroid() is the centroid of the polygon.
%
% See also Polygon.moments.
c = [p.moments(1,0) p.moments(0,1)] / p.area();
end
function r = perimeter(p)
%Polygon.perimeter Perimeter of polygon
%
% L = P.perimeter() is the perimeter of the polygon.
p = sum(sqrt(diff(p.x).^2+diff(p.y).^2));
end
function f = intersect(p, plist)
%Polygon.intersect Intersection of polygon with list of polygons
%
% I = P.intersect(PLIST) indicates whether or not the Polygon P
% intersects with
%
% i(j) = 1 if p intersects polylist(j), else 0.
% Based on ISINTPL
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/20/95, 08/25/95
f = [];
for q=plist
f = [f isintpl(p.x, p.y, q.x, q.y)];
end
end
function f = intersect_line(p, l)
%Polygon.intersect_line Intersection of polygon and line segment
%
% I = P.intersect_line(L) is the intersection points of a polygon P with
% the line segment L=[x1 x2; y1 y2]. I (2xN) has one column per
% intersection, each column is [x y]'.
f = [];
% find intersections
for i=1:p.n
in = mod(i, p.n)+1;
xv = [p.x(i); p.x(in)];
yv = [p.y(i); p.y(in)];
intsec = iscross(xv, yv, l(1,:)', l(2,:)');
if intsec
[x,y] = intsecl(xv, yv, l(1,:)', l(2,:)');
f = [f [x;y]];
end
end
end
function r = difference(p, q)
%Polygon.difference Difference of polygons
%
% D = P.difference(Q) is polygon P minus polygon Q.
%
% Notes::
% - If polygons P and Q are not intersecting, returns
% coordinates of P.
% - If the result D is not simply connected or consists of
% several polygons, resulting vertex list will contain NaNs.
% POLYDIFF Difference of 2 polygons.
% [XO,YO] = POLYDIFF(X1,Y1,X2,Y2) Calculates polygon(s) P
% of difference of polygons P1 and P1 with coordinates
% X1, Y1 and X2, Y2.
% The resulting polygon(s) is a set of all points which belong
% to P1 but not to to P2: P = P1 & ~P2.
% The input polygons must be non-self-intersecting and
% simply connected.
%
% If polygons P1, P2 are not intersecting, returns
% coordinates of the first polygon X1, X2.
% If the result P is not simply connected or consists of several
% polygons, resulting boundary consists of concatenated
% coordinates of these polygons, separated by NaN.
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/25/95
% Call POLYBOOL with flag=3
[xo,yo,ind] = polybool(p.x, p.y, q.x, q.y, 3);
r = Polygon([xo(:) yo(:)]');
end
function r = intersection(p, q)
%Polygon.intersection Intersection of polygons
%
% I = P.intersection(Q) is a Polygon representing the
% intersection of polygons P and Q.
%
% Notes::
% - If these polygons are not intersecting, returns empty polygon.
% - If intersection consist of several disjoint polygons
% (for non-convex P or Q) then vertices of I is the concatenation
% of the vertices of these polygons.
% POLYINTS Intersection of 2 polygons.
% [XO,YO] = POLYINTS(X1,Y1,X2,Y2) Calculates polygon(s)
% if intersection of polygons with coordinates X1, Y1
% and X2, Y2.
% The resulting polygon(s) is a set of all points which
% belong to both P1 and P2: P = P1 & P2.
% These polygons must be non-self-intersecting and
% simply connected.
%
% If these polygons are not intersecting, returns empty.
% If intersection consist of several disjoint polygons
% (for non-convex P1 or P2) output vectors XO, YO consist
% of concatenated cooddinates of these polygons,
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/25/95
% Call POLYBOOL with flag=1
[xo,yo,ind] = polybool(p.x, p.y, q.x, q.y, 1);
r = Polygon([xo(:) yo(:)]');
end
function r = union(p, q)
%Polygon.union Union of polygons
%
% I = P.union(Q) is a polygon representing the
% union of polygons P and Q.
%
% Notes::
% - If these polygons are not intersecting, returns a polygon with
% vertices of both polygons separated by NaNs.
% - If the result P is not simply connected (such as a polygon
% with a "hole") the resulting contour consist of counter-
% clockwise "outer boundary" and one or more clock-wise
% "inner boundaries" around "holes".
% POLYUNI Union of 2 polygons.
% [XO,YO] = POLYINT(X1,Y1,X2,Y2) Calculates polygon(s) P
% which is (are) union of polygons P1 and P2 with coordinates
% X1, Y1 and X2, Y2.
% The resulting polygon(s) is a set of all points which belong
% either to P1 or to P2: P = P1 | P2.
% The input polygons must be non-self-intersecting and
% simply connected.
%
% If polygons P1, P2 are not intersecting, returns
% coordinates of the both polygons separated by NaN.
% If both P1 and P2 are convex, their boundaries can have no
% more than 2 intersections. The result is also a convex
% polygon.
% If the result P is not simply connected (such as a polygon
% with a "hole") the resulting contour consist of counter-
% clockwise "outer boundary" and one or more clock-wise
% "inner boundaries" around "holes".
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/25/95
% Call POLYBOOL with flag=2 ..........
[xo,yo,ind] = polybool(p.x, p.y, q.x, q.y, 2);
r = Polygon([xo(:) yo(:)]');
end
function r = xor(p, q)
%Polygon.xor Exclusive or of polygons
%
% I = P.union(Q) is a polygon representing the
% exclusive-or of polygons P and Q.
%
% Notes::
% - If these polygons are not intersecting, returns a polygon with
% vertices of both polygons separated by NaNs.
% - If the result P is not simply connected (such as a polygon
% with a "hole") the resulting contour consist of counter-
% clockwise "outer boundary" and one or more clock-wise
% "inner boundaries" around "holes".
% POLYXOR Exclusive OR of 2 polygons.
% [XO,YO] = POLYXOR(X1,Y1,X2,Y2) Calculates polygon(s) P
% of difference of polygons P1 and P1 with coordinates
% X1, Y1 and X2, Y2.
% The resulting polygon(s) is a set of all points which belong
% either to P1 or to P2 but not to both:
% P = (P1 & ~P2) | (P2 & ~P1).
% The input polygons must be non-self-intersecting and
% simply connected.
%
% If polygons P1, P2 are not intersecting, returns
% coordinates of the both polygons separated by NaN.
% If the result P is not simply connected or consists of several
% polygons, resulting boundary consists of concatenated
% coordinates of these polygons, separated by NaN.
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/25/95
% Call POLYBOOL twice with flag=3
[xx,yy,ind] = polybool(p.x, p.y, q.x, q.y, 3);
xo = [xx; NaN]; yo = [yy; NaN];
[xx,yy,ind] = polybool(q.x, q.y, p.x, p.y, 3);
xo = [xo; xx]; yo = [yo; yy];
r = Polygon([xo(:) yo(:)]');
end
end % methods
end % classdef
function [is,in,un] = interval(x1,x2)
% Intersection and union of 2 intervals.
% [IS,IN,UN] = INTERVAL(X1,X2) calculates pair-wise
% intersection IN and union UN of N pairs of
% intervals with coordinates X1 and X2 (both are
% 2 by N vectors). Returns 1 by N boolean vector IS
% equal to 1 if intervals have non-empty intersection
% and 0 if they don't.
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 08/24/95
% Handle input ...........................
if nargin==0, help interval, return, end
if nargin==1
un = x1;
else
un = [x1; x2];
end
[in,un] = sort(un); % Sort both intervals together
un = un(1:2,:)-1;
is = sum(floor(un/2)); % Check for [0 0 1 1] or [1 1 0 0]
is = (is==1);
ii = find(in(2,:)==in(3,:));
is(ii) = .5*ones(size(ii));
% Extract intersection and union from sorted coordinates
if nargout>1
un = in([1 4],:);
in = in(2:3,:);
in(:,~is) = flipud(in(:,~is));
end
end
function [is,S] = iscross(x1,y1,x2,y2,tol)
% ISCROSS Finds whether pairs of lines cross each other
% [IS,S] = ISCROSS(X1,Y1,X2,Y2) where arguments X1, Y1,
% X2, Y2 are all 2 by N matrices are coordinates of
% ends of the pairs of line segments.
% Returns vector IS (1 by N) consisting of ones if
% corresponding pairs cross each other, zeros if they
% don't and .5 if an end of one line segment lies on
% another segment.
% Also returns a matrix S (4 by N) with each row
% consisting of cross products (double areas of
% corresponding triangles) built on the following points:
% (X2(1,:),Y2(1,:)),(X1(1,:),Y1(1,:)),(X2(2,:),Y2(2,:)),
% (X2(1,:),Y2(1,:)),(X1(2,:),Y1(2,:)),(X2(2,:),Y2(2,:))
% (X1(1,:),Y1(1,:)),(X2(1,:),Y2(1,:)),(X1(2,:),Y1(2,:))
% (X1(1,:),Y1(1,:)),(X2(2,:),Y2(2,:)),(X1(2,:),Y1(2,:))
% The signs of these 4 areas can be used to determine
% whether these lines and their continuations cross each
% other.
% [IS,S] = ISCROSS(X1,Y1,X2,Y2,TOL) uses tolerance TOL
% for detecting the crossings (default is 0).
% Copyright (c) 1995 by Kirill K. Pankratov
% [email protected]
% 08/14/94, 05/18/95, 08/25/95
% Defaults and parameters .......................
tol_dflt = 0; % Tolerance for area calculation
is_chk = 1; % Check input arguments
% Handle input ..................................
if nargin==0, help iscross, return, end
if nargin<4 % Check if all 4 entered
error(' Not enough input arguments')
end
if nargin<5, tol = tol_dflt; end
if tol < 0, is_chk = 0; tol = 0; end
% Check the format of arguments .................
if is_chk
[x1,y1,x2,y2] = linechk(x1,y1,x2,y2);
end
len = size(x1,2);
o2 = ones(2,1);
% Find if the ranges of pairs of segments intersect
[isx,S,A] = interval(x1,x2);
scx = diff(A);
[isy,S,A] = interval(y1,y2);
scy = diff(A);
is = isx & isy;
% If S values are not needed, extract only those pairs
% which have intersecting ranges ..............
if nargout < 2
isx = find(is); % Indices of pairs to be checked
% further
x1 = x1(:,isx);
x2 = x2(:,isx);
y1 = y1(:,isx);
y2 = y2(:,isx);
is = is(isx);
if isempty(is), is = zeros(1,len); return, end
scx = scx(isx);
scy = scy(isx);
end
% Rescale by ranges ...........................
x1 = x1.*scx(o2,:);
x2 = x2.*scx(o2,:);
y1 = y1.*scy(o2,:);
y2 = y2.*scy(o2,:);
% Calculate areas .............................
S = zeros(4,length(scx));
S(1,:) = (x2(1,:)-x1(1,:)).*(y2(2,:)-y1(1,:));
S(1,:) = S(1,:)-(x2(2,:)-x1(1,:)).*(y2(1,:)-y1(1,:));
S(2,:) = (x2(1,:)-x1(2,:)).*(y2(2,:)-y1(2,:));
S(2,:) = S(2,:)-(x2(2,:)-x1(2,:)).*(y2(1,:)-y1(2,:));
S(3,:) = (x1(1,:)-x2(1,:)).*(y1(2,:)-y2(1,:));
S(3,:) = S(3,:)-(x1(2,:)-x2(1,:)).*(y1(1,:)-y2(1,:));
S(4,:) = (x1(1,:)-x2(2,:)).*(y1(2,:)-y2(2,:));
S(4,:) = S(4,:)-(x1(2,:)-x2(2,:)).*(y1(1,:)-y2(2,:));
% Find if they cross each other ...............
is = (S(1,:).*S(2,:)<=0)&(S(3,:).*S(4,:)<=0);
% Find very close to intersection
isy = min(abs(S));
ii = find(isy<=tol & is);
is(ii) = .5*ones(size(ii));
% Output
if nargout < 2
isy = zeros(1,len);
isy(isx) = is;
is = isy;
else
isy = scx.*scy;
ii = find(~isy);
isy(ii) = ones(size(ii));
S = S./isy(ones(4,1),:);
end
end
function [xo,yo,ind] = polybool(x1,y1,x2,y2,flag)
% [XO,YO] = POLYBOOL(X1,Y1,X2,Y2,FLAG)
% calulates results of Boolean operations on
% a pair of polygons.
% FLAG Specifies the type of the operation:
% 1 - Intersection (P1 & P2)
% 2 - Union (P1 | P2)
% 3 - Difference (P1 & ~P2)
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/25/95, 09/07/95
% This program calls the following functions:
% AREA, ISINTPL, ISCROSS, INTSECL.
% Algorithm:
% 1. Check boundary contour directions (area).
% For intersection and union make all
% counter-clockwise. For difference make the second
% contour clock-wise.
% 2. Calculate matrix of intersections (function ISINTPL).
% Quick exit if no intersections.
% 3. For intersecting segments calculate intersection
% coordinates (function INTSECL).
% 4. Sort intersections along both contours.
% 5. Calculate sign of cross-product between intersectiong
% segments. This will give which contour goes "in" and
% "out" at intersections.
%
% 6. Start with first intersection:
% Determine direction to go ("in" for intersection,
% "out" for union).
% Move until next intersection, switch polygons at each
% intersection until coming to the initial point.
% If not all intersections are encountered, the
% resulting polygon is disjoint. Separate output
% coordinates by NaN and repeat procedure until all
% intersections are counted.
% Default for flag
flag_dflt = 1; % 1- intersec., 2-union, 3 - diff.
% Handle input
if nargin==0, help polybool, return, end
if nargin < 4
error(' Not enough input arguments')
end
if nargin<5, flag = flag_dflt; end
x1 = x1(:); y1 = y1(:);
x2 = x2(:); y2 = y2(:);
l1 = length(x1);
l2 = length(x2);
% Check areas and reverse if negative
nn1 = area(x1,y1);
if nn1<0, x1 = flipud(x1); y1 = flipud(y1); end
nn2 = area(x2,y2);
if (nn2<0 & flag<3) | (nn2>0 & flag==3)
x2 = flipud(x2); y2 = flipud(y2);
end
% If both polygons are identical ........
if l1==l2
if all(x1==x2) & all(y1==y2)
if flag<3, xo = x1; yo = y1; ind = 1:l1;
else, xo = []; yo = []; ind = []; end
return
end
end
% Calculate matrix of intersections .....
[is,C] = isintpl(x1,y1,x2,y2);
is = any(any(C));
% Quick exit if no intersections ........
if ~is
if flag==1 % Intersection
xo=[]; yo = [];
elseif flag==2 % Union
xo = [x1; nan; x2];
yo = [y1; nan; y2];
elseif flag==3 % Difference
xo = x1; yo = y1;
end
return
end
% Mark intersections with unique numbers
i1 = find(C);
ni = length(i1);
C(i1) = 1:ni;
% Close polygon contours
x1 = [x1; x1(1)]; y1 = [y1; y1(1)];
x2 = [x2; x2(1)]; y2 = [y2; y2(1)];
l1 = length(x1); l2 = length(x2);
% Calculate intersections themselves
[i1,i2,id] = find(C);
xs1 = [x1(i1) x1(i1+1)]'; ys1 = [y1(i1) y1(i1+1)]';
xs2 = [x2(i2) x2(i2+1)]'; ys2 = [y2(i2) y2(i2+1)]';
% Call INTSECL ............................
[xint,yint] = intsecl(xs1,ys1,xs2,ys2);
% For sements belonging to the same line
% find interval of intersection ...........
ii = find(xint==inf);
if ~isempty(ii)
[is,inx] = interval(xs1(:,ii),xs2(:,ii));
[is,iny] = interval(ys1(:,ii),ys2(:,ii));
xint(ii) = mean(inx);
yint(ii) = mean(iny);
end
% Coordinate differences of intersecting segments
xs1 = diff(xs1); ys1 = diff(ys1);
xs2 = diff(xs2); ys2 = diff(ys2);
% Calculate cross-products
cp = xs1.*ys2-xs2.*ys1;
cp = cp>0;
if flag==2, cp=~cp; end % Reverse if union
cp(ii) = 2*ones(size(ii));
% Sort intersections along the contours
ind = (xint-x1(i1)').^2+(yint-y1(i1)').^2;
ind = ind./(xs1.^2+ys1.^2);
cnd = min(ind(ind>0));
ind = ind+i1'+i2'/(ni+1)*cnd*0;
[xo,ii] = sort(ind);
xs1 = id(ii);
[xo,ind] = sort(xs1);
ind = rem(ind,ni)+1;
xs1 = xs1(ind);
ind = (xint-x2(i2)').^2+(yint-y2(i2)').^2;
ind = ind./(xs2.^2+ys2.^2);
cnd = min(ind(ind>0));
[xo,ii] = sort(i2'+ind+i1'/(ni+1)*cnd*0);
xs2 = id(ii);
[xo,ind] = sort(xs2);
ind = rem(ind,ni)+1;
xs2 = xs2(ind);
% Combine coordinates in one vector
x1 = [x1; x2]; y1 = [y1; y2];
% Find max. possible length of a chain
xo = find(any(C'));
xo = diff([xo xo(1)+l1]);
mlen(1) = max(xo);
xo = find(any(C));
xo = diff([xo xo(1)+l2]);
mlen(2) = max(xo);
% Check if multiple intersections in one segment
xo = diff([i1 i2]);
is_1 = ~all(all(xo));
% Begin counting intersections *********************
% Initialization ..................
int = zeros(size(xint));
nn = 1; % First intersection
nn1 = i1(nn); nn2 = i2(nn);
b = cp(nn);
is2 = b==2;
xo = []; yo = []; ind = [];
closed = 0;
% Proceed until all intersections are counted
while ~closed % begin counting `````````````````````0
% If contour closes, find new starting point
if int(nn) & ~all(int)
ii = find(int);
C(id(ii)) = zeros(size(ii));
nn = min(find(~int)); % Next intersection
nn1 = i1(nn);
nn2 = i2(nn);
xo = [xo; nan]; % Separate by NaN
yo = [yo; nan];
ind = [ind; nan];
% Choose direction ......
b = cp(nn);
end
% Add current intersection ......
xo = [xo; xint(nn)];
yo = [yo; yint(nn)];
ind = [ind; 0];
int(nn) = 1;
closed = all(int);
% Find next segment
% Indices for next intersection
if ~b, nn = xs1(nn);
else, nn = xs2(nn);
end
if ~b, pt0 = nn1; else, pt0 = nn2; end
nn1 = i1(nn);
nn2 = i2(nn);
if b, pt = nn2; else, pt = nn1; end
if b, pt0 = pt0+l1; pt = pt+l1; end
ii = (pt0+1:pt);
% Go through the beginning ..............
cnd = pt<pt0 | (pt==pt0 & is_1 & flag>1);
if cnd
if ~b, ii = [pt0+1:l1 1:pt];
else, ii = [pt0+1:l1+l2 l1+1:pt];
end
end
len = length(ii);
cnd = b & len>mlen(2);
cnd = cnd | (~b & len>mlen(1));
if is2 | cnd, ii=[]; end
% Add new segment
xo = [xo; x1(ii)];
yo = [yo; y1(ii)];
ind = [ind; ii'];
% Switch direction
if cp(nn)==2, b = ~b; is2 = 1;
else, b = cp(nn); is2 = 0;
end
end % End while (all intersections) '''''''''''''''0
% Remove coincident successive points
ii = find(~diff(xo) & ~diff(yo));
xo(ii) = []; yo(ii) = []; ind(ii) = [];
% Remove points which are
ii = find(isnan(xo));
if ~isempty(ii)
i2 = ones(size(xo));
ii = [ii; length(xo)+1];
i1 = find(diff(ii)==3);
i1 = ii(i1);
i1 = [i1; i1+1; i1+2];
i2(i1) = zeros(size(i1));
i1 = find(diff(ii)==2);
i1 = ii(i1);
i1 = [i1; i1+1];
i2(i1) = zeros(size(i1));
xo = xo(i2); yo = yo(i2); ind = ind(i2);
end
end
function [xo,yo] = intsecpl(xv,yv,xl,yl,trace)
% INTSECPL Intersection of a polygon and a line.
% [XI,YI] = INTSECPL(XV,YV,XL,YL) calculates
% intersections XI, YI of a polygon with vertices XV,
% YV and a line specified by pairs of end coordinates
% XL = [XL0 XL1], YL = [YL0 YL1]. Line is assumed to
% continue beyond the range of end points.
% INTSECPL(XV,YV,[A B]) uses another specification for
% a line: Y = A*X+B.
%
% If a line does not intersect polygon, returns empty
% XI, YI.
% For convex polygon maximum number of intersections is
% 2, for non-convex polygons multiple intersections are
% possible.
%
% INTSECPL(XV,YV,XL,YL) by itself or
% [XI,YI] = INTSECPL(XV,YV,XL,YL,1) plots polygon,
% a line segment and intersection segment(s)
% (part(s) of the same line inside the polygon).
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/25/95, 08/27/95, 09/27/95
% Calls ISCROSS, INTSECL programs.
% Defaults and parameters .................................
tol = 1e-14; % Tolerance
marg = tol; % Margins for polygon frame
is_ab = 0; % Default A*X+B mode
% Handle input ............................................
if nargin==0, help intsecpl, return, end
if nargin < 3
error(' Not enough input arguments')
end
if nargin<5, trace = 0; end
if nargin==4 % Check if 4-th arg is trace
if max(size(yl))==1, trace = yl; is_ab = 1; end
end
if nargin==3, is_ab = 1; end
trace = trace | nargin<2;
if length(xv)~=length(yv)
error(' Vectors X, Y must have the same size')
end
% Auxillary ...........
xv = [xv(:); xv(1)];
yv = [yv(:); yv(1)];
ii = find(abs(diff(xv))<tol & abs(diff(yv))<tol);
xv(ii) = []; yv(ii) = [];
nv = length(xv);
ov = ones(nv-1,1);
% Polygon frame
lim = [min(xv)-marg max(xv)+marg min(yv)-marg max(yv)+marg];
% Estimate for diameter
d = sqrt((lim(2)-lim(1)).^2+(lim(4)-lim(3)).^2);
% Form line segment depending on how line is specified
if is_ab % A*X+B mode ...................
xl = xl(:);
if length(xl)<2
error(' Line is specified by at least two parameters')
end
a = xl(1); b = xl(2);
xl = [lim(1)-1 lim(2)+1];
yl = a*xl+b;
else % [X1 X2],[Y1 Y2] mode ..........
x0 = (xl(1)+xl(2))/2;
y0 = (yl(1)+yl(2))/2;
dx = xl(2)-x0;
dy = yl(2)-y0;
dl = max(abs([lim(1:2)-x0 lim(3:4)-y0]));
d = max(d,dl);
dl = sqrt(dx.^2+dy.^2);
dl = max(d,d/dl);
dx = dx*dl; dy = dy*dl;
xl = [x0-dx x0+dx];
yl = [y0-dy y0+dy];
end
% Find intersecting segments ..............................
is = iscross([xv(1:nv-1) xv(2:nv)]',[yv(1:nv-1) yv(2:nv)]',...
xl(ov,:)',yl(ov,:)',0);
% Quick exit if no intersections .........................
if ~any(is)
if trace
% Intersection with polygon frame
[xl,yl] = intsecpl(lim([1 2 2 1]),lim([3 3 4 4]),xl,yl);
%plot(xv,yv,xl,yl) % Plotting itself
end
xo = []; yo = [];
return
end
% For segments touching the line (is==.5) find whether pairs of
% successive segments are on the same side
ii = find(is==.5)';
if ii~=[]
xo = [ii-1 ii+1];
xo = xo+(nv-1)*(xo<1);
yo = iscross([xv(xo(:,1)) xv(xo(:,2))]',[yv(xo(:,1)) yv(xo(:,2))]',...
xl,yl,tol);
ii = ii(find(yo==1));
is(ii) = zeros(size(ii));
end
% Calculate intersection coordinates ......................
ii = find(is);
oi = ones(size(ii));
[xo,yo] = intsecl([xv(ii) xv(ii+1)]',[yv(ii) yv(ii+1)]',...
xl(oi,:)',yl(oi,:)');
dx = find(~finite(xo));
xo(dx) = []; yo(dx) = [];
ii(dx) = []; oi(dx) = [];
% Sort intersections along the line ..........
xo = xo(:); yo = yo(:);
if any(diff(xo))
[xo,ii] = sort(xo);
yo = yo(ii);
else
[yo,ii] = sort(yo);
xo = xo(ii);
end
% Exclude repeated points (degenerate cases)
% ///////// It seems that this is not needed, figure this
% later ///////////////////
if length(ii)>1 & 0 % Do not execute
xx = [xo yo];
yy = diff(xx)';
ii = [1 find(any(abs(yy)>tol))+1];
xo = xx(ii,1); yo = xx(ii,2);
oi = ones(size(xo));
end
% Plotting ................................................
if trace
oi(3:2:length(oi)) = oi(3:2:length(oi))+1;
oi = cumsum(oi);
len = max(oi);
xp = nan*ones(len,1); yp = xp;
xp(oi) = xo;
yp(oi) = yo;
% Intersection with polygon frame
[xl,yl] = intsecpl(lim([1 2 2 1]),lim([3 3 4 4]),xl,yl);
plot(xv,yv,xl,yl,xp,yp) % Plotting itself
end
end
function [is,S] = isintpl(x1,y1,x2,y2)
% ISINTPL Check for intersection of polygons.
% [IS,S] = ISINTPL(X1,Y1,X2,Y2) Accepts coordinates
% X1,Y1 and X2, Y2 of two polygons. Returns scalar
% IS equal to 1 if these polygons intersect each other
% and 0 if they do not.
% Also returns Boolean matrix S of the size length(X1)
% by length(X2) so that {ij} element of which is 1 if
% line segments i to i+1 of the first polygon and
% j to j+1 of the second polygon intersect each other,
% 0 if they don't and .5 if they "touch" each other.
% Copyright (c) 1995 by Kirill K. Pankratov,
% [email protected].
% 06/20/95, 08/25/95
% Handle input ...................................
if nargin==0, help isintpl, return, end
if nargin<4
error(' Not enough input arguments ')
end
% Make column vectors and check sizes ............
x1 = x1(:); y1 = y1(:);
x2 = x2(:); y2 = y2(:);
l1 = length(x1);
l2 = length(x2);
if length(y1)~=l1 | length(y2)~=l2
error('(X1,Y1) and (X2,Y2) must pair-wise have the same length.')
end
% Quick exit if empty
if l1<1 | l2<1, is = []; S = []; return, end
% Check if their ranges are intersecting .........
lim1 = [min(x1) max(x1)]';
lim2 = [min(x2) max(x2)]';
isx = interval(lim1,lim2); % X-ranges
lim1 = [min(y1) max(y1)]';
lim2 = [min(y2) max(y2)]';
isy = interval(lim1,lim2); % Y-ranges
is = isx & isy;
S = zeros(l2,l1);
if ~is, return, end % Early exit if disparate limits
% Indexing .......................................
[i11,i12] = meshgrid(1:l1,1:l2);
[i21,i22] = meshgrid([2:l1 1],[2:l2 1]);
i11 = i11(:); i12 = i12(:);
i21 = i21(:); i22 = i22(:);
% Calculate matrix of intersections ..............
S(:) = iscross([x1(i11) x1(i21)]',[y1(i11) y1(i21)]',...
[x2(i12) x2(i22)]',[y2(i12) y2(i22)]')';
S = S';
is = any(any(S));
end
function [xo,yo] = intsecl(x1,y1,x2,y2,tol)
% INTSECL Intersection coordinates of two line segments.
% [XI,YI] = INTSECL(X1,Y1,X2,Y2) where all 4
% arguments are 2 by N matrices with coordinates
% of ends of N pairs of line segments (so that
% the command such as PLOT(X1,Y1,X2,Y2) will plot
% these pairs of lines).
% Returns 1 by N vectors XI and YI consisting of
% coordinates of intersection points of each of N
% pairs of lines.
%
% Special cases:
% When a line segment is degenerate into a point
% and does not lie on line through the other segment
% of a pair returns XI=NaN while YI has the following
% values: 1 - when the first segment in a pair is
% degenerate, 2 - second segment, 0 - both segments
% are degenerate.
% When a pair of line segments is parallel, returns
% XI = Inf while YI is 1 for coincident lines,
% 0 - for parallel non-coincident ones.
% INTSECL(X1,Y1,X2,Y2,TOL) also specifies tolerance
% in detecting coincident points in different line
% segments.
% Copyright (c) 1995 by Kirill K. Pankratov
% [email protected]
% 04/15/94, 08/14/94, 05/10/95, 08/23/95
% Defaults and parameters .........................
tol_dflt = 0; % Tolerance for coincident points
is_chk = 1; % Check input arguments
% Handle input ....................................
if nargin==0, help intsecl, return, end
if nargin<4 % Check if all 4 entered
error(' Not enough input arguments')
end
if nargin<5, tol = tol_dflt; end
if tol < 0, is_chk = 0; tol = 0; end
% Check the format of arguments .......
if is_chk
[x1,y1,x2,y2] = linechk(x1,y1,x2,y2);
end
% Auxillary
o2 = ones(2,1);
i_pt1 = []; i_pt2 = []; i_pt12 = [];
% Make first points origins ...........
xo = x1(1,:);
yo = y1(1,:);
x2 = x2-xo(o2,:);
y2 = y2-yo(o2,:);
% Differences of first segments .......
a = x1(2,:)-x1(1,:);
b = y1(2,:)-y1(1,:);
s = sqrt(a.^2+b.^2); % Lengths of first segments
i_pt1 = find(~s);
s(i_pt1) = ones(size(i_pt1));
rr = rand(size(i_pt1));
a(i_pt1) = cos(rr);
b(i_pt1) = sin(rr);
% Normalize by length .................
a = a./s; b = b./s;
% Rotate coordinates of the second segment
tmp = x2.*a(o2,:)+y2.*b(o2,:);
y2 = -x2.*b(o2,:)+y2.*a(o2,:);
x2 = tmp;
% Calculate differences in second segments
s = x2(2,:)-x2(1,:);
tmp = y2(2,:)-y2(1,:);
cc = tmp(i_pt1);
% Find some degenerate cases .......................
% Find zeros in differences
izy2 = find(~tmp);
tmp(izy2) = ones(size(izy2));
% Find degenerate and parallel segments
bool = ~s(izy2);
i_par = izy2(~bool);
i_pt2 = izy2(bool);
bool = abs(y2(1,i_pt2))<=tol;
i_pt2_off = i_pt2(~bool);
i_pt2_on = i_pt2(bool);
if ~isempty(i_par)
bool = abs(y2(1,i_par))<=tol;
i_par_off = i_par(~bool);
i_par_on = i_par(bool);
end
% Calculate intercept with rotated x-axis ..........
tmp = s./tmp; % Slope
tmp = x2(1,:)-y2(1,:).*tmp;
% Rotate and translate back to original coordinates
xo = tmp.*a+xo;
yo = tmp.*b+yo;
% Mark special cases ...................................
% First segments are degenerate to points
if ~isempty(i_pt1)
bool = ~s(i_pt1) & ~cc;
i_pt12 = i_pt1(bool);
i_pt1 = i_pt1(~bool);
bool = abs(tmp(i_pt1))<=tol;
i_pt1_on = i_pt1(bool);
i_pt1_off = i_pt1(~bool);
xo(i_pt1_on) = x1(1,i_pt1_on);
yo(i_pt1_on) = y1(1,i_pt1_on);
oo = ones(size(i_pt1_off));
xo(i_pt1_off) = nan*oo;
yo(i_pt1_off) = oo;
end
% Second segments are degenerate to points ...
if ~isempty(i_pt2)
oo = ones(size(i_pt2_off));
xo(i_pt2_off) = nan*oo;
yo(i_pt2_off) = 2*oo;
end
% Both segments are degenerate ...............
if ~isempty(i_pt12)
bool = x1(i_pt12)==xo(i_pt12);
i_pt12_on = i_pt12(bool);
i_pt12_off = i_pt12(~bool);
xo(i_pt12_on) = x1(1,i_pt12_on);
yo(i_pt12_on) = y1(1,i_pt12_on);
oo = ones(size(i_pt12_off));
xo(i_pt12_off) = nan*oo;
yo(i_pt12_off) = 0*oo;
end
% Parallel segments .........................
if ~isempty(i_par)
oo = ones(size(i_par_on));
xo(i_par_on) = inf*oo;
yo(i_par_on) = oo;
oo = ones(size(i_par_off));
xo(i_par_off) = inf*oo;
yo(i_par_off) = 0*oo;
end
end
function [x1,y1,x2,y2] = linechk(x1,y1,x2,y2)
% LINECHK Input checking for line segments.
% Copyright (c) 1995 by Kirill K. Pankratov
% [email protected]
% 08/22/95,
% String for transposing
str = ['x1=x1'';'; 'y1=y1'';'; 'x2=x2'';'; 'y2=y2'';'];
% Sizes
sz = [size(x1); size(y1); size(x2); size(y2)]';
psz = prod(sz);
% Check x1, y1
if psz(1)~=psz(2)
error(' Arguments x1 and y1 must have the same size')
end
% Check x2, y2
if psz(3)~=psz(3)
error(' Arguments x2 and y2 must have the same size')
end
% Check if any arguments are less than 2 by 1
if any(max(sz)<2)
error(' Arguments x1, y1, x2, y2 must be at least 2 by 1 vectors')
end
% Check if no size is equal to 2
if any(all(sz~=2))
error(' Arguments x1, y1, x2, y2 must be 2 by 1 vectors')
end
% Find aruments to be transposed .............................
ii = find(sz(1,:)~=2);
for jj = 1:length(ii)
eval(str(ii(jj),:)); % Transpose if neccessary
end
sz(:,ii) = flipud(sz(:,ii));
% If vectors, extend to 2 by n matrices ......................
n = max(sz(2,:));
on = ones(1,n);
if sz(2,1)<n, x1 = x1(:,on); end
if sz(2,2)<n, y1 = y1(:,on); end
if sz(2,3)<n, x2 = x2(:,on); end
if sz(2,4)<n, y2 = y2(:,on); end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
edgelist.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/edgelist.m
| 4,737 |
utf_8
|
3d7876f26f51a03f4c49328237250877
|
%EDGELIST Return list of edge pixels for region
%
% EG = EDGELIST(IM, SEED) is a list of edge pixels (2xN) of a region in the
% image IM starting at edge coordinate SEED=[X,Y]. The edgelist has one column per
% edge point coordinate (x,y).
%
% EG = EDGELIST(IM, SEED, DIRECTION) as above, but the direction of edge
% following is specified. DIRECTION == 0 (default) means clockwise, non
% zero is counter-clockwise. Note that direction is with respect to y-axis
% upward, in matrix coordinate frame, not image frame.
%
% [EG,D] = EDGELIST(IM, SEED, DIRECTION) as above but also returns a vector
% of edge segment directions which have values 1 to 8 representing W SW S SE E
% NW N NW respectively.
%
% Notes::
% - Coordinates are given assuming the matrix is an image, so the indices are
% always in the form (x,y) or (column,row).
% - IM is a binary image where 0 is assumed to be background, non-zero
% is an object.
% - SEED must be a point on the edge of the region.
% - The seed point is always the first element of the returned edgelist.
% - 8-direction chain coding can give incorrect results when used with
% blobs founds using 4-way connectivty.
%
% Reference::
% - METHODS TO ESTIMATE AREAS AND PERIMETERS OF BLOB-LIKE OBJECTS: A COMPARISON
% Luren Yang, Fritz Albregtsen, Tor Lgnnestad and Per Grgttum
% IAPR Workshop on Machine Vision Applications Dec. 13-15, 1994, Kawasaki
%
% See also ILABEL.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [e,d] = edgelist(im, P, direction)
% deal with direction argument
if nargin == 2
direction = 0;
end
if direction == 0
neighbours = [1:8]; % neigbours in clockwise direction
else
neighbours = [8:-1:1]; % neigbours in counter-clockwise direction
end
P = P(:);
try
pix0 = im(P(2), P(1)); % color of pixel we start at
catch
error('TBCOMMON:edgelist', 'specified coordinate is not within image');
end
P0 = [];
% find an adjacent point outside the blob
Q = adjacent_point(im, P, pix0);
assert(~isempty(Q), 'TBCOMMON:edgelist', 'no neighbour outside the blob');
e = P; % initialize the edge list
dir = []; % initialize the direction list
% these are directions of 8-neighbours in a clockwise direction
dirs = [-1 0; -1 1; 0 1; 1 1; 1 0; 1 -1; 0 -1; -1 -1]';
while true
% find which direction is Q
dQ = Q - P;
for kq=1:8
if all(dQ == dirs(:,kq))
break;
end
end
% now test for directions relative to Q
for j=neighbours
% get index of neighbour's direction in range [1,8]
k = j + kq;
if k > 8
k = k - 8;
end
dir = [dir; k];
% compute coordinate of the k'th neighbour
Nk = P + dirs(:,k);
try
if im(Nk(2), Nk(1)) == pix0
% if this neighbour is in the blob it is the next edge pixel
P = Nk;
break;
end
end
Q = Nk; % the (k-1)th neighbour
end
% check if we are back where we started
if isempty(P0)
P0 = P; % make a note of where we started
else
if all(P == P0)
break;
end
end
% keep going, add P to the edgelist
e = [e P];
end
if nargout > 1
d = dir;
end
end
function P = adjacent_point(im, seed, pix0)
% find an adjacent point not in the region
dirs = [1 0; 0 1; -1 0; 0 -1; -1 1; -1 -1; 1 -1; 1 1];
for d=dirs'
P = seed(:) + d;
try
if im(P(2), P(1)) ~= pix0
return;
end
catch
% if we get an exception then by definition P is outside the region,
% since it's off the edge of the image
return;
end
end
P = [];
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
diff2.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/diff2.m
| 1,285 |
utf_8
|
d2018ea5bfa0dc51016c7c936df1b4d1
|
%DIFF2 First-order difference
%
% D = DIFF2(V) is the first-order difference (1xN) of the series data in
% vector V (1xN) and the first element is zero.
%
% D = DIFF2(A) is the first-order difference (MxN) of the series data in
% each row of the matrix A (MxN) and the first element in each row is zero.
%
% Notes::
% - Unlike the builtin function DIFF, the result of DIFF2 has the same
% number of columns as the input.
%
% See also DIFF.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function d = diff2(v)
[r,c] =size(v);
d = [zeros(1,c); diff(v)];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
rvccheck.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/rvccheck.m
| 2,868 |
utf_8
|
0a6c6a7bbb84d1de106fefff5323bd67
|
function rvccheck(verbose)
if nargin == 0
verbose = true;
end
% display current versions of MATLAB
year = version('-release');
if verbose
fprintf('You are using:\n - MATLAB release %s\n', year);
end
% check how old it is
today = datevec(now);
age = today(1) - str2num(year(1:4));
if age >= 2
fprintf(' ** this is at least %d years old, you may have issues\n', age);
end
% display versions of toolboxes (use unique RTB and MVTB functions)
p = getpath('lspb');
a = ver( p );
rtb = ~isempty(a);
p = getpath('idisp');
a = ver( p );
mvtb = ~isempty(a);
if verbose
if rtb
if findstr(p, 'Add-Ons')
where = 'mltbx install to Add-Ons';
else
if exist( fullfile(p, '.git'), 'dir' )
where = 'local (git clone) install';
else
where = 'local (zip) install';
end
end
fprintf(' - %s %s %s [%s]\n', a.Name, a.Version, a.Date, where);
end
if mvtb
if findstr(p, 'Add-Ons')
where = 'mltbx install to Add-Ons';
else
if exist( fullfile(p, '.git'), 'dir' )
where = 'local (git clone) install';
else
where = 'local (zip) install';
end
end
fprintf(' - %s %s %s [%s]\n', a.Name, a.Version, a.Date, where);
end
end
% check for shadowed files
k = 0;
if rtb
k = k + checkpath('rotx');
k = k + checkpath('roty');
k = k + checkpath('rotz');
k = k + checkpath('angdiff');
end
if mvtb
k = k + checkpath('im2col');
k = k + checkpath('col2im');
k = k + checkpath('angdiff');
end
if k > 0
fprintf('Some Toolbox files are "shadowed" and will cause problems with the use of this toolbox\n');
fprintf('Use path tool to move this Toolbox to the top of the path\n')
end
end
function k = checkpath(funcname)
funcpath = which(funcname); % find first instance in path
k = 0;
good = {'rvc', ...
'robotics-toolbox-matlab', 'Robotics Toolbox for MATLAB', ...
'machinevision-toolbox-matlab', 'Machine Vision Toolbox for MATLAB', ...
'smtb', 'spatial-math', 'Spatial Math Toolbox for MATLAB'};
if exist(funcname)
if all( cellfun(@(x) isempty(strfind(funcpath, x)), good) )
fprintf('** Toolbox function %s is shadowed by %s\n', funcname, which(funcname) );
k = 1;
end
end
end
function p = getpath(funcname)
funcpath = which(funcname);
k = strfind( funcpath, [filesep funcname]);
p = funcpath(1:k-1);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
filt1d.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/filt1d.m
| 2,048 |
utf_8
|
bc8104a2b86eb158bb26e4ed77ac7e0f
|
%FILT1D 1-dimensional rank filter
%
% Y = FILT1D(X, OPTIONS) is the minimum, maximum or median value (1xN) of the
% vector X (1xN) compute over an odd length sliding window.
%
% Options::
% 'max' Compute maximum value over the window (default)
% 'min' Compute minimum value over the window
% 'median' Compute minimum value over the window
% 'width',W Width of the window (default 5)
%
% Notes::
% - If the window width is even, it is incremented by one.
% - The first and last elements of X are replicated so the output vector is the
% same length as the input vector.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
% Copyright (c) Peter Corke 6/93
% vectorized version 8/95 pic
function m = filt1d(s, varargin)
opt.width = 5;
opt.op = {'max', 'min', 'median'};
opt = tb_optparse(opt, varargin);
% enforce a column vector
s = s(:)';
% enforce odd window length
w2 = floor(opt.width/2);
w = 2*w2 + 1;
n = length(s);
m = zeros(w,n+w-1);
s0 = s(1); sl = s(n);
% replicate first and last elements
for i=0:(w-1),
m(i+1,:) = [s0*ones(1,i) s sl*ones(1,w-i-1)];
end
switch (opt.op)
case 'max'
m = max(m);
case 'min'
m = min(m);
case 'median'
m = median(m);
end
m = m(w2+1:w2+n);
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
yaxis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/yaxis.m
| 1,310 |
utf_8
|
0db9a465f805810b37b09d08336176c6
|
%YAYIS set Y-axis scaling
%
% YAXIS(MAX) set y-axis scaling from 0 to MAX.
%
% YAXIS(MIN, MAX) set y-axis scaling from MIN to MAX.
%
% YAXIS([MIN MAX]) as above.
%
% YAXIS restore automatic scaling for y-axis.
%
% See also YAXIS.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function yaxis(a1, a2)
if nargin == 0,
set(gca, 'YLimMode', 'auto')
return
elseif nargin == 1,
if length(a1) == 1,
mn = 0;
mx = a1;
elseif length(a1) == 2,
mn = a1(1);
mx = a1(2);
end
elseif nargin == 2,
mn = a1;
mx = a2;
end
set(gca, 'YLimMode', 'manual', 'YLim', [mn mx])
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
colorname.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/colorname.m
| 5,777 |
utf_8
|
c7a519e639e1ff6b85516095712405d9
|
%COLORNAME Map between color names and RGB values
%
% RGB = COLORNAME(NAME) is the RGB-tristimulus value (1x3) corresponding to
% the color specified by the string NAME. If RGB is a cell-array (1xN) of
% names then RGB is a matrix (Nx3) with each row being the corresponding
% tristimulus.
%
% XYZ = COLORNAME(NAME, 'xyz') as above but the XYZ-tristimulus value
% corresponding to the color specified by the string NAME.
%
% XY = COLORNAME(NAME, 'xy') as above but the xy-chromaticity coordinates
% corresponding to the color specified by the string NAME.
%
% NAME = COLORNAME(RGB) is a string giving the name of the color that is
% closest (Euclidean) to the given RGB-tristimulus value (1x3). If RGB is
% a matrix (Nx3) then return a cell-array (1xN) of color names.
%
% NAME = COLORNAME(XYZ, 'xyz') as above but the color is the closest (Euclidean)
% to the given XYZ-tristimulus value.
%
% NAME = COLORNAME(XYZ, 'xy') as above but the color is the closest (Euclidean)
% to the given xy-chromaticity value with assumed Y=1.
%
% Notes::
% - Color name may contain a wildcard, eg. "?burnt"
% - Based on the standard X11 color database rgb.txt.
% - Tristimulus values are in the range 0 to 1
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function out = colorname(a, varargin)
opt.space = {'rgb', 'xyz', 'xy', 'lab', 'ab'};
opt = tb_optparse(opt, varargin);
persistent rgbtable;
% ensure that the database is loaded
if isempty(rgbtable)
% load mapping table from file
fprintf('loading rgb.txt\n');
f = fopen('data/rgb.txt', 'r');
k = 0;
rgb = [];
names = {};
xy = [];
while ~feof(f)
line = fgets(f);
if line(1) == '#',
continue;
end
[A,count,errm,next] = sscanf(line, '%d %d %d');
if count == 3
k = k + 1;
rgb(k,:) = A' / 255.0;
names{k} = lower( strtrim(line(next:end)) );
end
end
s.rgb = rgb;
s.names = names;
rgbtable = s;
end
if isstr(a)
% map name to rgb/xy
if a(1) == '?'
% just do a wildcard lookup
out = namelookup(rgbtable, a(2:end), opt);
else
out = name2color(rgbtable, a, opt);
end
elseif iscell(a)
% map multiple names to colorspace
out = [];
for name=a
color = name2color(rgbtable, name{1}, opt);
if isempty(color)
warning('Color %s not found', name{1});
end
out = [out; color];
end
else
% map values to strings
out = {};
switch opt.space
case {'rgb', 'xyz', 'lab'}
assert(numcols(a) == 3, 'Color value must have 3 elements');
% convert reference colors to input color space
table = colorspace(['RGB->' opt.space], rgbtable.rgb);
for color=a'
d = distance(color, table');
[~,k] = min(d);
out = [out rgbtable.names{k}];
end
case {'xy', 'ab'}
assert(numcols(a) == 2, 'Color value must have 2 elements');
% convert reference colors to input color space
switch opt.space
case 'xy'
table = colorspace('RGB->XYZ', rgbtable.rgb);
table = table(:,1:2) ./ (sum(table,2)*[1 1]);
case 'ab'
table = colorspace('RGB->Lab', rgbtable.rgb);
table = table(:,2:3);
end
for color=a'
d = distance(color, table');
[~,k] = min(d);
out = [out rgbtable.names{k}];
end
end
if length(out) == 1
out = out{1};
end
end
end
function r = namelookup(table, s, opt)
s = lower(s); % all matching done in lower case
r = {};
count = 1;
for k=1:length(table.names),
if ~isempty( findstr(table.names{k}, s) )
r{count} = table.names{k};
count = count + 1;
end
end
end
function out = name2color(table, s, opt)
s = lower(s); % all matching done in lower case
for k=1:length(table.names),
if strcmp(s, table.names(k)),
rgb = table.rgb(k,:);
switch opt.space
case {'rgb', 'xyz', 'lab'}
out = colorspace(['RGB->' opt.space], rgb);
case 'xy'
XYZ = colorspace('RGB->XYZ', rgb);
out = tristim2cc(XYZ);
case 'ab';
Lab = colorspace('RGB->Lab', rgb);
out = Lab(2:3);
end
return;
end
end
out = [];
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
polydiff.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/polydiff.m
| 1,119 |
utf_8
|
3358d9e6a460f1a769fc034f0a00897f
|
%POLYDIFF Differentiate a polynomial
%
% PD = POLYDIFF(P) is a vector of coefficients of a polynomial (1xN-1) which is the
% derivative of the polynomial P (1xN).
%
% p = [3 2 -1];
% polydiff(p)
% ans =
% 6 2
%
% See also POLYVAL.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function pd = polydiff(p)
n = length(p)-1;
pd = [n:-1:1] .* p(1:n);
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
randinit.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/randinit.m
| 978 |
utf_8
|
118aaf915c94e7df6953a8a937ba88f8
|
%RANDINIT Reset random number generator
%
% RANDINIT resets the defaul random number stream.
%
% See also RandStream.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function randinit(seed)
stream = RandStream.getGlobalStream;
stream.reset()
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
xaxis.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/xaxis.m
| 1,832 |
utf_8
|
aeb2d1ed8dcaf8d74d9cfff5546879cf
|
%XAXIS Set X-axis scaling
%
% XAXIS(MAX) set x-axis scaling from 0 to MAX.
%
% XAXIS(MIN, MAX) set x-axis scaling from MIN to MAX.
%
% XAXIS([MIN MAX]) as above.
%
% XAXIS restore automatic scaling for x-axis.
%
% See also YAXIS.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function xaxis(varargin)
opt.all = false;
[opt,args] = tb_optparse(opt, varargin);
if length(args) == 0
[x,y] = ginput(2);
mn = x(1);
mx = x(2);
elseif length(args) == 1
if length(args{1}) == 1
mn = 0;
mx = args{1};
elseif length(args{1}) == 2
mn = args{1}(1);
mx = args{1}(2);
end
elseif length(args) == 2
mn = args{1};
mx = args{2};
end
if opt.all
for a=get(gcf,'Children')',
if strcmp(get(a, 'Type'), 'axes') == 1,
set(a, 'XLimMode', 'manual', 'XLim', [mn mx])
set(a, 'YLimMode', 'auto')
end
end
else
set(gca, 'XLimMode', 'manual', 'XLim', [mn mx])
set(gca, 'YLimMode', 'auto')
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
dockfigs.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/dockfigs.m
| 1,180 |
utf_8
|
55bce19340194193b60ce661b658894a
|
%DOCKFIGS Control figure docking in the GUI
%
% dockfigs causes all new figures to be docked into the GUI
%
% dockfigs(1) as above.
%
% dockfigs(0) causes all new figures to be undocked from the GUI
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function dockfigs(arg)
if nargin == 0
arg = 1;
end
if arg
set(0, 'DefaultFigureWindowStyle', 'docked')
else
set(0, 'DefaultFigureWindowStyle', 'normal')
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
usefig.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/usefig.m
| 348 |
utf_8
|
c47f23a7a2dcad028e840e34500f5959
|
%USEFIG Named figure windows
%
% usefig('Foo') makes figure 'Foo' the current figure, if it doesn't
% exist create it.
%
% h = usefig('Foo') as above, but returns the figure handle
function H = usefig(name)
h = findobj('Name', name);
if isempty(h),
h = figure;
set(h, 'Name', name);
else
figure(h);
end
if nargout > 0,
H = h;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
circle.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/circle.m
| 2,075 |
utf_8
|
6a9dea8240a3f9b5329ef331aef61802
|
%CIRCLE Compute points on a circle
%
% CIRCLE(C, R, OPTIONS) plots a circle centred at C (1x2) with radius R on the current
% axes.
%
% X = CIRCLE(C, R, OPTIONS) is a matrix (2xN) whose columns define the
% coordinates [x,y] of points around the circumferance of a circle
% centred at C (1x2) and of radius R.
%
% C is normally 2x1 but if 3x1 then the circle is embedded in 3D, and X is Nx3,
% but the circle is always in the xy-plane with a z-coordinate of C(3).
%
% Options::
% 'n',N Specify the number of points (default 50)
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function out = circle(centre, rad, varargin)
opt.n = 50;
[opt,arglist] = tb_optparse(opt, varargin);
% compute points on circumference
th = [0:opt.n-1]'/ opt.n*2*pi;
x = rad*cos(th) + centre(1);
y = rad*sin(th) + centre(2);
% add extra row if z-coordinate is specified, but circle is always in xy plane
if length(centre) > 2
z = ones(size(x))*centre(3);
p = [x y z]';
else
p = [x y]';
end
if nargout > 0
% return now
out = p;
return;
else
% else plot the circle
p = [p p(:,1)]; % make it close
if numrows(p) > 2
plot3(p(1,:), p(2,:), p(3,:), arglist{:});
else
plot(p(1,:), p(2,:), arglist{:});
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
stlRead.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/stlRead.m
| 11,483 |
utf_8
|
152f25d793763b55b15b646992987e02
|
%STLREAD reads any STL file not depending on its format
%
% [v, f, n, name] = stlRead(fileName) reads the STL format file (ASCII or
% binary) and returns vertices V, faces F, normals N and NAME is the name
% of the STL object (NOT the name of the STL file).
%
% Authors::
% - from MATLAB File Exchange by Pau Mico, https://au.mathworks.com/matlabcentral/fileexchange/51200-stltools
% - Copyright (c) 2015, Pau Mico
% - Copyright (c) 2013, Adam H. Aitkenhead
% - Copyright (c) 2011, Francis Esmonde-White
%
% stlGetFormat: identifies the format of the STL file and returns 'binary'
% or 'ascii'. This file is inspired in the 'READ-stl' file written and
% published by Adam H. Aitkenhead
% (http://www.mathworks.com/matlabcentral/fileexchange/27390-mesh-voxelisation).
% Copyright (c) 2013, Adam H. Aitkenhead.
%
% stlReadAscii: reads an STL file written in ascii format. This file is
% inspired in the 'READ-stl' file written and published by Adam H.
% Aitkenhead
% (http://www.mathworks.com/matlabcentral/fileexchange/27390-mesh-voxelisation).
% Copyright (c) 2013, Adam H. Aitkenhead
%
% stlReadBinary: reads an STL file written in binary format. This file
% is inspired in the 'READ-stl' file written and published by Adam H.
% Aitkenhead
% (http://www.mathworks.com/matlabcentral/fileexchange/27390-mesh-voxelisation).
% Copyright (c) 2013, Adam H. Aitkenhead stlRead: uses 'stlGetFormat',
%
% 'stlReadAscii' and 'stlReadBinary' to make STL reading independent of the
% format of the file
%
% stlSlimVerts: finds and removes duplicated vertices. This function is
% written and published by Francis Esmonde-White as PATCHSLIM
% (http://www.mathworks.com/matlabcentral/fileexchange/29986-patch-slim--patchslim-m-).
% Copyright (c) 2011, Francis Esmonde-White.%
%
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
% * Neither the name of the The MathWorks, Inc. nor the names
% of its contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
% * Neither the name of the The Christie NHS Foundation Trust nor the names
% of its contributors may be used to endorse or promote products derived
% from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function [v, f, n, name] = stlRead(fileName)
%STLREAD reads any STL file not depending on its format
%V are the vertices
%F are the faces
%N are the normals
%NAME is the name of the STL object (NOT the name of the STL file)
format = stlGetFormat(fileName);
if strcmp(format,'ascii')
[v,f,n,name] = stlReadAscii(fileName);
elseif strcmp(format,'binary')
[v,f,n,name] = stlReadBinary(fileName);
end
end
function format = stlGetFormat(fileName)
%STLGETFORMAT identifies the format of the STL file and returns 'binary' or
%'ascii'
fid = fopen(fileName);
assert(fid > 0, 'Cant find file %s', fileName);
% Check the file size first, since binary files MUST have a size of 84+(50*n)
fseek(fid,0,1); % Go to the end of the file
fidSIZE = ftell(fid); % Check the size of the file
if rem(fidSIZE-84,50) > 0
format = 'ascii';
else
% Files with a size of 84+(50*n), might be either ascii or binary...
% Read first 80 characters of the file.
% For an ASCII file, the data should begin immediately (give or take a few
% blank lines or spaces) and the first word must be 'solid'.
% For a binary file, the first 80 characters contains the header.
% It is bad practice to begin the header of a binary file with the word
% 'solid', so it can be used to identify whether the file is ASCII or
% binary.
fseek(fid,0,-1); % go to the beginning of the file
header = strtrim(char(fread(fid,80,'uchar')')); % trim leading and trailing spaces
isSolid = strcmp(header(1:min(5,length(header))),'solid'); % take first 5 char
fseek(fid,-80,1); % go to the end of the file minus 80 characters
tail = char(fread(fid,80,'uchar')');
isEndSolid = findstr(tail,'endsolid');
% Double check by reading the last 80 characters of the file.
% For an ASCII file, the data should end (give or take a few
% blank lines or spaces) with 'endsolid <object_name>'.
% If the last 80 characters contains the word 'endsolid' then this
% confirms that the file is indeed ASCII.
if isSolid & isEndSolid
format = 'ascii';
else
format = 'binary';
end
end
fclose(fid);
end
function [v, f, n, name] = stlReadAscii(fileName)
%STLREADASCII reads a STL file written in ASCII format
%V are the vertices
%F are the faces
%N are the normals
%NAME is the name of the STL object (NOT the name of the STL file)
%======================
% STL ascii file format
%======================
% ASCII STL files have the following structure. Technically each facet
% could be any 2D shape, but in practice only triangular facets tend to be
% used. The present code ONLY works for meshes composed of triangular
% facets.
%
% solid object_name
% facet normal x y z
% outer loop
% vertex x y z
% vertex x y z
% vertex x y z
% endloop
% endfacet
%
% <Repeat for all facets...>
%
% endsolid object_name
fid = fopen(fileName);
cellcontent = textscan(fid,'%s','delimiter','\n'); % read all the file and put content in cells
content = cellcontent{:}(logical(~strcmp(cellcontent{:},''))); % remove all blank lines
fclose(fid);
% read the STL name
line1 = char(content(1));
if (size(line1,2) >= 7)
name = line1(7:end);
else
name = 'Unnamed Object';
end
% read the vector normals
normals = char(content(logical(strncmp(content,'facet normal',12))));
n = str2num(normals(:,13:end));
% read the vertex coordinates (vertices)
vertices = char(content(logical(strncmp(content,'vertex',6))));
v = str2num(vertices(:,7:end));
nvert = length(vertices); % number of vertices
nfaces = sum(strcmp(content,'endfacet')); % number of faces
if (nvert == 3*nfaces)
f = reshape(1:nvert,[3 nfaces])'; % create faces
end
% slim the file (delete duplicated vertices)
[v,f] = stlSlimVerts(v,f);
end
function [v, f, n, name] = stlReadBinary(fileName)
%STLREADBINARY reads a STL file written in BINARY format
%V are the vertices
%F are the faces
%N are the normals
%NAME is the name of the STL object (NOT the name of the STL file)
%=======================
% STL binary file format
%=======================
% Binary STL files have an 84 byte header followed by 50-byte records, each
% describing a single facet of the mesh. Technically each facet could be
% any 2D shape, but that would screw up the 50-byte-per-facet structure, so
% in practice only triangular facets are used. The present code ONLY works
% for meshes composed of triangular facets.
%
% HEADER:
% 80 bytes: Header text
% 4 bytes: (int) The number of facets in the STL mesh
%
% DATA:
% 4 bytes: (float) normal x
% 4 bytes: (float) normal y
% 4 bytes: (float) normal z
% 4 bytes: (float) vertex1 x
% 4 bytes: (float) vertex1 y
% 4 bytes: (float) vertex1 z
% 4 bytes: (float) vertex2 x
% 4 bytes: (float) vertex2 y
% 4 bytes: (float) vertex2 z
% 4 bytes: (float) vertex3 x
% 4 bytes: (float) vertex3 y
% 4 bytes: (float) vertex3 z
% 2 bytes: Padding to make the data for each facet 50-bytes in length
% ...and repeat for next facet...
fid = fopen(fileName);
header = fread(fid,80,'int8'); % reading header's 80 bytes
name = deblank(native2unicode(header,'ascii')');
if isempty(name)
name = 'Unnamed Object'; % no object name in binary files!
end
nfaces = fread(fid,1,'int32'); % reading the number of facets in the stl file (next 4 byters)
nvert = 3*nfaces; % number of vertices
% reserve memory for vectors (increase the processing speed)
n = zeros(nfaces,3);
v = zeros(nvert,3);
f = zeros(nfaces,3);
for i = 1 : nfaces % read the data for each facet
tmp = fread(fid,3*4,'float'); % read coordinates
n(i,:) = tmp(1:3); % x,y,z components of the facet's normal vector
v(3*i-2,:) = tmp(4:6); % x,y,z coordinates of vertex 1
v(3*i-1,:) = tmp(7:9); % x,y,z coordinates of vertex 2
v(3*i,:) = tmp(10:12); % x,y,z coordinates of vertex 3
f(i,:) = [3*i-2 3*i-1 3*i]; % face
fread(fid,1,'int16'); % Move to the start of the next facet (2 bytes of padding)
end
fclose(fid);
% slim the file (delete duplicated vertices)
[v,f] = stlSlimVerts(v,f);
end
function [vnew, fnew]= stlSlimVerts(v, f)
% PATCHSLIM removes duplicate vertices in surface meshes.
%
% This function finds and removes duplicate vertices.
%
% USAGE: [v, f]=patchslim(v, f)
%
% Where v is the vertex list and f is the face list specifying vertex
% connectivity.
%
% v contains the vertices for all triangles [3*n x 3].
% f contains the vertex lists defining each triangle face [n x 3].
%
% This will reduce the size of typical v matrix by about a factor of 6.
%
% For more information see:
% http://www.esmonde-white.com/home/diversions/matlab-program-for-loading-stl-files
%
% Francis Esmonde-White, May 2010
if ~exist('v','var')
error('The vertex list (v) must be specified.');
end
if ~exist('f','var')
error('The vertex connectivity of the triangle faces (f) must be specified.');
end
[vnew, indexm, indexn] = unique(v, 'rows');
fnew = indexn(f);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
pickregion.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/pickregion.m
| 3,137 |
utf_8
|
f282eb7d77ff4e8df065d73a0c7d9e37
|
%PICKREGION Pick a rectangular region of a figure using mouse
%
% [p1,p2] = PICKREGION() initiates a rubberband box at the current click point
% and animates it so long as the mouse button remains down. Returns the first
% and last coordinates in axis units.
%
% Options::
% 'axis',A The axis to select from (default current axis)
% 'ls',LS Line style for foreground line (default ':y');
% 'bg'LS, Line style for background line (default '-k');
% 'width',W Line width (default 2)
% 'pressed' Don't wait for first button press, use current position
%
% Notes::
% - Effectively a replacement for the builtin rbbox function which draws the box in
% the wrong location on my Mac's external monitor.
%
% Author::
% Based on rubberband box from MATLAB Central written/Edited by Bob Hamans
% ([email protected]) 02-04-2003, in turn based on an idea of
% Sandra Martinka's Rubberline.
function [p1,p2]=pickregion(varargin)
% handle options
opt.axis = gca;
opt.ls = ':y';
opt.bg = '-k';
opt.width = 2;
opt.pressed = false;
opt = tb_optparse(opt, varargin);
h = opt.axis;
% Get current user data
cudata=get(gcf,'UserData');
hold on;
% Wait for left mouse button to be pressed
if ~opt.pressed
k=waitforbuttonpress;
end
% get current point
p1=get(h,'CurrentPoint'); %get starting point
p1=p1(1,1:2); %extract x and y
% create 2 overlaid lines for contrast:
% black solid
% color dotted
lh1 = plot(p1(1),p1(2),opt.bg, 'LineWidth', opt.width); %plot starting point
lh2 = plot(p1(1), p1(2), opt.ls, 'LineWidth', opt.width);
% Save current point and handles in user data
udata.p1=p1;
udata.h=h;
udata.lh1=lh1;
udata.lh2=lh2;
% Set handlers for mouse up and mouse motion
udata.wbupOld = get(gcf, 'WindowButtonUp');
udata.wbmfOld = get(gcf, 'WindowButtonMotionFcn');
set(gcf, ...
'WindowButtonMotionFcn', @(src,event) wbmf(src,udata), ...
'WindowButtonUp', @(src,event) wbup(src,udata), ...
'DoubleBuffer','on');
% Wait until the lines have been destroyed
waitfor(lh1);
% Get data for the end point
p2=get(h,'Currentpoint'); %get end point
p2=p2(1,1:2); %extract x and y
% Remove the mouse event handlers and restore user data
set(gcf,'UserData',cudata,'DoubleBuffer','off');
end
function wbmf(src, ud) %window motion callback function
% get current coordinates
P = get(ud.h,'CurrentPoint');
P = P(1,1:2);
% Use 5 point to draw a rectangular rubberband box
xdata = [P(1),P(1),ud.p1(1),ud.p1(1),P(1)];
ydata = [P(2),ud.p1(2),ud.p1(2),P(2),P(2)];
% draw the two lines
set(ud.lh1,'XData', xdata,'YData', ydata);
set(ud.lh2,'XData', xdata,'YData', ydata);
end
function wbup(src, ud)
% remove motion handler
set(gcf, 'WindowButtonMotionFcn', ud.wbmfOld);
set(gcf, 'WindowButtonUpFcn', ud.wbupOld);
% delete the lines
delete(ud.lh2);
delete(ud.lh1);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mplot.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/mplot.m
| 7,123 |
utf_8
|
1b7af413e24c0753dcef8934378925e1
|
%MPLOT Plot time-series data
%
% A convenience function for plotting time-series data held in a matrix.
% Each row is a timestep and the first column is time.
%
% MPLOT(Y, OPTIONS) plots the time series data Y(NxM) in multiple
% subplots. The first column is assumed to be time, so M-1 plots are
% produced.
%
% MPLOT(T, Y, OPTIONS) plots the time series data Y(NxM) in multiple
% subplots. Time is provided explicitly as the first argument so M plots
% are produced.
%
% MPLOT(S, OPTIONS) as above but S is a structure. Each field is assumed
% to be a time series which is plotted. Time is taken from the field
% called 't'. Plots are labelled according to the name of the
% corresponding field.
%
% MPLOT(W, OPTIONS) as above but W is a structure created by the Simulink
% write to workspace block where the save format is set to "Structure
% with time". Each field in the signals substructure is plotted.
%
% MPLOT(R, OPTIONS) as above but R is a Simulink.SimulationOutput object
% returned by the Simulink sim() function.
%
% Options::
% 'col',C Select columns to plot, a boolean of length M-1 or a list of
% column indices in the range 1 to M-1
% 'label',L Label the axes according to the cell array of strings L
% 'date' Add a datestamp in the top right corner
%
% Notes::
% - In all cases a simple GUI is created which is invoked by a right
% clicking on one of the plotted lines. The supported options are:
% - zoom in the x-direction
% - shift view to the left or right
% - unzoom
% - show data points
%
% See also plot2, plotp.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function mplot(varargin)
opt.label = [];
opt.date = false;
opt.cols = [];
[opt,args] = tb_optparse(opt, varargin);
if isstruct(args{1})
s = args{1};
if isfield(s, 'signals'),
% To Workspace type structure
matplot(s.time, s.signals.values, opt);
if isfield(s, 'blockName'),
title(s.blockName)
end
else
% retriever type structure
structplot(args{:})
end
elseif isa(args{1}, 'Simulink.SimulationOutput')
% Simulink output object
s = args{1};
matplot(s.find('tout'), s.find('yout'), opt);
if isfield(s, 'blockName'),
title(s.blockName)
end
else
matplot(args{:}, opt)
end
if opt.date
datestamp
end
if ~isempty(opt.label)
mlabel(opt.label);
end
mtools
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function structplot(s)
if ~isfield(s, 't') & ~isfield(s, 'time')
error('structure must include a time element t')
end
if isfield(s, 't')
t = s.t;
elseif isfield(s, 'time'),
t = s.time;
end
f = fieldnames(s);
n = length(f) - 1;
sp = n*100 + 11;
tmax = max(t);
i = 1;
for ff = f'
fieldnam = char(ff);
switch fieldnam,
case {'t', 'time'},
otherwise,
h(i) = subplot(sp);
plot(t, getfield(s, fieldnam));
set(h(i), 'UserData', i);
v = axis;
v(2) = tmax;
axis(v);
grid
xlabel('Time');
ylabel(fieldnam);
sp = sp +1;
i = i + 1;
end
end
axes(h(1));
figure(gcf)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% legacy function for matrix input data, old mplot() compatible
function matplot(a1, a2, a3)
[r,c]=size(a1);
if nargin == 2
% [t y1 y2 ... yN]
t = a1(:,1);
y = a1(:,2:c);
cols = 1:(c-1);
gain = 1;
opt = a2;
elseif nargin == 3
if isvector(a1) & ismatrix(a2)
% t, [y1 y2 .. yN]
t = a1(:);
cols = 1:numcols(a2);
y = a2;
elseif isempty(a1) & ismatrix(a2)
% [], [y1 y2 .. yN]
cols = 1:numcols(a2);
y = a2;
t = [1:numrows(y)]';
end
opt = a3;
end
t = t(:);
[r,c]=size(y);
sp = c*100 + 10;
tmax = max(t);
for i=1:c
if (sp+i) == 111,
clf
plot(t,y(:,i));
h(i) = gca;
else
h(i) = subplot(sp+i);
plot(t,y(:,i));
end
set(h(i), 'UserData', i);
set(h(i), 'Tag', 'mplot');
v = axis;
v(2) = tmax;
axis(v);
grid
xlabel('Time');
lab = sprintf('Y(%2d)', cols(i));
ylabel(lab);
end
axes(h(1));
figure(gcf)
end
function mlabel(lab, varargin)
% find all child axes (subplots)
h = findobj(gcf, 'Type', 'axes');
for i=1:length(h),
if strcmp( get(h(i), 'visible'), 'on'),
axes(h(i))
% get subplot number from user data (I don't know who
% sets this but its very useful)
sp = get(h(i), 'UserData');
if sp == 1,
topplot = sp;
end
ylabel(lab{sp}, varargin{:});
end
end
if 0
if nargin > 1,
axes(h(topplot)); % top plot
title(tit);
end
end
end
function mtools
h = uicontextmenu;
uimenu(h, 'Label', 'X zoom', 'CallBack', 'xaxis');
uimenu(h, 'Label', '-->', 'CallBack', 'xscroll(0.5)');
uimenu(h, 'Label', '<--', 'CallBack', 'xscroll(-0.5)');
uimenu(h, 'Label', 'CrossHairs', 'CallBack', 'crosshair');
uimenu(h, 'Label', 'X UNzoom', 'CallBack', 'unzoom');
uimenu(h, 'Label', 'Pick delta', 'CallBack', 'fprintf(''%f %f\n'', diff(ginput(2)))');
uimenu(h, 'Label', 'Line fit', 'CallBack', 'ilinefit');
uimenu(h, 'Label', 'Show points', 'CallBack', 'showpoints(gca)');
uimenu(h, 'Label', 'Apply X zoom to all', 'CallBack', 'xaxisall');
for c=get(gcf, 'Children')',
set(c, 'UIContextMenu', h);
l = get(c, 'Children');
end
axes('pos', [0 0 1 0.05], 'visible', 'off')
end
function datestamp
uicontrol('Style', 'text', ...
'String', date, ...
'Units', 'Normalized', ...
'HorizontalAlignment', 'Right', ...
'BackgroundColor', 'w', ...
'Position', [.8 0.97 .2 .03]);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
runscript.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/runscript.m
| 8,329 |
utf_8
|
1a60ae9f2904735bde6dca3af52d4e0a
|
%RUNSCRIPT Run an M-file in interactive fashion
%
% RUNSCRIPT(SCRIPT, OPTIONS) runs the M-file SCRIPT and pauses after every
% executable line in the file until a key is pressed. Comment lines are shown
% without any delay between lines.
%
% Options::
% 'delay',D Don't wait for keypress, just delay of D seconds (default 0)
% 'cdelay',D Pause of D seconds after each comment line (default 0)
% 'begin' Start executing the file after the comment line %%begin (default false)
% 'dock' Cause the figures to be docked when created
% 'path',P Look for the file SCRIPT in the folder P (default .)
% 'dock' Dock figures within GUI
% 'nocolor' Don't use cprintf to print lines in color (comments black, code blue)
%
% Notes::
% - If no file extension is given in SCRIPT, .m is assumed.
% - A copyright text block will be skipped and not displayed.
% - If cprintf exists and 'nocolor' is not given then lines are displayed
% in color.
% - Leading comment characters are not displayed.
% - If the executable statement has comments immediately afterward (no blank lines)
% then the pause occurs after those comments are displayed.
% - A simple '-' prompt indicates when the script is paused, hit enter.
% - If the function cprintf() is in your path, the display is more
% colorful. You can get this file from MATLAB File Exchange.
% - If the file has a lot of boilerplate, you can skip over and not display
% it by giving the 'begin' option which searchers for the first line
% starting with %%begin and commences execution at the line after that.
%
% See also eval.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function runscript(fname, varargin)
opt.path = [];
opt.delay = [];
opt.begin = false;
opt.cdelay = 0;
opt.dock = false;
opt.color = true;
opt = tb_optparse(opt, varargin);
if ~exist('cprintf')
opt.color = false;
end
close all
curDir = pwd();
prevDockStatus = get(0,'DefaultFigureWindowStyle');
if opt.dock
set(0,'DefaultFigureWindowStyle','docked');
else
set(0,'DefaultFigureWindowStyle','normal');
end
if ~isempty(opt.path)
fname = fullfile(opt.path, [fname '.m']);
else
fname = [fname '.m'];
end
fp = fopen(fname, 'r');
clc
fprintf('--- runscript <-- %s\n', fname);
running = false;
shouldPause = false;
savedText = [];
if ~opt.begin
running = true;
end
lineNum = 1;
skipping = false;
% stashMode
% 0 normal
% 1 loop
% 2 continuation
continMode = false;
compoundDepth = 0;
while 1
% get the next line from the file, bail if EOF
line = fgetl(fp);
if line == -1
break
end
lineNum = lineNum+1;
if startswith(line, '% Copyright')
skipping = true;
continue;
end
% logic to skip lines until we see one beginning with %%begin
if ~running
if strcmp(line, '%%begin')
running = true;
else
continue;
end
end;
if length(strtrim(line)) == 0
% blank line
if skipping
skipping = false;
end
fprintf('\n');
if shouldPause
scriptwait(opt);
shouldPause = false;
end
continue
elseif skipping
continue;
elseif startswith(strtrim(line), '%')
% line was a comment
disp( strtrim(line(2:end)) )
pause(opt.cdelay) % optional comment delay
continue;
else
if shouldPause
scriptwait(opt);
shouldPause = false;
end
end
% if the start of a loop, stash the text for now
if startswith(line, 'for') || startswith(line, 'while') || startswith(line, 'if')
% found a compound block, don't eval it until we get to the end
compoundDepth = compoundDepth + 1;
end
% if the statement has a continuation
if endswith(line, '...') && compoundDepth == 0
% found a compound statement, don't eval it until we get to the end
continMode = true;
end
if compoundDepth == 0 && ~continMode
prompt = '>> ';
else
prompt = '';
end
% display the line with a pretend MATLAB prompt
if opt.color
cprintf('blue', '%s%s', prompt, line)
else
fprintf('%s', prompt); disp(line)
end
if compoundDepth > 0 || continMode
% we're in stashing mode
savedText = strcat(savedText, '\n', line);
end
if compoundDepth > 0 && startswith(line, 'end')
% the compound block is fully unnested
compoundDepth = compoundDepth - 1;
if compoundDepth == 0
evalSavedText(savedText, lineNum, opt);
savedText = '';
shouldPause = true;
end
continue
elseif continMode && ~endswith(line, '...')
% no longer in continuation mode
evalSavedText(savedText, lineNum, opt);
savedText = '';
continMode = false;
shouldPause = true;
continue
end
if compoundDepth == 0 && ~continMode
% it's a simple executable statement, execute it
fprintf(' \n');
try
evalSavedText(line, lineNum, opt);
catch
break
end
shouldPause = true;
end
end
fprintf('------ done --------\n');
% restore the docking mode if we set it
set(0,'DefaultFigureWindowStyle', prevDockStatus)
cd(curDir)
end
function evalSavedText(text, lineNum, opt)
if length(strtrim(text)) == 0
return
end
text = sprintf(text);
try
if opt.color
text = strrep(text, '''', ''''''); % fix single quotes
t = evalin('base', strcat('evalc(''', text, ''')') );
cprintf('blue', '%s', t);
else
evalin('base', text);
end
catch m
fprintf('error in script %s at line %d', fname, lineNum);
m.rethrow();
end
fprintf('\n');
end
% delay or prompt according to passed options
function scriptwait(opt)
if isempty(opt.delay)
%a = input('-', 's');
prompt = 'continue?';
bs = repmat('\b', [1 length(prompt)]);
if opt.color
cprintf('red', prompt); pause;
cprintf('text', bs);
else
fprintf(prompt); pause;
fprintf(bs);
end
else
pause(opt.delay);
end
end
% test if s2 is at the start of s1 (ignoring leading spaces)
function res = startswith(s1, s2)
s1 = strtrim(s1); % trim leading white space
r = strfind(s1, s2);
res = false;
if ~isempty(r) && (r(1) == 1)
res = true;
end
end
% test if s2 is at the end of s1
function res = endswith(s1, s2)
if length(s1) < length(s2)
res = false;
else
n2 = length(s2)-1;
res = strcmp(s1(end-n2:end), s2);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
rvcpath.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/rvcpath.m
| 1,137 |
utf_8
|
f1b242a7ae5a23962546beba760c6ae1
|
%RVCPATH Install location of RVC tools
%
% p = RVCPATH is the path of the top level folder for the installed RVC
% tools.
%
% p = RVCPATH(FOLDER) is the full path of the specified FOLDER which is relative to the
% installed RVC tools.
%
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function p = rvcpath(a)
p = fileparts( which('startup_rvc.m') );
if nargin > 0
p = fullfile(p, a);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mmlabel.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/mmlabel.m
| 1,458 |
utf_8
|
6bb8d41bb64488913bcc3a1ae684d829
|
%MMLABEL labels for mplot style graph
%
% mmlabel({lab1 lab2 lab3})
%
% Notes::
% - was previously (rev 9) named mlabel() but changed to avoid clash with the
% Mapping Toolbox.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function mmlabel(lab, varargin)
% find all child axes (subplots)
h = findobj(gcf, 'Type', 'axes');
for i=1:length(h)
if strcmp( get(h(i), 'visible'), 'on'),
axes(h(i))
% get subplot number from user data (I don't know who
% sets this but its very useful)
sp = get(h(i), 'UserData');
if sp == 1,
topplot = sp;
end
ylabel(lab{sp}, varargin{:});
end
end
if 0
if nargin > 1,
axes(h(topplot)); % top plot
title(tit);
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
plotp.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/plotp.m
| 1,573 |
utf_8
|
820ce5525622153db6f6a564377af983
|
%PLOTP Plot trajectory
%
% Convenience function to plot points stored columnwise.
%
% PLOTP(P) plots a set of points P, which by Toolbox convention are stored
% one per column. P can be 2xN or 3xN. By default a linestyle of 'bx'
% is used.
%
% PLOTP(P, LS) as above but the line style arguments LS are passed to plot.
%
% See also PLOT, PLOT2.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function h = plotp(p1, varargin)
if length(varargin) == 0
varargin = {'bx'};
end
assert(any(numrows(p1) == [2 3]), 'RTB:plotp:badarg', '2D or 3D points, columnwise, only');
if numrows(p1) == 3
hh = plot3(p1(1,:), p1(2,:), p1(3,:), varargin{:});
xyzlabel
else
hh = plot(p1(1,:), p1(2,:), varargin{:});
xlabel('x');
ylabel('y');
end
if nargout == 1
h = hh;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mtools.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/mtools.m
| 1,847 |
utf_8
|
bc44bea8453c76d09fb4f2c4fee81dbd
|
%MTOOLS add simple/useful tools to all windows in figure
%
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function mtools
global DDXFILENAME
h = uicontextmenu;
uimenu(h, 'Label', 'X zoom', 'CallBack', 'xaxis');
uimenu(h, 'Label', '-->', 'CallBack', 'xscroll(0.5)');
uimenu(h, 'Label', '<--', 'CallBack', 'xscroll(-0.5)');
uimenu(h, 'Label', 'CrossHairs', 'CallBack', 'crosshair');
uimenu(h, 'Label', 'X UNzoom', 'CallBack', 'unzoom');
uimenu(h, 'Label', 'Pick delta', 'CallBack', 'fprintf(''%f %f\n'', diff(ginput(2)))');
uimenu(h, 'Label', 'Line fit', 'CallBack', 'ilinefit');
uimenu(h, 'Label', 'Show points', 'CallBack', 'showpoints(gca)');
uimenu(h, 'Label', 'Apply X zoom to all', 'CallBack', 'xaxisall');
for c=get(gcf, 'Children')',
set(c, 'UIContextMenu', h);
l = get(c, 'Children');
end
axes('pos', [0 0 1 0.05], 'visible', 'off')
if 0
if ~isempty(DDXFILENAME),
s = sprintf('[%s] %s', DDXFILENAME, date);
else
s = sprintf('%s', date);
end
text(0.95, 0.1, s, 'horizontalalign', 'right', 'verticalalign', 'baseli')
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
bresenham.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/bresenham.m
| 3,069 |
utf_8
|
433dcd2346920722c37d9bbed814dbe8
|
%BRESENHAM Generate a line
%
% P = BRESENHAM(X1, Y1, X2, Y2) is a list of integer coordinates (2xN) for
% points lying on the line segment joining the integer coordinates (X1,Y1)
% and (X2,Y2).
%
% P = BRESENHAM(P1, P2) as above but P1=[X1; Y1] and P2=[X2; Y2].
%
% Notes::
% - Endpoint coordinates must be integer values.
%
% Author::
% - Based on code by Aaron Wetzler
%
% See also ICANVAS.
% http://www.mathworks.com/matlabcentral/fileexchange/28190-bresenham-optimized-for-matlab
% Copyright (c) 2010, Aaron Wetzler
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
function p = bresenham(x1, y1, x2, y2)
if nargin == 2
p1 = x1; p2 = y1;
x1 = p1(1); y1 = p1(2);
x2 = p2(1); y2 = p2(2);
elseif nargin ~= 4
error('expecting 2 or 4 arguments');
end
% ensure all values are integer
x1=round(x1); x2=round(x2);
y1=round(y1); y2=round(y2);
% compute the vertical and horizontal change
dx=abs(x2-x1);
dy=abs(y2-y1);
steep=abs(dy)>abs(dx);
if steep
% if slope > 1 swap the deltas
t=dx;
dx=dy;
dy=t;
end
%The main algorithm goes here.
if dy==0
%
q=zeros(dx+1,1);
else
q=[0;diff(mod([floor(dx/2):-dy:-dy*dx+floor(dx/2)]',dx))>=0];
end
%and ends here.
if steep
if y1<=y2
y=[y1:y2]';
else
y=[y1:-1:y2]';
end
if x1<=x2
x=x1+cumsum(q);
else
x=x1-cumsum(q);
end
else
if x1<=x2
x=[x1:x2]';
else
x=[x1:-1:x2]';
end
if y1<=y2
y=y1+cumsum(q);
else
y=y1-cumsum(q);
end
end
p = [x y];
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
gaussfunc.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/gaussfunc.m
| 2,159 |
utf_8
|
ce83ce3f5a887482ea5ec66c52e5f2d7
|
%GAUSSFUNC Gaussian kernel
%
% G = GAUSSFUNC(MEAN, VARIANCE, X) is the value of the normal
% distribution (Gaussian) function with MEAN (1x1) and VARIANCE (1x1), at
% the point X.
%
% G = GAUSSFUNC(MEAN, COVARIANCE, X, Y) is the value of the bivariate
% normal distribution (Gaussian) function with MEAN (1x2) and COVARIANCE
% (2x2), at the point (X,Y).
%
% G = GAUSSFUNC(MEAN, COVARIANCE, X) as above but X (NxM) and the result
% is also (NxM). X and Y values come from the column and row indices of
% X.
%
% Notes::
% - X or Y can be row or column vectors, and the result will also be a vector.
% - The area or volume under the curve is unity.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function g = gaussfunc(mu, variance, x, y)
if length(mu) == 1
% 1D case
assert(all(size(variance) == [1 1]), 'covariance must be a 1x1 matrix')
g = 1/sqrt(2*pi*variance) * exp( -((x-mu).^2)/(2*variance) );
elseif length(mu) == 2
% 2D case
assert(length(mu) == 2, 'mean must be a 2-vector');
assert(all(size(variance) == [2 2]), 'covariance must be a 2x2 matrix')
if nargin < 4
[x,y] = imeshgrid(x);
end
xx = x(:)-mu(1); yy = y(:)-mu(2);
ci = inv(variance);
g = 1/(2*pi*sqrt(det(variance))) * exp( -0.5*(xx.^2*ci(1,1) + yy.^2*ci(2,2) + 2*xx.*yy*ci(1,2)));
g = reshape(g, size(x));
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
PluckerTest.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/unit_test/PluckerTest.m
| 790 |
utf_8
|
2ba1dac6e1882a015dc1371045aa13bd
|
function tests = PluckerTest
tests = functiontests(localfunctions);
end
function constructor_test(tc)
end
function methods_test(tc)
% intersection
px = Plucker([0 0 0], [1 0 0]); % x-axis
py = Plucker([0 0 0], [0 1 0]); % y-axis
px1 = Plucker([0 1 0], [1 1 0]); % offset x-axis
verifyEqual(tc, px.origin_distance(), 0);
verifyEqual(tc, px1.origin_distance(), 1);
verifyEqual(tc, px1.origin_closesst(), [0 1 0]');
px.intersect(px)
px.intersect(py)
px.intersect(px1)
end
function intersect_test(tc)
px = Plucker([0 0 0], [1 0 0]); % x-axis
py = Plucker([0 0 0], [0 1 0]); % y-axis
plane.d = [1 0 0]; plane.p = 2; % plane x=2
px.intersect_plane(plane)
py.intersect_plane(plane)
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
plotXTest.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/unit_test/plotXTest.m
| 10,075 |
utf_8
|
5e0c1a61709cdd8015d7777373ef326a
|
% 2d outline, filled case
% 3d outlien, filled case
% with LS or edgecolor, color options etc.
function tests = plotXTest
tests = functiontests(localfunctions);
close all
end
function teardownOnce(tc)
close all
end
function plotpoint_test(tc)
% simple
points = rand(2,5);
clf; plot_point(points);
tc.verifyEqual(length(get(gca, 'Children')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
lines = findobj(gca, 'Type', 'line');
for i=1:5
tc.verifyEqual(length(lines(i).XData), 1);
tc.verifyEqual(length(lines(i).YData), 1);
tc.verifyEqual(lines(i).LineStyle, 'none');
tc.verifyEqual(lines(i).MarkerSize, 6);
tc.verifyEqual(lines(i).MarkerFaceColor, 'none');
tc.verifyEqual(lines(i).Marker, 'square');
end
% markers specified
clf; plot_point(points, 'rd');
tc.verifyEqual(length(get(gca, 'Children')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
lines = findobj(gca, 'Type', 'line');
for i=1:5
tc.verifyEqual(lines(i).LineStyle, 'none');
tc.verifyEqual(lines(i).MarkerSize, 6);
tc.verifyEqual(lines(i).MarkerFaceColor, 'none');
tc.verifyEqual(lines(i).Marker, 'diamond');
tc.verifyEqual(lines(i).Color, [1 0 0]);
end
% markers specified solid
clf; plot_point(points, 'rd', 'solid');
tc.verifyEqual(length(get(gca, 'Children')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
lines = findobj(gca, 'Type', 'line');
for i=1:5
tc.verifyEqual(lines(i).LineStyle, 'none');
tc.verifyEqual(lines(i).MarkerSize, 6);
tc.verifyEqual(lines(i).MarkerFaceColor, [1 0 0]);
tc.verifyEqual(lines(i).Marker, 'diamond');
tc.verifyEqual(lines(i).Color, [1 0 0]);
end
% sequential labels
clf; plot_point(points, 'sequence');
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
set = [1:5];
for i=1:5
set = setdiff(set, str2num(labels(i).String));
end
tc.verifyEmpty(set, 'Not all labels found');
% specified labels
L = {'A', 'B', 'C', 'D', 'E'};
clf; plot_point(points, 'label', L);
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
set = [1:5];
for i=1:5
set = setdiff(set, double(strip(labels(i).String))-'A'+1);
end
tc.verifyEmpty(set, 'Not all labels found');
% printf labels
clf; plot_point(points, 'printf', {'label=%d', 21:25});
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
set = [21:25];
for i=1:5
l = strip(labels(i).String);
tc.verifyEqual(l(1:6), 'label=');
set = setdiff(set, str2num(l(7:end)));
end
tc.verifyEmpty(set, 'Not all labels found');
% specify font size
clf; plot_point(points, 'sequence', 'textsize', 23);
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
for i=1:5
tc.verifyEqual(labels(i).FontSize, 23);
tc.verifyEqual(labels(i).FontWeight, 'normal');
end
% specify font color
clf; plot_point(points, 'sequence', 'textcolor', 'g');
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
for i=1:5
tc.verifyEqual(labels(i).Color, [0 1 0]);
tc.verifyEqual(labels(i).FontWeight, 'normal');
end
% specify font color
clf; plot_point(points, 'sequence', 'textcolor', [0.2 0.3 0.4]);
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
for i=1:5
tc.verifyEqual(labels(i).Color, [0.2 0.3 0.4]);
tc.verifyEqual(labels(i).FontWeight, 'normal');
end
% specify font weight
clf; plot_point(points, 'sequence', 'bold');
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
for i=1:5
tc.verifyEqual(labels(i).FontWeight, 'bold');
end
% specify font size, weight, color
clf; plot_point(points, 'sequence', 'textsize', 23, 'bold', 'textcolor', [0.2 0.3 0.4]);
tc.verifyEqual(length(get(gca, 'Children')), 10);
tc.verifyEqual(length(findobj(gca, 'Type', 'line')), 5);
tc.verifyEqual(length(findobj(gca, 'Type', 'text')), 5);
labels = findobj(gca, 'Type', 'text');
for i=1:5
tc.verifyEqual(labels(i).FontSize, 23);
tc.verifyEqual(labels(i).FontWeight, 'bold');
tc.verifyEqual(labels(i).Color, [0.2 0.3 0.4]);
end
end
function plotpoly_test(tc)
opt.animate = false;
% 2d and 3D
opt.tag = [];
opt.axis = [];
P = [1 3 5; 1 5 1];
clf; plot_poly(P);
tc.verifyEqual(length(get(gca, 'Children')), 1);
lines = findobj(gca, 'Type', 'line');
tc.verifyEqual(length(lines), 1);
tc.verifyEqual(length(lines(1).XData), 4);
tc.verifyEqual(length(lines(1).YData), 4);
tc.verifyEqual(lines(1).Marker, 'none');
tc.verifyEqual(lines(1).LineStyle, '-');
clf; plot_poly(P, 'g--');
tc.verifyEqual(length(get(gca, 'Children')), 1);
lines = findobj(gca, 'Type', 'line');
tc.verifyEqual(length(lines), 1);
tc.verifyEqual(length(lines(1).XData), 4);
tc.verifyEqual(length(lines(1).YData), 4);
tc.verifyEqual(lines(1).Marker, 'none');
tc.verifyEqual(lines(1).LineStyle, '--');
tc.verifyEqual(lines(1).Color, [0 1 0]);
clf; plot_poly(P, 'edgecolor', 'r');
tc.verifyEqual(length(get(gca, 'Children')), 1);
lines = findobj(gca, 'Type', 'line');
tc.verifyEqual(length(lines), 1);
tc.verifyEqual(length(lines(1).XData), 4);
tc.verifyEqual(length(lines(1).YData), 4);
tc.verifyEqual(lines(1).Marker, 'none');
tc.verifyEqual(lines(1).LineStyle, '-');
%tc.verifyEqual(lines(1).Color, [1 0 0]);
clf; plot_poly(P, 'edgecolor', [0.2 0.3 0.4]);
tc.verifyEqual(length(get(gca, 'Children')), 1);
lines = findobj(gca, 'Type', 'line');
tc.verifyEqual(length(lines), 1);
tc.verifyEqual(length(lines(1).XData), 4);
tc.verifyEqual(length(lines(1).YData), 4);
tc.verifyEqual(lines(1).Marker, 'none');
tc.verifyEqual(lines(1).LineStyle, '-');
%tc.verifyEqual(lines(1).Color, [0.2 0.3 0.4]);
clf; plot_poly(P, 'tag', 'bob');
lines = findobj(gca, 'Type', 'line');
%tc.verifyEqual(lines(1).Tag, 'bob'); % no tag for line type
%-------- patch mode
clf; plot_poly(P, 'fillcolor', 'r');
tc.verifyEqual(length(get(gca, 'Children')), 1);
patch = findobj(gca, 'Type', 'patch');
tc.verifyEqual(length(patch), 1);
tc.verifyEqual(patch.FaceColor, [1 0 0]);
tc.verifyEqual(patch.FaceAlpha, 1);
tc.verifyEqual(patch.EdgeColor, [0 0 0]);
tc.verifyEqual(patch.LineStyle, '-');
tc.verifySize(patch.Faces, [1 3]);
tc.verifySize(patch.Vertices, [3 2]);
clf; plot_poly(P, 'fillcolor', 'g', 'alpha', 0.5);
tc.verifyEqual(length(get(gca, 'Children')), 1);
patch = findobj(gca, 'Type', 'patch');
tc.verifyEqual(length(patch), 1);
tc.verifyEqual(patch.FaceColor, [0 1 0]);
tc.verifyEqual(patch.FaceAlpha, 0.5);
tc.verifyEqual(patch.EdgeColor, [0 0 0]);
tc.verifyEqual(patch.LineStyle, '-');
tc.verifySize(patch.Faces, [1 3]);
tc.verifySize(patch.Vertices, [3 2]);
clf; plot_poly(P, 'fillcolor', 'b', 'tag', 'bob');
patch = findobj(gca, 'Type', 'patch');
%tc.verifyEqual(patch.Tag, 'bob'); % no tag
end
function plot_sphere(tc)
end
function plot_box(tc)
end
function plot_arrow(tc)
end
function plot_homline(tc)
end
% plot_ellipse
function ellipse2d_test(testCase)
clf
E = diag([9 4]);
plot_ellipse(E)
plot_ellipse(E, [4 0], 'r--');
plot_ellipse(E, [0 4], 'edgecolor', 'g');
plot_ellipse(E, [4 4], 'fillcolor', 'g');
plot_ellipse(E, [0 8 0.5], 'edgecolor', 'r', 'fillcolor', 'c', 'alpha', 0.5, 'LineWidth', 3);
plot_ellipse(E, [4 8], 'b--', 'LineWidth', 3);
axis equal
end
function ellipse2d_animate_test(testCase)
clf
axis([-4 4 -4 4]);
E = diag([9 4]);
h = plot_ellipse(E, 'g');
for x = circle([0 0], 1)
plot_ellipse(E, x, 'alter', h)
pause(0.1)
end
clf
axis([-4 4 -4 4]);
h = plot_ellipse(E, [0 0 0.5], 'edgecolor', 'r', 'fillcolor', 'c', 'LineWidth', 3);
for x = circle([0 0], 1)
plot_ellipse(E, x, 'alter', h)
pause(0.1)
end
end
% plot_ellipse
function ellipse3d_test(testCase)
clf
E = diag([9 4 6]);
plot_ellipse(E)
pause
clf
plot_ellipse(E, 'edgecolor', 'g');
pause
clf
plot_ellipse(E, 'fillcolor', 'g');
pause
clf
plot_ellipse(E, 'fillcolor', 'g', 'shadow');
pause
clf
plot_ellipse(E, 'fillcolor', 'g', 'edgecolor', 'r', 'LineWidth', 2);
pause
plot_ellipse(E, [0 8], 'edgecolor', 'r', 'fillcolor', 'c');
plot_ellipse(E, [4 8], 'LineWidth', 3, 'MarkerStyle', '+');
axis equal
end
function ellipse3d_animate_test(testCase)
clf
axis([-4 4 -4 4 -4 4]);
E = diag([9 4 6]);
h = plot_ellipse(E, 'g');
for x = circle([0 0], 1)
plot_ellipse(E, [x; 0], 'alter', h)
pause(0.1)
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
tboptparseTest.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/common/unit_test/tboptparseTest.m
| 8,306 |
utf_8
|
7663089541e7d9d2c91c64363ab51eb9
|
function tests = tboptparseTest()
tests = functiontests(localfunctions);
end
function setupOnce(tc)
opt.foo = false;
opt.bar = true;
opt.blah = [];
opt.stuff = {};
opt.choose = {'this', 'that', 'other'};
opt.select = {'#no', '#yes'};
opt.old = '@foo';
opt.d_3d = false;
tc.TestData.opt = opt;
end
function boolTest(tc)
opt.foo = false;
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.foo, false);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo'});
tc.verifyEqual(out.foo, true);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'distract'});
tc.verifyEqual(out.foo, false);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'foo', 'distract'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'distract', 'foo'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
end
function noboolTest(tc)
opt.foo = true;
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.foo, true);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo'});
tc.verifyEqual(out.foo, true);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'nofoo'});
tc.verifyEqual(out.foo, false);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'distract'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'foo', 'distract'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'distract', 'foo'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'nofoo', 'distract'});
tc.verifyEqual(out.foo, false);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'distract', 'nofoo'});
tc.verifyEqual(out.foo, false);
tc.verifyEqual(args, {'distract'});
end
function setTest(tc)
opt.foo = [];
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.foo, []);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', 3});
tc.verifyEqual(out.foo, 3);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', 'bar'});
tc.verifyEqual(out.foo, 'bar');
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', [1 2 3]});
tc.verifyEqual(out.foo, [1 2 3]);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', {1 2 3}});
tc.verifyEqual(out.foo, {1 2 3});
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'distract'});
tc.verifyEqual(out.foo, []);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'distract', 'foo', 'bar'});
tc.verifyEqual(out.foo, 'bar');
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'foo', 'bar', 'distract'});
tc.verifyEqual(out.foo, 'bar');
tc.verifyEqual(args, {'distract'});
end
function cellsetTest(tc)
opt.foo = {};
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.foo, {});
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', 3});
tc.verifyEqual(out.foo, {3});
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', 'bar'});
tc.verifyEqual(out.foo, {'bar'});
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', [1 2 3]});
tc.verifyEqual(out.foo, {[1 2 3]});
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo', {1 2 3}});
tc.verifyEqual(out.foo, {1 2 3});
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'distract'});
tc.verifyEqual(out.foo, {});
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'distract', 'foo', 'bar'});
tc.verifyEqual(out.foo, {'bar'});
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'foo', 'bar', 'distract'});
tc.verifyEqual(out.foo, {'bar'});
tc.verifyEqual(args, {'distract'});
end
function chooseTest(tc)
opt.choose = {'this', 'that', 'other'};
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.choose, 'this');
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'this'});
tc.verifyEqual(out.choose, 'this');
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'that'});
tc.verifyEqual(out.choose, 'that');
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'other'});
tc.verifyEqual(out.choose, 'other');
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'yetanother'}); % this one not in the list
tc.verifyEqual(out.choose, 'this'); % return default
tc.verifyEqual(args, {'yetanother'}); % and the arg is returned here
[out,args] = tb_optparse(opt, {'distract', 'that'});
tc.verifyEqual(out.choose, 'that');
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'that','distract'});
tc.verifyEqual(out.choose, 'that');
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'yetanother','distract'});
tc.verifyEqual(out.choose, 'this');
tc.verifyEqual(args, {'yetanother','distract'});
end
function hashchooseTest(tc)
opt.choose = {'#this', '#that', '#other'};
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.choose, 1);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'this'});
tc.verifyEqual(out.choose, 1);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'that'});
tc.verifyEqual(out.choose, 2);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'other'});
tc.verifyEqual(out.choose, 3);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'yetanother'}); % this one not in the list
tc.verifyEqual(out.choose, 1); % return default
tc.verifyEqual(args, {'yetanother'}); % and the arg is returned here
[out,args] = tb_optparse(opt, {'distract', 'that'});
tc.verifyEqual(out.choose, 2);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'that','distract'});
tc.verifyEqual(out.choose, 2);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'yetanother','distract'});
tc.verifyEqual(out.choose, 1);
tc.verifyEqual(args, {'yetanother','distract'});
end
function synonymTest(tc)
opt.foo = false;
opt.bar = '@foo';
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.foo, false);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'foo'});
tc.verifyEqual(out.foo, true);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'bar'});
tc.verifyEqual(out.foo, true);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'distract'});
tc.verifyEqual(out.foo, false);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'bar', 'distract'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
[out,args] = tb_optparse(opt, {'distract', 'bar'});
tc.verifyEqual(out.foo, true);
tc.verifyEqual(args, {'distract'});
end
function startDigitTest(tc)
% bool
opt.d_3foo = false;
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.d_3foo, false);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'3foo'});
tc.verifyEqual(out.d_3foo, true);
tc.verifySize(args, [0 0]);
% set
opt.d_3foo = [];
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.d_3foo, []);
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'3foo', [1 2 3]});
tc.verifyEqual(out.d_3foo, [1 2 3]);
tc.verifySize(args, [0 0]);
% choose
opt.d_3foo = {'this', 'that', 'other'};
[out,args] = tb_optparse(opt, {});
tc.verifyEqual(out.d_3foo, 'this');
tc.verifySize(args, [0 0]);
[out,args] = tb_optparse(opt, {'3foo', 'that'});
tc.verifyEqual(out.d_3foo, 'that');
tc.verifySize(args, [0 0]);
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
wtrans.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/wtrans.m
| 1,393 |
utf_8
|
b7605b6674672f58fa44fff0ff9f444b
|
%WTRANS Transform a wrench between coordinate frames
%
% WT = WTRANS(T, W) is a wrench (6x1) in the frame represented by the homogeneous
% transform T (4x4) corresponding to the world frame wrench W (6x1).
%
% The wrenches W and WT are 6-vectors of the form [Fx Fy Fz Mx My Mz]'.
%
% See also TR2DELTA, TR2JAC.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function Wt = wtrans(T, W)
assert(ishomog(T), 'RTB:wtrans:badarg', 'T must be 4x4');
assert(isvec(W,6), 'RTB:wtrans:badarg', 'W must be a 6-vector');
W = W(:);
f = W(1:3); m = W(4:6);
k = cross(f, transl(T) ) + m;
ft = t2r(T)' * f;
mt = t2r(T)' * k;
Wt = [ft; mt];
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
mtraj.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/mtraj.m
| 3,306 |
utf_8
|
3b82474dbf11dba63f8278f8dc1b72f9
|
%MTRAJ Multi-axis trajectory between two points
%
% [Q,QD,QDD] = MTRAJ(TFUNC, Q0, QF, M) is a multi-axis trajectory (MxN) varying
% from configuration Q0 (1xN) to QF (1xN) according to the scalar trajectory function
% TFUNC in M steps. Joint velocity and acceleration can be optionally returned as
% QD (MxN) and QDD (MxN) respectively. The trajectory outputs have one row per
% time step, and one column per axis.
%
% The shape of the trajectory is given by the scalar trajectory function
% TFUNC which is applied to each axis:
% [S,SD,SDD] = TFUNC(S0, SF, M);
% and possible values of TFUNC include @lspb for a trapezoidal trajectory, or
% @tpoly for a polynomial trajectory.
%
% [Q,QD,QDD] = MTRAJ(TFUNC, Q0, QF, T) as above but T (Mx1) is a time
% vector which dictates the number of points on the trajectory.
%
% Notes::
% - If no output arguments are specified Q, QD, and QDD are plotted.
% - When TFUNC is @tpoly the result is functionally equivalent to JTRAJ except
% that no initial velocities can be specified. JTRAJ is computationally a little
% more efficient.
%
% See also JTRAJ, MSTRAJ, LSPB, TPOLY.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [S,Sd,Sdd] = mtraj(tfunc, q0, qf, M)
if ~isa(tfunc, 'function_handle')
error('first argument must be a function handle');
end
M0 = M;
if ~isscalar(M)
M = length(M);
end
if numcols(q0) ~= numcols(qf)
error('must be same number of columns in q0 and qf')
end
s = zeros(M, numcols(q0));
sd = zeros(M, numcols(q0));
sdd = zeros(M, numcols(q0));
for i=1:numcols(q0)
% for each axis
[s(:,i),sd(:,i),sdd(:,i)] = tfunc(q0(i), qf(i), M);
end
% - If no output arguments are specified S, SD, and SDD are plotted
% against time.
switch nargout
case 0
clf
if isscalar(M0)
t = [1:M0]';
else
t = M0;
end
subplot(311)
plot(t, s); grid; ylabel('s');
subplot(312)
plot(t, sd); grid; ylabel('sd');
subplot(313)
plot(t, sdd); grid; ylabel('sdd');
if ~isscalar(M0)
xlabel('time')
else
for c=get(gcf, 'Children');
set(c, 'XLim', [1 M0]);
end
end
shg
case 1
S = s;
case 2
S = s;
Sd = sd;
case 3
S = s;
Sd = sd;
Sdd = sdd;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
lspb.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/lspb.m
| 5,386 |
utf_8
|
fbf1346e01e601dd3d554501c4367a67
|
%LSPB Linear segment with parabolic blend
%
% [S,SD,SDD] = LSPB(S0, SF, M) is a scalar trajectory (Mx1) that varies
% smoothly from S0 to SF in M steps using a constant velocity segment and
% parabolic blends (a trapezoidal velocity profile). Velocity and
% acceleration can be optionally returned as SD (Mx1) and SDD (Mx1)
% respectively.
%
% [S,SD,SDD] = LSPB(S0, SF, M, V) as above but specifies the velocity of
% the linear segment which is normally computed automatically.
%
% [S,SD,SDD] = LSPB(S0, SF, T) as above but specifies the trajectory in
% terms of the length of the time vector T (Mx1).
%
% [S,SD,SDD] = LSPB(S0, SF, T, V) as above but specifies the velocity of
% the linear segment which is normally computed automatically and a time
% vector.
%
% LSPB(S0, SF, M, V) as above but plots S, SD and SDD versus time in a single
% figure.
%
% Notes::
% - If M is given
% - Velocity is in units of distance per trajectory step, not per second.
% - Acceleration is in units of distance per trajectory step squared, not
% per second squared.
% - If T is given then results are scaled to units of time.
% - The time vector T is assumed to be monotonically increasing, and time
% scaling is based on the first and last element.
% - For some values of V no solution is possible and an error is flagged.
%
% References::
% - Robotics, Vision & Control, Chap 3,
% P. Corke, Springer 2011.
%
% See also TPOLY, JTRAJ.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%TODO
% add a 'dt' option, to convert to everything to units of seconds
function [s,sd,sdd] = lspb(q0, q1, t, V)
t0 = t;
if isscalar(t)
t = (0:t-1)';
else
t = t(:);
end
plotsargs = {'Markersize', 16};
tf = max(t(:));
if nargin < 4
% if velocity not specified, compute it
V = (q1-q0)/tf * 1.5;
else
V = abs(V) * sign(q1-q0);
if abs(V) < abs(q1-q0)/tf
error('V too small');
elseif abs(V) > 2*abs(q1-q0)/tf
error('V too big');
end
end
if q0 == q1
s = ones(size(t)) * q0;
sd = zeros(size(t));
sdd = zeros(size(t));
return
end
tb = (q0 - q1 + V*tf)/V;
a = V/tb;
p = zeros(length(t), 1);
pd = p;
pdd = p;
for i = 1:length(t)
tt = t(i);
if tt <= tb
% initial blend
p(i) = q0 + a/2*tt^2;
pd(i) = a*tt;
pdd(i) = a;
elseif tt <= (tf-tb)
% linear motion
p(i) = (q1+q0-V*tf)/2 + V*tt;
pd(i) = V;
pdd(i) = 0;
else
% final blend
p(i) = q1 - a/2*tf^2 + a*tf*tt - a/2*tt^2;
pd(i) = a*tf - a*tt;
pdd(i) = -a;
end
end
switch nargout
case 0
if isscalar(t0)
% for scalar time steps, axis is labeled 1 .. M
xt = t+1;
else
% for vector time steps, axis is labeled by vector M
xt = t;
end
clf
subplot(311)
% highlight the accel, coast, decel phases with different
% colored markers
hold on
%plot(xt, p);
k = t<= tb;
plot(xt(k), p(k), 'r.-', plotsargs{:});
k = (t>=tb) & (t<= (tf-tb));
plot(xt(k), p(k), 'b.-', plotsargs{:});
k = t>= (tf-tb);
plot(xt(k), p(k), 'g.-', plotsargs{:});
grid; ylabel('$s$', 'FontSize', 16, 'Interpreter','latex');
hold off
subplot(312)
plot(xt, pd, '.-', plotsargs{:});
grid;
if isscalar(t0)
ylabel('$ds/dk$', 'FontSize', 16, 'Interpreter','latex');
else
ylabel('$ds/dt$', 'FontSize', 16, 'Interpreter','latex');
end
subplot(313)
plot(xt, pdd, '.-', plotsargs{:});
grid;
if isscalar(t0)
ylabel('$ds^2/dk^2$', 'FontSize', 16, 'Interpreter','latex');
else
ylabel('$ds^2/dt^2$', 'FontSize', 16, 'Interpreter','latex');
end
if ~isscalar(t0)
xlabel('t (seconds)')
else
xlabel('k (step)');
for c=findobj(gcf, 'Type', 'axes')
set(c, 'XLim', [1 t0]);
end
end
shg
case 1
s = p;
case 2
s = p;
sd = pd;
case 3
s = p;
sd = pd;
sdd = pdd;
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
qplot.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/qplot.m
| 1,557 |
utf_8
|
585f70da4e5c4f31e64f8f5b54973326
|
%QPLOT Plot robot joint angles
%
% QPLOT(Q) is a convenience function to plot joint angle trajectories (Mx6) for
% a 6-axis robot, where each row represents one time step.
%
% The first three joints are shown as solid lines, the last three joints (wrist)
% are shown as dashed lines. A legend is also displayed.
%
% QPLOT(T, Q) as above but displays the joint angle trajectory versus time
% given the time vector T (Mx1).
%
% See also JTRAJ, PLOTP, PLOT.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function qplot(t, q)
if nargin < 2
q = t;
t = (1:numrows(q))';
end
%clf
hold on
plot(t, q(:,1:3))
plot(t, q(:,4:6), '--')
grid on
xlabel('Time (s)')
ylabel('Joint coordinates (rad,m)')
legend('q1', 'q2', 'q3', 'q4', 'q5', 'q6');
hold off
xlim([t(1), t(end)]);
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
distributeblocks.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/distributeblocks.m
| 2,689 |
utf_8
|
02d506ec479136e1e31aa0bc8d7e55e2
|
%DISTRIBUTEBLOCKS Distribute blocks in Simulink block library
%
% distributeBlocks(MODEL) equidistantly distributes blocks in a Simulink
% block library named MODEL.
%
% Notes::
% - The MATLAB functions to create Simulink blocks from symbolic
% expresssions actually place all blocks on top of each other. This
% function scans a simulink model and rearranges the blocks on an
% equidistantly spaced grid.
% - The Simulink model must already be opened before running this
% function!
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also symexpr2slblock, doesblockexist.
% Copyright (C) 2012-2013, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for Matlab (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
%
% The code generation module emerged during the work on a project funded by
% the German Research Foundation (DFG, BE1569/7-1). The authors gratefully
% acknowledge the financial support.
function [ ] = distributeblocks( mdlName )
%% Get a list of all first level blocks:
blockNames = find_system(mdlName,'SearchDepth',1);
blockNames = blockNames(2:end); % First cell contains the model name
%% Determine the maximum width and height of a block
allPosC = get_param(blockNames,'Position');
allPosM = cell2mat(allPosC); % [left top right bottom] The maximum value for a coordinate is 32767
widths = allPosM(:,3)-allPosM(:,1);
heights = allPosM(:,4)-allPosM(:,2);
maxWidth = max(widths);
maxHeight = max(heights);
%% Set grid spacing
wBase = 2*maxWidth;
hBase = 2*maxHeight;
%% Start rearranging blocks
nBlocks = size(allPosM,1);
nColRow = ceil(sqrt(nBlocks));
for iBlocks = 1:nBlocks
% block location on grid
[row,col] = ind2sub([nColRow, nColRow],iBlocks);
% compute block coordinates
left = col*wBase;
right = left+maxWidth;
top = row*hBase;
bottom = top+maxHeight;
% apply new coordinates
set_param(blockNames{iBlocks},'Position',[left top right bottom])
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ccodefunctionstring.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/ccodefunctionstring.m
| 7,927 |
utf_8
|
cfe55f9ddbe99a594495d3620bfe4dd3
|
%CCODEFUNCTIONSTRING Converts a symbolic expression into a C-code function
%
% [FUNSTR, HDRSTR] = ccodefunctionstring(SYMEXPR, ARGLIST) returns a string
% representing a C-code implementation of a symbolic expression SYMEXPR.
% The C-code implementation has a signature of the form:
%
% void funname(double[][n_o] out, const double in1,
% const double* in2, const double[][n_i] in3);
%
% depending on the number of inputs to the function as well as the
% dimensionality of the inputs (n_i) and the output (n_o).
% The whole C-code implementation is returned in FUNSTR, while HDRSTR
% contains just the signature ending with a semi-colon (for the use in
% header files).
%
% Options::
% 'funname',name Specify the name of the generated C-function. If
% this optional argument is omitted, the variable name
% of the first input argument is used, if possible.
% 'output',outVar Defines the identifier of the output variable in the C-function.
% 'vars',varCells The inputs to the C-code function must be defined as a cell array. The
% elements of this cell array contain the symbolic variables required to
% compute the output. The elements may be scalars, vectors or matrices
% symbolic variables. The C-function prototype will be composed accoringly
% as exemplified above.
% 'flag',sig Specifies if function signature only is generated, default (false).
%
% Example::
% % Create symbolic variables
% syms q1 q2 q3
%
% Q = [q1 q2 q3];
% % Create symbolic expression
% myrot = rotz(q3)*roty(q2)*rotx(q1)
%
% % Generate C-function string
% [funstr, hdrstr] = ccodefunctionstring(myrot,'output','foo', ...
% 'vars',{Q},'funname','rotate_xyz')
%
% Notes::
% - The function wraps around the built-in Matlab function 'ccode'. It does
% not check for proper C syntax. You must take care of proper
% dimensionality of inputs and outputs with respect to your symbolic
% expression on your own. Otherwise the generated C-function may not
% compile as desired.
%
% Author::
% Joern Malzahn, ([email protected])
%
% See also ccode, matlabFunction.
% Copyright (C) 2012-2018, by Joern Malzahn
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function [funstr hdrstr] = ccodefunctionstring(f,varargin)
% option defaults
opt.funname = inputname(1);
opt.output{1} = zeros(size(f));
opt.outputName{1} = inputname(1);
opt.flag = 0;
if isempty(opt.outputName{1})
opt.outputName{1} = 'myout';
end
opt.vars = {};
% tb_optparse is not applicable here,
% since handling cell inputs and extracting input variable names is
% required.
% Thus, scan varargin manually:
if mod(nargin,2)==0
error('CodeGenerator:codefunctionstring:wrongArgumentList',...
'Wrong number of elements in the argument list.');
end
for iArg = 1:2:nargin-1
switch lower(varargin{iArg})
case 'funname'
opt.funname = varargin{iArg+1};
case 'output'
if ~isempty(varargin{iArg+1})
opt.outputName{1} = varargin{iArg+1};
end
case 'vars'
opt.vars = varargin{iArg+1};
case 'flag'
opt.flag = varargin{iArg+1};
otherwise
error('ccodefunctionstring:unknownArgument',...
['Argument ',inputname(iArg),' unknown.']);
end
end
nOut = numel(opt.output);
nIn = numel(opt.vars);
%% Function signature
funstr = sprintf('void %s(', opt.funname);
initstr = '';
% outputs
for iOut = 1:nOut
tmpOutName = opt.outputName{iOut};
tmpOut = opt.output{iOut};
if ~isscalar(tmpOut);
funstr = [funstr, sprintf('double %s[][%u]', tmpOutName, size(tmpOut,1) ) ];
for iRow = 1:size(tmpOut,1)
for iCol = 1:size(tmpOut,2)
initstr = sprintf(' %s %s[%u][%u]=0;\n',initstr,tmpOutName,iCol-1,iRow-1);
end
end
else
funstr = [funstr, sprintf('double %s', tmpOutName ) ];
end
% separate argument list by commas
if ( iOut ~= nOut ) || ( nIn > 0 )
funstr = [funstr,', '];
end
end
% inputs
for iIn = 1:nIn
tmpInName = ['input',num2str(iIn)];%opt.varsName{iIn};
tmpIn = opt.vars{iIn};
% treat different dimensionality of input variables
if isscalar(tmpIn)
funstr = [funstr, sprintf('const double %s', tmpInName ) ];
elseif isvector(tmpIn)
funstr = [funstr, sprintf('const double* %s', tmpInName ) ];
elseif ismatrix(tmpIn)
funstr = [funstr, sprintf('const double %s[][%u]', tmpInName, size(tmpIn,2) ) ];
else
error('ccodefunctionstring:UnsupportedOutputType', 'Unsupported datatype for %s', tmpOutName)
end
% separate argument list by commas
if ( iIn ~= nIn )
funstr = [funstr,', '];
end
end
funstr = [funstr,sprintf('%s', ')')];
% finalize signature for the use in header files
if nargout > 1
hdrstr = [funstr,sprintf('%s', ';')];
end
if opt.flag
return; %% STOP IF FLAG == TRUE
end
% finalize signature for use in function definition
funstr = [funstr,sprintf('%s', '{')];
funstr = sprintf('%s\n%s',funstr,sprintf('%s', ' ') ); % empty line
%% Function body
% input paramter expansion
for iIn = 1:nIn
tmpInName = ['input',num2str(iIn)];%opt.varsName{iIn};
tmpIn = opt.vars{iIn};
% for scalars
% -> do nothing
% for vectors
if ~isscalar(tmpIn) && isvector(tmpIn)
nEl = numel(tmpIn);
for iEl = 1:nEl
funstr = sprintf('%s\n%s',...
funstr,...
sprintf(' double %s = %s[%u];', char(tmpIn(iEl)), tmpInName,iEl-1 ));
end
% for matrices
elseif ~isscalar(tmpIn) && ~isvector(tmpIn) && ismatrix(tmpIn)
nRow = size(tmpIn,1);
nCol = size(tmpIn,2);
for iRow = 1:nRow
for iCol = 1:nCol
funstr = sprintf('%s\n%s',...
funstr,...
sprintf(' double %s%u%u = %s[%u][%u];', char(tmpIn(iRow,iCol)), iRow, iCol, tmpInName{iIn},iRow-1,iCol-1 ));
end
end
end
end
funstr = sprintf('%s\n%s',...
funstr,...
sprintf('%s', ' ') );
funstr = sprintf('%s\n%s',...
funstr,...
sprintf('%s\n\n', initstr) );
% Actual code
% use f.' here, because of column/row indexing in C
codestr = '';
if ~isequal(f, sym(zeros(size(f))))
eval([opt.outputName{1}, ' = f.''; codestr = ccode(',opt.outputName{1},');'])
end
if isscalar(f)
% in the case of scalar expressions the resulting ccode always
% begins with ' t0'. Replace that with the desired name.
codestr = strrep(codestr,'t0',opt.outputName{1});
end
funstr = sprintf('%s\n%s',...
funstr,...
codestr );
funstr = sprintf('%s\n%s',...
funstr,sprintf('%s', '}') );
funstr = sprintf('%s\n%s',...
funstr,sprintf('%s', ' ') ); % empty line
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
PoseGraph.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/PoseGraph.m
| 19,934 |
utf_8
|
fb33eb8e5b89b2304d1d87c7ccfcae17
|
%PoseGraph Pose graph
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
classdef PoseGraph < handle
properties
graph
ngrid
center
cellsize
end
methods
function pg = PoseGraph(filename, varargin)
% parse the file data
% we assume g2o format
% VERTEX* vertex_id X Y THETA
% EDGE* startvertex_id endvertex_id X Y THETA IXX IXY IYY IXT IYT ITT
% vertex numbers start at 0
opt.laser = false;
opt = tb_optparse(opt, varargin);
pg.graph = PGraph(3, 'distance', 'SE2');
fp = fopen(filename, 'r');
assert(fp > 0, 'Can''t open file %s', filename);
toroformat = false;
nlaser = 0;
% indices into ROBOTLASER1 record for the 3x3 info matrix in column major
% order
g2o = [6 7 8 7 9 10 8 10 11];
toro = [6 7 10 7 8 11 10 11 9];
% we keep an array pgi = vindex(gi) to map g2o vertex index to PGraph vertex index
tic
while ~feof(fp)
line = fgets(fp);
% is it a comment?
if line(1) == '#'
continue;
end
% get keyword
k = strfind(line, ' ');
% and deal with it
switch line(1:k-1)
case 'VERTEX_SE2'
% g2o format vertex
vertex = sscanf(line(k+1:end), '%d %f %f %f')';
v = pg.graph.add_node(vertex(2:4));
vindex(vertex(1)+1) = v;
vd.type = 'vertex';
pg.graph.setvdata(v, vd);
case 'VERTEX_XY'
vertex = sscanf(line(k+1:end), '%d %f %f')';
v = pg.graph.add_node(vertex(2:4));
vindex(vertex(1)+1) = v;
vd.type = 'landmark';
pg.graph.setvdata(v, vd);
case 'EDGE_SE2'
% g2o format edge
edge = sscanf(line(k+1:end), '%f')';
v1 = vindex(edge(1)+1);
v2 = vindex(edge(2)+1);
% create the edge
e = pg.graph.add_edge(v1, v2);
% create the edge data as a structure
% X Y T
% 3 4 5
ed.mean = edge(3:5);
% IXX IXY IXT IYY IYT ITT
% 6 7 8 9 10 11
ed.info = reshape(edge(g2o), [3 3]);
% and attach it
pg.graph.setedata(e, ed);
case 'VERTEX2'
toroformat = true;
vertex = sscanf(line(k+1:end), '%d %f %f %f')';
v = pg.graph.add_node(vertex(2:4));
vindex(vertex(1)+1) = v;
vd.type = 'vertex';
pg.graph.setvdata(v, vd);
case 'EDGE2'
toroformat = true;
edge = sscanf(line(k+1:end), '%f')';
v1 = vindex(edge(1)+1);
v2 = vindex(edge(2)+1);
% create the edge
e = pg.graph.add_edge(v1, v2);
% create the edge data as a structure
% X Y T
% 3 4 5
ed.mean = edge(3:5);
% IXX IXY IYY ITT IXT IYT
% 6 7 8 9 10 11
ed.info = reshape(edge(toro), [3 3]);
% and attach it
pg.graph.setedata(e, ed);
case 'ROBOTLASER1'
if ~opt.laser
continue;
end
% laser records are associated with the immediately preceding VERTEX record
[laser,n] = sscanf(line(k+1:end), '%f');
nbeams = laser(8);
vd.theta = [0:nbeams-1] * laser(4) + laser(2);
vd.range = laser(9:8+nbeams)';
vd.time = laser(21+nbeams);
pg.graph.setvdata(v, vd);
nlaser = nlaser + 1;
otherwise
error('RTB:posegraph:badfile', 'Unexpected line <%s> in %s', line(1:k-1), filename);
end
end
elapsed = toc;
fclose(fp);
if toroformat
fprintf('loaded TORO/LAGO format file: %d nodes, %d edges in %.2f sec\n', pg.graph.n, pg.graph.ne, elapsed);
else
fprintf('loaded g2o format file: %d nodes, %d edges in %.2f sec\n', pg.graph.n, pg.graph.ne, elapsed);
if nlaser > 0
fprintf(' %d laser scans: %d beams, fov %g to %g deg, max range %g\n', ...
nlaser, nbeams, [laser(2) sum(laser(2:3))]*180/pi, laser(5) );
end
end
end
function [r, theta] = scan(pg, n)
vd = pg.graph.vdata(n);
r = vd.range;
theta = vd.theta;
end
function [X,Y] = scanxy(pg, n)
vd = pg.graph.vdata(n);
[x,y] = pol2cart(vd.theta, vd.range);
if nargout == 1
X = [x; y];
elseif nargout == 2
X = x; Y = y;
end
end
function plot_scan(pg, n)
for i=n(:)'
[x,y] = pg.scanxy(i);
plot(x, y, '.', 'MarkerSize', 10);
pause
end
end
function xyt = pose(pg, i)
xyt = pg.graph.coord(i);
end
function t = time(pg, n)
t = pg.graph.vdata(n).time;
end
function plot(pg, varargin)
pg.graph.plot(varargin{:});
xlabel('x')
ylabel('y')
grid on
end
function world = scanmap(pg, varargin)
opt.center = [75 50];
opt.ngrid = 3000;
opt.cellsize = 0.1;
pg = tb_optparse(opt, varargin, pg);
h = waitbar(0, 'rendering a map');
world = zeros(pg.ngrid, pg.ngrid, 'int32');
for i=1:1:pg.graph.n
if rem(i, 20) == 0
waitbar(i/pg.graph.n, h)
end
xy = pg.scanxy(i);
[r,theta] = pg.scan(i);
xy(:,r>40) = [];
xyt = pg.graph.coord(i);
xy = SE2(xyt) * xy;
% start of each ray
[x1,y1] = pg.w2g(xyt(1:2));
for s=1:numcols(xy)
% end of each ray
[x2,y2] = pg.w2g(xy(:,s));
% all cells along the ray
p = bresenham(x1, y1, x2, y2);
try
k = sub2ind(size(world), p(:,1), p(:,2));
k1 = k(1:end-1); k2 = k(end);
world(k1) = world(k1) - 1;
world(k2) = world(k2) + 1;
catch me
% come here if any point on the ray is outside the grid
% silently ignore it
end
end
end
close(h)
%idisp(world)
end
function [gx,gy] = w2g(pg, w)
dd = 0.10;
w = w(:) + pg.center(:);
g = round(w/pg.cellsize);
gx = g(1); gy = g(2);
end
function plot_occgrid(pg, w)
x = [1:numcols(w)]*pg.cellsize - pg.center(1);
y = [1:numrows(w)]*pg.cellsize - pg.center(2);
w(w<0) = -1;
w(w>0) = 1;
w=-w;
idisp(w, 'nogui', 'xydata', {x, y})
xlabel('x'); ylabel('y');
end
% This source code is part of the graph optimization package
% deveoped for the lectures of robotics2 at the University of Freiburg.
%
% Copyright (c) 2007 Giorgio Grisetti, Gian Diego Tipaldi
%
% It is licences under the Common Creative License,
% Attribution-NonCommercial-ShareAlike 3.0
%
% You are free:
% - to Share - to copy, distribute and transmit the work
% - to Remix - to adapt the work
%
% Under the following conditions:
%
% - Attribution. You must attribute the work in the manner specified
% by the author or licensor (but not in any way that suggests that
% they endorse you or your use of the work).
%
% - Noncommercial. You may not use this work for commercial purposes.
%
% - Share Alike. If you alter, transform, or build upon this work,
% you may distribute the resulting work only under the same or
% similar license to this one.
%
% Any of the above conditions can be waived if you get permission
% from the copyright holder. Nothing in this license impairs or
% restricts the author's moral rights.
%
% This software is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied
% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
% PURPOSE.
%ls-slam.m
%this file is released under the creative common license
%solves a graph-based slam problem via least squares
%vmeans: matrix containing the column vectors of the poses of the vertices
% the vertices are odrered such that vmeans[i] corresponds to the ith id
%eids: matrix containing the column vectors [idFrom, idTo]' of the ids of the vertices
% eids[k] corresponds to emeans[k] and einfs[k].
%emeans: matrix containing the column vectors of the poses of the edges
%einfs: 3d matrix containing the information matrices of the edges
% einfs(:,:,k) refers to the information matrix of the k-th edge.
%n: number of iterations
%newmeans: matrix containing the column vectors of the updated vertices positions
function g2 = optimize(pg, varargin)
opt.iterations = 10;
opt.animate = false;
opt.retain = false;
opt = tb_optparse(opt, varargin);
g2 = PGraph(pg.graph); % deep copy
eprev = Inf;
for i=1:opt.iterations
if opt.animate
if ~opt.retain
clf
end
g2.plot();
pause(0.5)
end
[vmeans,energy] = linearize_and_solve(g2);
g2.setcoord(vmeans);
if energy >= eprev
break;
end
eprev = energy;
end;
pg.graph = g2;
end
end % methods
end % classdef
%computes the taylor expansion of the error function of the k_th edge
%vmeans: vertices positions
%eids: edge ids
%emeans: edge means
%k: edge number
%e: e_k(x)
%A: d e_k(x) / d(x_i)
%B: d e_k(x) / d(x_j)
%function [e, A, B]=linear_factors(vmeans, eids, emeans, k)
function [e, A, B]=linear_factors(g, edge)
%extract the ids of the vertices connected by the kth edge
% id_i=eids(1,k);
% id_j=eids(2,k);
%extract the poses of the vertices and the mean of the edge
% v_i=vmeans(:,id_i);
% v_j=vmeans(:,id_j);
% z_ij=emeans(:,k);
v = g.vertices(edge);
v_i = g.coord(v(1));
v_j = g.coord(v(2));
z_ij = g.edata(edge).mean;
%compute the homoeneous transforms of the previous solutions
zt_ij=v2t(z_ij);
vt_i=v2t(v_i);
vt_j=v2t(v_j);
%compute the displacement between x_i and x_j
f_ij=(inv(vt_i)*vt_j);
%this below is too long to explain, to understand it derive it by hand
theta_i=v_i(3);
ti=v_i(1:2,1);
tj=v_j(1:2,1);
dt_ij=tj-ti;
si=sin(theta_i);
ci=cos(theta_i);
A= [-ci, -si, [-si, ci]*dt_ij; si, -ci, [-ci, -si]*dt_ij; 0, 0, -1 ];
B =[ ci, si, 0 ; -si, ci, 0 ; 0, 0, 1 ];
ztinv=inv(zt_ij);
e=t2v(ztinv*f_ij);
ztinv(1:2,3) = 0;
A=ztinv*A;
B=ztinv*B;
% %compute the homogeneous transforms of the previous solutions
% zt_ij=v2t(z_ij);
% vt_i=v2t(v_i);
% vt_j=v2t(v_j);
% % zt_ij = SE2(z_ij);
% % vt_i = SE2(v_i);
% % vt_j = SE2(v_j);
%
% %compute the displacement between x_i and x_j
% %f_ij=(inverse(vt_i)*vt_j);
% f_ij = vt_i.inv * vt_j;
%
% %this below is too long to explain, to understand it derive it by hand
% theta_i=v_i(3);
% ti=v_i(1:2);
% tj=v_j(1:2);
% dt_ij=tj-ti;
%
% si=sin(theta_i);
% ci=cos(theta_i);
%
% A= [-ci, -si, [-si, ci]*dt_ij; si, -ci, [-ci, -si]*dt_ij; 0, 0, -1 ];
% B =[ ci, si, 0 ; -si, ci, 0 ; 0, 0, 1 ];
%
% ztinv = inv(zt_ij);
% e = xyt(ztinv*f_ij);
% ztinv.t = 0;
% A = ztinv*A;
% B = ztinv*B;
end
%linearizes and solves one time the ls-slam problem specified by the input
%vmeans: vertices positions at the linearization point
%eids: edge ids
%emeans: edge means
%einfs: edge information matrices
%newmeans: new solution computed from the initial guess in vmeans
function [newmeans,energy] = linearize_and_solve(g)
tic
fprintf('solving');
% H and b are respectively the system matrix and the system vector
H=zeros(g.n*3,g.n*3);
b=zeros(g.n*3,1);
% this loop constructs the global system by accumulating in H and b the contributions
% of all edges (see lecture)
%for k=1:size(eids,2)
fprintf('.');
etotal = 0;
for edge = 1:g.ne
[e, A, B]=linear_factors(g, edge);
omega = g.edata(edge).info;
%compute the blocks of H^k
% not quite sure whey SE3 is being transposed, what does that mean?
b_i = -A'*omega*e;
b_j = -B'*omega*e;
H_ii = A'*omega*A;
H_ij = A'*omega*B;
H_jj = B'*omega*B;
v = g.vertices(edge);
id_i = v(1); id_j = v(2);
%accumulate the blocks in H and b
H((id_i-1)*3+1:id_i*3,(id_i-1)*3+1:id_i*3) = H((id_i-1)*3+1:id_i*3,(id_i-1)*3+1:id_i*3) + H_ii;
H((id_j-1)*3+1:id_j*3,(id_j-1)*3+1:id_j*3) = H((id_j-1)*3+1:id_j*3,(id_j-1)*3+1:id_j*3) + H_jj;
H((id_i-1)*3+1:id_i*3,(id_j-1)*3+1:id_j*3) = H((id_i-1)*3+1:id_i*3,(id_j-1)*3+1:id_j*3) + H_ij;
H((id_j-1)*3+1:id_j*3,(id_i-1)*3+1:id_i*3) = H((id_j-1)*3+1:id_j*3,(id_i-1)*3+1:id_i*3) + H_ij';
b((id_i-1)*3+1:id_i*3,1) = b((id_i-1)*3+1:id_i*3,1) + b_i;
b((id_j-1)*3+1:id_j*3,1) = b((id_j-1)*3+1:id_j*3,1) + b_j;
%NOTE on Matlab compatibility: note that we use the += operator which is octave specific
%using H=H+.... results in a tremendous overhead since the matrix would be entirely copied every time
%and the matrix is huge
etotal = etotal + e'*e;
end;
fprintf('.');
%note that the system (H b) is obtained only from
%relative constraints. H is not full rank.
%we solve the problem by anchoring the position of
%the the first vertex.
%this can be expressed by adding the equation
% deltax(1:3,1)=0;
%which is equivalent to the following
H(1:3,1:3) = H(1:3,1:3) + eye(3);
SH=sparse(H);
fprintf('.');
deltax=SH\b;
fprintf('.');
%split the increments in nice 3x1 vectors and sum them up to the original matrix
newmeans = g.coord()+reshape(deltax,3,g.n);
%normalize the angles between -PI and PI
for (i=1:size(newmeans,2))
s=sin(newmeans(3,i));
c=cos(newmeans(3,i));
newmeans(3,i)=atan2(s,c);
end
dt = toc;
fprintf('done in %.2g sec. Total cost %g \n', dt, etotal);
if nargout > 1
energy = etotal;
end
end
% This source code is part of the graph optimization package
% deveoped for the lectures of robotics2 at the University of Freiburg.
%
% Copyright (c) 2007 Giorgio Grisetti, Gian Diego Tipaldi
%
% It is licences under the Common Creative License,
% Attribution-NonCommercial-ShareAlike 3.0
%
% You are free:
% - to Share - to copy, distribute and transmit the work
% - to Remix - to adapt the work
%
% Under the following conditions:
%
% - Attribution. You must attribute the work in the manner specified
% by the author or licensor (but not in any way that suggests that
% they endorse you or your use of the work).
%
% - Noncommercial. You may not use this work for commercial purposes.
%
% - Share Alike. If you alter, transform, or build upon this work,
% you may distribute the resulting work only under the same or
% similar license to this one.
%
% Any of the above conditions can be waived if you get permission
% from the copyright holder. Nothing in this license impairs or
% restricts the author's moral rights.
%
% This software is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied
% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
% PURPOSE.
%computes the homogeneous transform matrix A of the pose vector v
function A=v2t(v)
c=cos(v(3));
s=sin(v(3));
A=[c, -s, v(1) ;
s, c, v(2) ;
0 0 1 ];
end
%computes the pose vector v from an homogeneous transform A
function v=t2v(A)
v(1:2, 1)=A(1:2,3);
v(3,1)=atan2(A(2,1),A(1,1));
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
jsingu.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/jsingu.m
| 1,404 |
utf_8
|
be339e3f968bb5c9a77a957fdf69e028
|
%JSINGU Show the linearly dependent joints in a Jacobian matrix
%
% JSINGU(J) displays the linear dependency of joints in a Jacobian matrix.
% This dependency indicates joint axes that are aligned and causes singularity.
%
% See also SerialLink.jacobn.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function jsingu(J)
% convert to row-echelon form
[R, jb] = rref(J);
R(abs(R) < 100*eps) = 0;
depcols = setdiff( 1:numcols(J), jb);
fprintf('%d linearly dependent joints:\n', length(depcols));
for d=depcols
fprintf(' q%d depends on: ', d)
for k=find(R(:,d))
fprintf('q%d ', k);
end
fprintf('\n');
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
ReedsShepp.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/ReedsShepp.m
| 9,770 |
utf_8
|
67ddf6852b22805e223af77aad5a75b0
|
% Reeds Shepp path planner sample code
%
% based on python code from Python Robotics by Atsushi Sakai(@Atsushi_twi)
%
% Peter 3/18
%
% Finds the shortest path between 2 configurations:
% - robot can move forward or backward
% - the robot turns at zero or maximum curvature
% - there are discontinuities in velocity and steering commands (cusps)
% to see what it does run
%
% >> ReedsShepp.test
%
% References::
% - Reeds, J. A.; Shepp, L. A.
% Optimal paths for a car that goes both forwards and backwards.
% Pacific J. Math. 145 (1990), no. 2, 367--393.
% https://projecteuclid.org/euclid.pjm/1102645450
% each path is described by a 3-letter word.
% the algorithm finds a bunch of possible paths, then chooses the shortest
% one. Each word is represented by a structure with fields:
% - word a 3-letter sequence drawn from the letters LRLS
% - L total path length
% - lengths a 3-vector of lengths, signed to indicate the direction of
% curvature
% - traj a cell array of 3xN matrices giving the path for each segment
% - dir the direction of travel: +1 or -1
%
% TODO: display all the solutions in one figure, as subplots
classdef ReedsShepp < handle
properties
best % the best path
words
maxc
end
methods
function obj = ReedsShepp(q0, qf, maxcurv, dl)
obj.maxc = maxcurv;
% return the word describing the shortest path
obj.words = generate_path(q0, qf, maxcurv);
if isempty(obj.words)
error('no path');
end
% find shortest path
[~,k] = min( [obj.words.L] );
obj.best = obj.words(k);
% add the trajectory
obj.best = generate_trajectories(obj.best, maxcurv, dl, q0);
end
function p = path(obj)
p = [obj.best.traj{:}]';
end
function show(obj)
for w=obj.words
fprintf('%s (%g): [%g %g %g]\n', w.word, w.L, w.lengths);
end
end
function plot(obj, varargin)
opt.circles = [];
opt.join = [];
opt = tb_optparse(opt, varargin);
if ~ishold
clf
end
hold on
word = obj.best;
for i=1:3
if word.dir(i) > 0
color = 'b';
else
color = 'r';
end
if i == 1
x = word.traj{i}(1,:);
y = word.traj{i}(2,:);
else
% ensure we join up the lines in the plot
x = [x(end) word.traj{i}(1,:)];
y = [y(end) word.traj{i}(2,:)];
end
if ~isempty(opt.join) && i<3
plot(x(end), y(end), opt.join{:});
end
if ~isempty(opt.circles)
T = SE2(word.traj{i}(:,1));
R = 1/obj.maxc;
c = T*[0; word.dir(i)*R];
plot_circle(c, R, opt.circles)
plot_point(c, 'k+')
end
plot(x, y, color, 'LineWidth', 2);
end
grid on; xlabel('X'); ylabel('Y')
hold off
axis equal
title('Reeds-Shepp path');
end
function s = char(obj)
s = '';
s = strvcat(s, sprintf('Reeds-Shepp path: %s, length %f', obj.best.word, obj.best.L));
s = strvcat(s, sprintf(' segment lengths: %f %f %f', obj.best.lengths));
end
function display(obj)
disp( char(obj) );
end
end
methods(Static)
function test()
maxcurv = 1;
dl = 0.05;
q0 = [0 0 pi/4]'; qf = [0 0 pi]';
p = ReedsShepp(q0, qf, maxcurv, dl)
p.plot('circles', 'k--', 'join', {'Marker', 'o', 'MarkerFaceColor', 'k'});
end
end
end % class ReedsShepp
function out = generate_trajectories(word, maxc, d, q0)
% initialize the configuration
p0 = q0;
% output struct is same as input struct, but we will add:
% - a cell array of trajectories
% - a vector of directions -1 or +1
out = word;
for i=1:3
m = word.word(i);
l = word.lengths(i);
x = [0:d:abs(l) abs(l)];
p = pathseg(x, sign(l), m, maxc, p0);
% add new fields to the struct
if i == 1
out.traj{i} = p;
else
% for subsequent segments skip the first point, same as last
% point of previous segment
out.traj{i} = p(:,2:end);
end
out.dir(i) = sign(l);
% initial state for next segment is last state of this segment
p0 = p(:,end);
end
end
function q = pathseg(l, dir, m, maxc, p0)
q0 = p0(:);
switch m
case 'S'
f = @(t,q) dir*[cos(q(3)), sin(q(3)), 0]';
case {'L', 'R'}
f = @(t,q) dir*[cos(q(3)), sin(q(3)), dir*maxc]';
end
[t,q] = ode45(f, l, q0);
q = q'; % points are column vectors
end
function words = generate_path(q0, q1, maxc)
% return a list of all possible words
q0 = q0(:); q1 = q1(:);
dq = q1 - q0;
dth = dq(3);
xy = rot2(q0(3))' * dq(1:2) * maxc;
x = xy(1); y = xy(2);
words = [];
words = SCS(x, y, dth, words);
words = CSC(x, y, dth, words);
words = CCC(x, y, dth, words);
% account for non-unit curvature
for i=1:numel(words)
words(i).lengths = words(i).lengths / maxc;
words(i).L = words(i).L / maxc;
end
end
%%
function owords = SCS(x, y, phi, words)
words = SLS([ x y phi], 1, 'SLS', words);
words = SLS([ x -y -phi], 1, 'SRS', words);
owords = words;
end
function owords = CCC(x, y, phi, words)
words = LRL([ x y phi], 1, 'LRL', words);
words = LRL([-x y -phi], -1, 'LRL', words);
words = LRL([ x -y -phi], 1, 'RLR', words);
words = LRL([-x -y phi], -1, 'RLR', words);
% backwards
xb = x * cos(phi) + y * sin(phi);
yb = x * sin(phi) - y * cos(phi);
flip = [0 1 0; 1 0 0; 0 0 1]; % flip u and v
words = LRL([ xb yb phi], flip, 'LRL', words);
words = LRL([-xb yb -phi], -flip, 'LRL', words);
words = LRL([ xb -yb -phi], flip, 'RLR', words);
words = LRL([-xb -yb phi], -flip, 'RLR', words);
owords = words;
end
function owords = CSC(x, y, phi, words)
words = LSL([ x y phi], 1, 'LSL', words);
words = LSL([-x y -phi], -1, 'LSL', words);
words = LSL([ x -y -phi], 1, 'RSR', words);
words = LSL([-x -y phi], -1, 'RSR', words);
words = LSR([ x y phi], 1, 'LSR', words);
words = LSR([-x y -phi], -1, 'LSR', words);
words = LSR([ x -y -phi], 1, 'RSL', words);
words = LSR([-x -y phi], -1, 'RSL', words);
owords = words;
end
% requires LSL, LSR, SLS, LRL
%%
function owords = SLS(q, sign, word, words)
x = q(1); y = q(2); phi = mod(q(3), 2*pi);
if y > 0.0 && phi > 0.0 && phi < pi * 0.99
xd = - y / tan(phi) + x;
t = xd - tan(phi / 2.0);
u = phi;
v = norm( [(x - xd) y]) - tan(phi / 2.0);
owords = addpath(words, sign*[t, u, v], word);
elseif y < 0.0 && phi > 0.0 && phi < pi * 0.99
xd = - y / tan(phi) + x;
t = xd - tan(phi / 2.0);
u = phi;
v = -norm([(x - xd) y]) - tan(phi / 2.0);
owords = addpath(words, sign*[t, u, v], word);
else
owords = words;
end
end
function owords = LSL(q, sign, word, words)
x = q(1); y = q(2); phi = mod(q(3), 2*pi);
[t,u] = cart2pol(x - sin(phi), y - 1.0 + cos(phi));
if t >= 0.0
v = angdiff(phi - t);
if v >= 0.0
owords = addpath(words, sign*[t, u, v], word);
return
end
end
owords = words;
end
function owords = LRL(q, sign, word, words)
x = q(1); y = q(2); phi = mod(q(3), 2*pi);
[t1,u1] = cart2pol(x - sin(phi), y - 1.0 + cos(phi));
if u1 <= 4.0
u = -2.0 * asin(0.25 * u1);
t = angdiff(t1 + 0.5 * u + pi);
v = angdiff(phi - t + u);
if t >= 0.0 && u <= 0.0
owords = addpath(words, [t, u, v]*sign, word);
return
end
end
owords = words;
end
function owords = LSR(q, sign, word, words)
x = q(1); y = q(2); phi = mod(q(3), 2*pi);
[t1,u1] = cart2pol(x + sin(phi), y - 1.0 - cos(phi));
u1 = u1^2;
if u1 >= 4.0
u = sqrt(u1 - 4.0);
theta = atan2(2.0, u);
t = angdiff(t1 + theta);
v = angdiff(t - phi);
if t >= 0.0 && v >= 0.0
owords = addpath(words, sign*[t, u, v], word);
return
end
end
owords = words;
end
%%
function owords = addpath(words, lengths, ctypes)
% create a struct to represent this segment
word.word = ctypes;
word.lengths = lengths;
% check same path exist
for p = words
if strcmp(p.word, word.word)
if sum(p.lengths) - sum(word.lengths) <= 0.01
owords = words;
return %not insert path
end
end
end
word.L = sum(abs(lengths));
% long enough to add?
if word.L >= 0.01
owords = [words word];
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
purepursuit.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/purepursuit.m
| 2,081 |
utf_8
|
2e538c81d09c6a5cac6d21d0139799dc
|
%PUREPURSUIT Find pure pursuit goal
%
% P = PUREPURSUIT(CP, R, PATH) is the current pursuit point (2x1) for a robot at
% location CP (2x1) following a PATH (Nx2). The pursuit point is the
% closest point along the path that is a distance >= R from the current
% point CP.
%
% Reference::
% - A review of some pure-pursuit based tracking techniques for control of
% autonomous vehicle, Samuel etal., Int. J. Computer Applications, Feb 2016
% - Steering Control of an Autonomous Ground Vehicle with Application to
% the DARPA Urban Challenge, Stefan F. Campbell, Masters thesis, MIT, 2007.
%
% See also Navigation.
% Copyright (C) 1993-2019, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function pstar = purepursuit(cp, R, traj)
cp = cp(:)'; % ensure a row vector
% find closest point on the path to current point
d = colnorm((traj-cp)'); % rely on implicit expansion
[~,i] = min(d);
% find all points on the path at least R away
k = find(d(i+1:end) >= R); % find all points beyond horizon
if isempty(k)
% no such points, we must be near the end, goal is the end
pstar = traj(end,:);
else
% many such points, take the first one
k = k(1); % first point beyond horizon
j = i+k-1; % index into traj array
pstar = traj(j,:);
%[j traj(j,:) norm(pstar-cp)]
end
end
|
github
|
RobinAmsters/GT_mobile_robotics-master
|
joy2tr.m
|
.m
|
GT_mobile_robotics-master/common/rvctools/robot/joy2tr.m
| 2,953 |
utf_8
|
fb046603cd51e0ad017bba56b43b5b8c
|
%JOY2TR Update transform from joystick
%
% T = JOY2TR(T, OPTIONS) updates the SE(3) homogeneous transform (4x4)
% according to spatial velocities sourced from a connected joystick device.
%
% Options::
% 'delay',D Pause for D seconds after reading (default 0.1)
% 'scale',S A 2-vector which scales joystick translational and
% rotational to rates (default [0.5m/s, 0.25rad/s])
% 'world' Joystick motion is in the world frame
% 'tool' Joystick motion is in the tool frame (default)
% 'rotate',R Index of the button used to enable rotation (default 7)
%
% Notes::
% - Joystick axes 0,1,3 map to X,Y,Z or R,P,Y motion.
% - A joystick button enables the mapping to translation OR rotation.
% - A 'delay' of zero means no pause
% - If 'delay' is non-zero 'scale' maps full scale to m/s or rad/s.
% - If 'delay' is zero 'scale' maps full scale to m/sample or rad/sample.
%
% See also joystick.
% Copyright (C) 1993-2017, by Peter I. Corke
%
% This file is part of The Robotics Toolbox for MATLAB (RTB).
%
% RTB is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% RTB is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Leser General Public License
% along with RTB. If not, see <http://www.gnu.org/licenses/>.
%
% http://www.petercorke.com
function Tout = joy2tr(T, varargin)
% parse the options
opt.delay = 0.1;
opt.rotate = 7;
opt.scale = [0.5 0.25];
opt.frame = {'tool', 'world'};
opt.min = 0.006;
opt = tb_optparse(opt, varargin);
% get the raw joystick output
[j,b] = joystick();
% update a 6-vector of translational and rotational velocities
vel = zeros(1,6);
if b(7) == 0
% translation mode
vel(1:2) = j(1:2);
vel(3) = j(4);
else
% rotation mode
vel(4:5) = j(1:2);
vel(6) = j(4);
end
% values below threshold are set to zero
vel(abs(vel) < opt.min) = 0;
% apply scaling factors
scale = opt.scale;
if opt.delay > 0
% normalize scaling factors by time
pause(opt.delay);
scale = scale * opt.delay;
end
vel(1:3) = vel(1:3) * scale(1);
vel(4:6) = vel(4:6) * scale(2);
% compute the incremental motion
dT = transl(vel(1:3)) * rpy2tr(vel(4:6));
% and apply it to the input transform
switch opt.frame
case 'tool'
Tout = T * dT;
case 'world'
Tout = dT * T;
end
% normalize just to be safe
Tout = trnorm(Tout);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.