74 Commits

Author SHA1 Message Date
c47b7229ba a 2026-01-08 19:35:10 -08:00
02189baaab unit test fixes 2026-01-07 12:41:22 -08:00
af6a0447a8 added z component to GA with constant partition 2026-01-07 11:43:14 -08:00
62e015da42 removed extra file 2026-01-07 09:42:09 -08:00
ddecf63d68 added h plots 2026-01-06 21:57:30 -08:00
591430ad8a unit test updates 2026-01-06 20:22:28 -08:00
1e7540226e fixed and verified communications constraint 2026-01-06 12:24:42 -08:00
4fe897455d fixed lesser neighbor algorithm 2026-01-06 10:57:56 -08:00
7d1154d028 cleaned up todo notes 2026-01-02 13:30:40 -08:00
16673a437e project housekeeping 2026-01-02 13:26:35 -08:00
6403e7cbcc removed options for guidance models other than GA 2026-01-01 17:26:15 -08:00
066acd0949 removed collision geometry label input 2026-01-01 17:22:17 -08:00
8dfa0c337a removed agent label input at initialization 2026-01-01 17:16:11 -08:00
492c5c2140 nixed agent index property 2026-01-01 17:02:36 -08:00
06f6af1511 added silent LNA test case 2026-01-01 16:27:28 -08:00
c59b96f547 added agent position trail to plot 2026-01-01 16:06:19 -08:00
4735c2b77b debugging comms constraints 2025-12-31 20:54:01 -08:00
d6a9c4ac06 Added lesser neighbor algorithm and constraints 2025-12-31 19:19:36 -08:00
fa8da50db1 test updates 2025-12-29 17:35:38 -08:00
61cdb96102 added communications geometry 2025-12-27 16:14:44 -08:00
1d11ac4e90 made no plotting flag for better performance and unit testing 2025-12-24 16:20:57 -08:00
843e5ba574 cleanup 2025-12-24 16:01:31 -08:00
50eaad9504 fixed comms LOS obstruction by obstacles 2025-12-24 16:00:42 -08:00
14e372ae55 added domain constraints 2025-12-23 17:22:34 -08:00
8315b6c511 obstacle avoidance 2025-12-23 14:57:13 -08:00
4fa942564a added basic obstacle avoidance test case 2025-12-23 12:37:53 -08:00
6632c9885d fixed minimum agent altitude initial condition 2025-12-23 12:13:15 -08:00
1fa76c7023 added minimum altitude constraint as obstacle 2025-12-23 12:02:40 -08:00
33036c95fd made video writing optional for performance benefits 2025-12-23 11:50:26 -08:00
557d8fe63c t 2025-12-13 12:18:48 -08:00
2cd1bb8659 CA verifying test 2025-12-05 17:52:53 -08:00
06882d2f30 fixed abuse of memory 2025-12-05 17:28:34 -08:00
95ea19e546 fixed guidance only pulling things towards the middle and added CA QP CBF code 2025-12-05 16:04:02 -08:00
96c91c3988 added collision barrier function and gradient 2025-12-04 18:24:49 -08:00
d70781fadc Merge branch 'main' into gradient-ascent 2025-12-04 16:10:13 -08:00
a688e9c285 cleanup 2025-12-04 15:24:11 -08:00
d30fd9ccaa fixed performance plot after 50th timestep 2025-12-01 22:59:35 -08:00
bdd018e566 refactored performance plot data storage 2025-12-01 22:59:35 -08:00
28a6bfe3de gradient ascent works now? 2025-12-01 22:59:35 -08:00
c92ef143d1 added debug visualization for agent GA 2025-12-01 22:59:35 -08:00
6d16dfe974 flawed GA implementation 2025-12-01 22:59:35 -08:00
1e0db2a46c removed early exit from main loop 2025-12-01 22:59:35 -08:00
f9aa2eb9d4 fixed performance plot after 50th timestep 2025-12-01 22:58:38 -08:00
f296fd2803 refactored performance plot data storage 2025-11-30 22:32:17 -08:00
7c87458b66 gradient ascent works now? 2025-11-30 19:08:15 -08:00
4e0f213d0c added debug visualization for agent GA 2025-11-30 11:00:39 -08:00
f9f070e2d0 flawed GA implementation 2025-11-30 09:52:17 -08:00
352d2ed1de removed early exit from main loop 2025-11-25 13:09:33 -08:00
59805dff72 added early exit from main loop for semistable final states 2025-11-25 09:07:02 -08:00
a8380985e1 better sigmoid sensor unit testing 2025-11-25 09:07:02 -08:00
55b69d4e33 added performance plot legend, rolling normalization 2025-11-25 09:07:02 -08:00
779d7d2cc6 fixed issues in sigmoid sensor model causing inverted response (annular partitions) 2025-11-25 09:07:02 -08:00
58d009c8fc fixed initial altitude range 2025-11-25 09:07:02 -08:00
b62f0f6410 better random agent placement with respect to sensor capabilities 2025-11-18 09:08:12 -08:00
fe5f3bb2be cleaned up plotting 2025-11-18 09:08:12 -08:00
35b15db5d3 Added plotting of sigmoid sensor parameters 2025-11-18 09:08:12 -08:00
f50e3e2832 started unit test for sigmoid sensor performance fcns 2025-11-18 09:08:12 -08:00
e53b721f34 started performance plot 2025-11-18 09:08:12 -08:00
db20f11ea8 added sensor performance metric 2025-11-18 09:08:12 -08:00
86342c4572 updated plotting org 2025-11-18 09:08:12 -08:00
b9a2a83ac6 added randomness to sensor parameters 2025-11-18 09:08:12 -08:00
9dbd29849f cleaned up randomly generated obstacle collision code 2025-11-18 09:08:12 -08:00
12dbde7a02 cleaned up obstacle generation 2025-11-18 09:08:12 -08:00
c9ac9d7725 adjusted partitioning to allow non-assignment 2025-11-18 09:08:12 -08:00
afa5d79c1d refactored sensing objective into domain, random inits 2025-11-18 09:08:12 -08:00
e0f365b21b reorganized code into separate files 2025-11-18 09:08:12 -08:00
4363914215 fixed cone radius and sigmoid sensor test parameters 2025-11-18 09:08:12 -08:00
855b28b066 added large factor to sigmoid sensor performance calculation 2025-11-18 09:08:12 -08:00
79783d754b added cone geometry, implemented fov visualization 2025-11-13 09:52:32 -08:00
1592e3321e partitioning introduced to main loop 2025-11-13 09:52:32 -08:00
792ca1042c implemented partitioning 2025-11-13 09:52:32 -08:00
4fc8d98e9d potential videowriter compat fix 2025-11-13 09:52:32 -08:00
8103591b7c refactored agent sensing and guidance 2025-11-13 09:52:32 -08:00
c21ce3a35d updated plotting 2025-11-13 09:52:32 -08:00
278 changed files with 3490 additions and 1588 deletions

9
.gitignore vendored
View File

@@ -40,4 +40,11 @@ codegen/
*.sbproj.bak *.sbproj.bak
# Sandbox contents # Sandbox contents
sandbox/* sandbox/*
# Videos
*.mp4
*.avi
# Figures
*.fig

45
@agent/agent.m Normal file
View File

@@ -0,0 +1,45 @@
classdef agent
properties (SetAccess = public, GetAccess = public)
% Identifiers
label = "";
% Sensor
sensorModel;
sensingLength = 0.05; % length parameter used by sensing function
% State
lastPos = NaN(1, 3); % position from previous timestep
pos = NaN(1, 3); % current position
vel = NaN(1, 3); % current velocity
pan = NaN; % pan angle
tilt = NaN; % tilt angle
% Collision
collisionGeometry;
barrierFunction;
dBarrierFunction;
% FOV cone
fovGeometry;
% Communication
comRange = NaN;
commsGeometry = spherical;
lesserNeighbors = [];
performance = 0;
% Plotting
scatterPoints;
debug = false;
debugFig;
plotCommsGeometry = true;
end
methods (Access = public)
[obj] = initialize(obj, pos, vel, pan, tilt, collisionGeometry, sensorModel, guidanceModel, comRange, index, label);
[obj] = run(obj, domain, partitioning, t, index);
[obj, f] = plot(obj, ind, f);
updatePlots(obj);
end
end

80
@agent/initialize.m Normal file
View File

@@ -0,0 +1,80 @@
function obj = initialize(obj, pos, vel, pan, tilt, collisionGeometry, sensorModel, comRange, label, debug, plotCommsGeometry)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
pos (1, 3) double;
vel (1, 3) double;
pan (1, 1) double;
tilt (1, 1) double;
collisionGeometry (1, 1) {mustBeGeometry};
sensorModel (1, 1) {mustBeSensor};
comRange (1, 1) double;
label (1, 1) string = "";
debug (1, 1) logical = false;
plotCommsGeometry (1, 1) logical = false;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'agent')};
end
obj.pos = pos;
obj.vel = vel;
obj.pan = pan;
obj.tilt = tilt;
obj.collisionGeometry = collisionGeometry;
obj.sensorModel = sensorModel;
obj.label = label;
obj.debug = debug;
obj.plotCommsGeometry = plotCommsGeometry;
% Add spherical geometry based on com range
obj.commsGeometry = obj.commsGeometry.initialize(obj.pos, comRange, REGION_TYPE.COMMS, sprintf("%s Comms Geometry", obj.label));
if obj.debug
obj.debugFig = figure;
tiledlayout(obj.debugFig, "TileSpacing", "tight", "Padding", "compact");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Objective");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Sensor Performance");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Gradient Objective");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Gradient Sensor Performance");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Sensor Performance x Gradient Objective");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Gradient Sensor Performance x Objective");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Agent Performance (C)");
nexttile;
axes(obj.debugFig.Children(1).Children(1));
axis(obj.debugFig.Children(1).Children(1), "image");
xlabel(obj.debugFig.Children(1).Children(1), "X"); ylabel(obj.debugFig.Children(1).Children(1), "Y");
title(obj.debugFig.Children(1).Children(1), "Gradient Agent Performance (del C)");
end
% Initialize FOV cone
obj.fovGeometry = cone;
obj.fovGeometry = obj.fovGeometry.initialize([obj.pos(1:2), 0], tand(obj.sensorModel.alphaTilt) * obj.pos(3), obj.pos(3), REGION_TYPE.FOV, sprintf("%s FOV", obj.label));
end

40
@agent/plot.m Normal file
View File

@@ -0,0 +1,40 @@
function [obj, f] = plot(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'agent')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Plot points representing the agent position
hold(f.Children(1).Children(end), "on");
o = scatter3(f.Children(1).Children(end), obj.pos(1), obj.pos(2), obj.pos(3), 'filled', 'ko', 'SizeData', 25);
hold(f.Children(1).Children(end), "off");
% Check if this is a tiled layout figure
if strcmp(f.Children(1).Type, 'tiledlayout')
% Add to other perspectives
o = [o; copyobj(o(1), f.Children(1).Children(2))];
o = [o; copyobj(o(1), f.Children(1).Children(3))];
o = [o; copyobj(o(1), f.Children(1).Children(4))];
end
obj.scatterPoints = o;
% Plot collision geometry
[obj.collisionGeometry, f] = obj.collisionGeometry.plotWireframe(ind, f);
% Plot communications geometry
if obj.plotCommsGeometry
[obj.commsGeometry, f] = obj.commsGeometry.plotWireframe(ind, f);
end
% Plot FOV geometry
[obj.fovGeometry, f] = obj.fovGeometry.plot(ind, f);
end

155
@agent/run.m Normal file
View File

@@ -0,0 +1,155 @@
function obj = run(obj, domain, partitioning, t, index)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
domain (1, 1) {mustBeGeometry};
partitioning (:, :) double;
t (1, 1) double;
index (1, 1) double;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'agent')};
end
% Collect objective function values across partition
partitionMask = partitioning == index;
objectiveValues = domain.objective.values(partitionMask); % f(omega) on W_n
% Compute sensor performance across partition
maskedX = domain.objective.X(partitionMask);
maskedY = domain.objective.Y(partitionMask);
zFactor = 1;
sensorValues = obj.sensorModel.sensorPerformance(obj.pos, obj.pan, obj.tilt, [maskedX, maskedY, zeros(size(maskedX))]); % S_n(omega, P_n) on W_n
sensorValuesLower = obj.sensorModel.sensorPerformance(obj.pos - [0, 0, zFactor * domain.objective.discretizationStep], obj.pan, obj.tilt, [maskedX, maskedY, zeros(size(maskedX))]); % S_n(omega, P_n - [0, 0, z]) on W_n
sensorValuesHigher = obj.sensorModel.sensorPerformance(obj.pos + [0, 0, zFactor * domain.objective.discretizationStep], obj.pan, obj.tilt, [maskedX, maskedY, zeros(size(maskedX))]); % S_n(omega, P_n - [0, 0, z]) on W_n
% Put the values back into the form of the partition to enable basic operations on this data
F = NaN(size(partitionMask));
F(partitionMask) = objectiveValues;
S = NaN(size(partitionMask));
Slower = S;
Shigher = S;
S(partitionMask) = sensorValues;
Slower(partitionMask) = sensorValuesLower;
Shigher(partitionMask) = sensorValuesHigher;
% Find agent's performance
C = S .* F;
obj.performance = [obj.performance, sum(C(~isnan(C)))]; % at current Z only
C = cat(3, Shigher, S, Slower) .* F;
% Compute gradient on agent's performance
[gradCX, gradCY, gradCZ] = gradient(C, domain.objective.discretizationStep); % grad C
gradC = cat(4, gradCX, gradCY, gradCZ);
nGradC = vecnorm(gradC, 2, 4);
if obj.debug
% Compute additional component-level values for diagnosing issues
[gradSensorPerformanceX, gradSensorPerformanceY] = gradient(S, domain.objective.discretizationStep); % grad S_n
[gradObjectiveX, gradObjectiveY] = gradient(F, domain.objective.discretizationStep); % grad f
gradS = cat(3, gradSensorPerformanceX, gradSensorPerformanceY, zeros(size(gradSensorPerformanceX))); % grad S_n
gradF = cat(3, gradObjectiveX, gradObjectiveY, zeros(size(gradObjectiveX))); % grad f
ii = 8;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), F./max(F, [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), S./max(S, [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), vecnorm(gradF, 2, 3)./max(vecnorm(gradF, 2, 3), [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), vecnorm(gradS, 2, 3)./max(vecnorm(gradS, 2, 3), [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), S .* vecnorm(gradF, 2, 3)./max(vecnorm(gradF, 2, 3), [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), F .* vecnorm(gradS, 2, 3)./max(vecnorm(gradS, 2, 3), [], 'all')./(max(F .* vecnorm(gradS, 2, 3)./max(vecnorm(gradS, 2, 3), [], 'all'))));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), C./max(C, [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
ii = ii - 1;
hold(obj.debugFig.Children(1).Children(ii), "on");
cla(obj.debugFig.Children(1).Children(ii));
imagesc(obj.debugFig.Children(1).Children(ii), nGradC./max(nGradC, [], 'all'));
hold(obj.debugFig.Children(1).Children(ii), "off");
[x, y] = find(nGradC == max(nGradC, [], "all"));
% just pick one
r = randi([1, size(x, 1)]);
x = x(r); y = y(r);
% switch them
temp = x;
x = y;
y = temp;
% find objective location in discrete domain
[~, xIdx] = find(domain.objective.groundPos(1) == domain.objective.X);
xIdx = unique(xIdx);
[yIdx, ~] = find(domain.objective.groundPos(2) == domain.objective.Y);
yIdx = unique(yIdx);
for ii = 8:-1:1
hold(obj.debugFig.Children(1).Children(ii), "on");
% plot GA selection
scatter(obj.debugFig.Children(1).Children(ii), x, y, 'go');
scatter(obj.debugFig.Children(1).Children(ii), x, y, 'g+');
% plot objective center
scatter(obj.debugFig.Children(1).Children(ii), xIdx, yIdx, 'ro');
scatter(obj.debugFig.Children(1).Children(ii), xIdx, yIdx, 'r+');
hold(obj.debugFig.Children(1).Children(ii), "off");
end
end
% return now if there is no data to work with, and do not move
if all(isnan(nGradC), 'all')
return;
end
% Use largest grad(C) value to find the direction of the next position
[xNextIdx, yNextIdx, zNextIdx] = ind2sub(size(nGradC), find(nGradC == max(nGradC, [], 'all')));
% switch them
temp = xNextIdx;
xNextIdx = yNextIdx;
yNextIdx = temp;
roundingScale = 10^-log10(domain.objective.discretizationStep);
zKey = zFactor * [1; 0; -1];
pNext = [floor(roundingScale .* mean(unique(domain.objective.X(:, xNextIdx))))./roundingScale, floor(roundingScale .* mean(unique(domain.objective.Y(yNextIdx, :))))./roundingScale, obj.pos(3) + zKey(zNextIdx)]; % have to do some unfortunate rounding here sometimes
% Determine next position
vDir = (pNext - obj.pos)./norm(pNext - obj.pos, 2);
rate = 0.1 - 0.0004 * t; % slow down as you get closer, coming to a stop by the end
nextPos = obj.pos + vDir * rate;
% Move to next position
obj.lastPos = obj.pos;
obj.pos = nextPos;
% Reinitialize collision geometry in the new position
d = obj.pos - obj.collisionGeometry.center;
if isa(obj.collisionGeometry, 'rectangularPrism')
obj.collisionGeometry = obj.collisionGeometry.initialize([obj.collisionGeometry.minCorner; obj.collisionGeometry.maxCorner] + d, obj.collisionGeometry.tag, obj.collisionGeometry.label);
elseif isa(obj.collisionGeometry, 'spherical')
obj.collisionGeometry = obj.collisionGeometry.initialize(obj.collisionGeometry.center + d, obj.collisionGeometry.radius, obj.collisionGeometry.tag, obj.collisionGeometry.label);
else
error("?");
end
end

46
@agent/updatePlots.m Normal file
View File

@@ -0,0 +1,46 @@
function updatePlots(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
end
arguments (Output)
end
% Scatterplot point positions
for ii = 1:size(obj.scatterPoints, 1)
obj.scatterPoints(ii).XData = obj.pos(1);
obj.scatterPoints(ii).YData = obj.pos(2);
obj.scatterPoints(ii).ZData = obj.pos(3);
end
% Find change in agent position since last timestep
deltaPos = obj.pos - obj.lastPos;
% Collision geometry edges
for jj = 1:size(obj.collisionGeometry.lines, 2)
% Update plotting
for ii = 1:size(obj.collisionGeometry.lines(:, jj), 1)
obj.collisionGeometry.lines(ii, jj).XData = obj.collisionGeometry.lines(ii, jj).XData + deltaPos(1);
obj.collisionGeometry.lines(ii, jj).YData = obj.collisionGeometry.lines(ii, jj).YData + deltaPos(2);
obj.collisionGeometry.lines(ii, jj).ZData = obj.collisionGeometry.lines(ii, jj).ZData + deltaPos(3);
end
end
% Communications geometry edges
if obj.plotCommsGeometry
for jj = 1:size(obj.commsGeometry.lines, 2)
for ii = 1:size(obj.collisionGeometry.lines(:, jj), 1)
obj.collisionGeometry.lines(ii, jj).XData = obj.collisionGeometry.lines(ii, jj).XData + deltaPos(1);
obj.collisionGeometry.lines(ii, jj).YData = obj.collisionGeometry.lines(ii, jj).YData + deltaPos(2);
obj.collisionGeometry.lines(ii, jj).ZData = obj.collisionGeometry.lines(ii, jj).ZData + deltaPos(3);
end
end
end
% Update FOV geometry surfaces
for jj = 1:size(obj.fovGeometry.surface, 2)
% Update each plot
obj.fovGeometry.surface(jj).XData = obj.fovGeometry.surface(jj).XData + deltaPos(1);
obj.fovGeometry.surface(jj).YData = obj.fovGeometry.surface(jj).YData + deltaPos(2);
obj.fovGeometry.surface(jj).ZData = obj.fovGeometry.surface(jj).ZData + deltaPos(3);
end
end

153
@miSim/constrainMotion.m Normal file
View File

@@ -0,0 +1,153 @@
function [obj] = constrainMotion(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
if size(obj.agents, 1) < 2
nAAPairs = 0;
else
nAAPairs = nchoosek(size(obj.agents, 1), 2); % unique agent/agent pairs
end
agents = [obj.agents{:}];
v = reshape(([agents.pos] - [agents.lastPos])./obj.timestep, 3, size(obj.agents, 1))';
% Initialize QP based on number of agents and obstacles
nAOPairs = size(obj.agents, 1) * size(obj.obstacles, 1); % unique agent/obstacle pairs
nADPairs = size(obj.agents, 1) * 5; % agents x (4 walls + 1 ceiling)
nLNAPairs = sum(obj.constraintAdjacencyMatrix, 'all') - size(obj.agents, 1);
total = nAAPairs + nAOPairs + nADPairs + nLNAPairs;
kk = 1;
A = zeros(total, 3 * size(obj.agents, 1));
b = zeros(total, 1);
% Set up collision avoidance constraints
h = NaN(size(obj.agents, 1));
h(logical(eye(size(obj.agents, 1)))) = 0; % self value is 0
for ii = 1:(size(obj.agents, 1) - 1)
for jj = (ii + 1):size(obj.agents, 1)
h(ii, jj) = norm(agents(ii).pos - agents(jj).pos)^2 - (agents(ii).collisionGeometry.radius + agents(jj).collisionGeometry.radius)^2;
h(jj, ii) = h(ii, jj);
A(kk, (3 * ii - 2):(3 * ii)) = -2 * (agents(ii).pos - agents(jj).pos);
A(kk, (3 * jj - 2):(3 * jj)) = -A(kk, (3 * ii - 2):(3 * ii));
b(kk) = obj.barrierGain * h(ii, jj)^3;
kk = kk + 1;
end
end
hObs = NaN(size(obj.agents, 1), size(obj.obstacles, 1));
% Set up obstacle avoidance constraints
for ii = 1:size(obj.agents, 1)
for jj = 1:size(obj.obstacles, 1)
% find closest position to agent on/in obstacle
cPos = obj.obstacles{jj}.closestToPoint(agents(ii).pos);
hObs(ii, jj) = dot(agents(ii).pos - cPos, agents(ii).pos - cPos) - agents(ii).collisionGeometry.radius^2;
A(kk, (3 * ii - 2):(3 * ii)) = -2 * (agents(ii).pos - cPos);
b(kk) = obj.barrierGain * hObs(ii, jj)^3;
kk = kk + 1;
end
end
% Set up domain constraints (walls and ceiling only)
% Floor constraint is implicit with an obstacle corresponding to the
% minimum allowed altitude, but I included it anyways
for ii = 1:size(obj.agents, 1)
% X minimum
h_xMin = (agents(ii).pos(1) - obj.domain.minCorner(1)) - agents(ii).collisionGeometry.radius;
A(kk, (3 * ii - 2):(3 * ii)) = [-1, 0, 0];
b(kk) = obj.barrierGain * h_xMin^3;
kk = kk + 1;
% X maximum
h_xMax = (obj.domain.maxCorner(1) - agents(ii).pos(1)) - agents(ii).collisionGeometry.radius;
A(kk, (3 * ii - 2):(3 * ii)) = [1, 0, 0];
b(kk) = obj.barrierGain * h_xMax^3;
kk = kk + 1;
% Y minimum
h_yMin = (agents(ii).pos(2) - obj.domain.minCorner(2)) - agents(ii).collisionGeometry.radius;
A(kk, (3 * ii - 2):(3 * ii)) = [0, -1, 0];
b(kk) = obj.barrierGain * h_yMin^3;
kk = kk + 1;
% Y maximum
h_yMax = (obj.domain.maxCorner(2) - agents(ii).pos(2)) - agents(ii).collisionGeometry.radius;
A(kk, (3 * ii - 2):(3 * ii)) = [0, 1, 0];
b(kk) = obj.barrierGain * h_yMax^3;
kk = kk + 1;
% Z minimum
h_zMin = (agents(ii).pos(3) - obj.domain.minCorner(3)) - agents(ii).collisionGeometry.radius;
A(kk, (3 * ii - 2):(3 * ii)) = [0, 0, -1];
b(kk) = obj.barrierGain * h_zMin^3;
kk = kk + 1;
% Z maximum
h_zMax = (obj.domain.maxCorner(2) - agents(ii).pos(2)) - agents(ii).collisionGeometry.radius;
A(kk, (3 * ii - 2):(3 * ii)) = [0, 0, 1];
b(kk) = obj.barrierGain * h_zMax^3;
kk = kk + 1;
end
% Save off h function values (ignoring network constraints which may evolve in time)
obj.h(:, obj.timestepIndex) = [h(triu(true(size(obj.agents, 1)), 1)); reshape(hObs, [], 1); h_xMin; h_xMax; h_yMin; h_yMax; h_zMin; h_zMax;];
% Add communication network constraints
hComms = NaN(size(obj.agents, 1));
hComms(logical(eye(size(obj.agents, 1)))) = 0;
for ii = 1:(size(obj.agents, 1) - 1)
for jj = (ii + 1):size(obj.agents, 1)
if obj.constraintAdjacencyMatrix(ii, jj)
hComms(ii, jj) = min([obj.agents{ii}.commsGeometry.radius, obj.agents{jj}.commsGeometry.radius])^2 - norm(agents(ii).pos - agents(jj).pos)^2;
A(kk, (3 * ii - 2):(3 * ii)) = 2 * (agents(ii).pos - agents(jj).pos);
A(kk, (3 * jj - 2):(3 * jj)) = -A(kk, (3 * ii - 2):(3 * ii));
b(kk) = obj.barrierGain * hComms(ii, jj);
% dVNominal = v(ii, 1:3) - v(jj, 1:3); % nominal velocities
% h_dot_nom = -2 * (agents(ii).pos - agents(jj).pos) * dVNominal';
% b(kk) = -h_dot_nom + obj.barrierGain * hComms(ii, jj)^3;
kk = kk + 1;
end
end
end
% Solve QP program generated earlier
vhat = reshape(v', 3 * size(obj.agents, 1), 1);
H = 2 * eye(3 * size(obj.agents, 1));
f = -2 * vhat;
% Update solution based on constraints
assert(size(A,2) == size(H,1))
assert(size(A,1) == size(b,1))
assert(size(H,1) == length(f))
opt = optimoptions('quadprog', 'Display', 'off');
[vNew, ~, exitflag, m] = quadprog(sparse(H), double(f), A, b, [],[], [], [], [], opt);
assert(exitflag == 1, sprintf('quadprog failure... %s%s', newline, m.message));
vNew = reshape(vNew, 3, size(obj.agents, 1))';
if exitflag <= 0
warning("QP failed, continuing with unconstrained solution...")
vNew = v;
end
% Update the "next position" that was previously set by unconstrained
% GA using the constrained solution produced here
for ii = 1:size(vNew, 1)
obj.agents{ii}.pos = obj.agents{ii}.lastPos + vNew(ii, :) * obj.timestep;
end
% Here we run this at the simulation level, but in reality there is no
% parent level, so this would be run independently on each agent.
% Running at the simulation level is just meant to simplify the
% simulation
end

93
@miSim/initialize.m Normal file
View File

@@ -0,0 +1,93 @@
function obj = initialize(obj, domain, objective, agents, minAlt, timestep, partitoningFreq, maxIter, obstacles, makePlots, makeVideo)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
domain (1, 1) {mustBeGeometry};
objective (1, 1) {mustBeA(objective, 'sensingObjective')};
agents (:, 1) cell;
minAlt (1, 1) double = 1;
timestep (:, 1) double = 0.05;
partitoningFreq (:, 1) double = 0.25
maxIter (:, 1) double = 1000;
obstacles (:, 1) cell {mustBeGeometry} = cell(0, 1);
makePlots(1, 1) logical = true;
makeVideo (1, 1) logical = true;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% enable/disable plotting and video writer
obj.makePlots = makePlots;
if ~obj.makePlots
if makeVideo
warning("makeVideo set to true, but makePlots set to false. Setting makeVideo to false.");
makeVideo = false;
end
end
obj.makeVideo = makeVideo;
% Define simulation time parameters
obj.timestep = timestep;
obj.timestepIndex = 0;
obj.maxIter = maxIter - 1;
% Define domain
obj.domain = domain;
obj.partitioningFreq = partitoningFreq;
% Add geometries representing obstacles within the domain
obj.obstacles = obstacles;
% Add an additional obstacle spanning the domain's footprint to
% represent the minimum allowable altitude
obj.minAlt = minAlt;
if obj.minAlt > 0
obj.obstacles{end + 1, 1} = rectangularPrism;
obj.obstacles{end, 1} = obj.obstacles{end, 1}.initialize([obj.domain.minCorner; obj.domain.maxCorner(1:2), obj.minAlt], "OBSTACLE", "Minimum Altitude Domain Constraint");
end
% Define objective
obj.objective = objective;
% Define agents
obj.agents = agents;
obj.constraintAdjacencyMatrix = logical(eye(size(agents, 1)));
% Set labels for agents and collision geometries in cases where they
% were not provieded at the time of their initialization
for ii = 1:size(obj.agents, 1)
% Agent
if isempty(char(obj.agents{ii}.label))
obj.agents{ii}.label = sprintf("Agent %d", ii);
end
% Collision geometry
if isempty(char(obj.agents{ii}.collisionGeometry.label))
obj.agents{ii}.collisionGeometry.label = sprintf("Agent %d Collision Geometry", ii);
end
end
% Compute adjacency matrix and lesser neighbors
obj = obj.updateAdjacency();
obj = obj.lesserNeighbor();
% Set up times to iterate over
obj.times = linspace(0, obj.timestep * obj.maxIter, obj.maxIter+1)';
obj.partitioningTimes = obj.times(obj.partitioningFreq:obj.partitioningFreq:size(obj.times, 1));
% Prepare performance data store (at t = 0, all have 0 performance)
obj.perf = [zeros(size(obj.agents, 1) + 1, 1), NaN(size(obj.agents, 1) + 1, size(obj.partitioningTimes, 1) - 1)];
% Prepare h function data store
obj.h = NaN(size(obj.agents, 1) * (size(obj.agents, 1) - 1) / 2 + size(obj.agents, 1) * size(obj.obstacles, 1) + 6, size(obj.times, 1) - 1);
% Create initial partitioning
obj = obj.partition();
% Initialize variable that will store agent positions for trail plots
obj.posHist = NaN(size(obj.agents, 1), obj.maxIter + 1, 3);
obj.posHist(1:size(obj.agents, 1), 1, 1:3) = reshape(cell2mat(cellfun(@(x) x.pos, obj.agents, 'UniformOutput', false)), size(obj.agents, 1), 1, 3);
% Set up plots showing initialized state
obj = obj.plot();
end

76
@miSim/lesserNeighbor.m Normal file
View File

@@ -0,0 +1,76 @@
function obj = lesserNeighbor(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% initialize solution with self-connections only
constraintAdjacencyMatrix = logical(eye(size(obj.agents, 1)));
for ii = 1:size(obj.agents, 1)
% Find lesser neighbors of each agent
% Lesser neighbors of ii are jj < ii in range of ii
lesserNeighbors = [];
for jj = 1:(ii - 1)
if obj.adjacency(ii, jj)
lesserNeighbors = [lesserNeighbors, jj];
end
end
obj.agents{ii}.lesserNeighbors = lesserNeighbors;
% Early exit for isolated agents
if isempty(obj.agents{ii}.lesserNeighbors)
continue
end
% Focus on subgraph defined by lesser neighbors
subgraphAdjacency = obj.adjacency(obj.agents{ii}.lesserNeighbors, obj.agents{ii}.lesserNeighbors);
% Find connected components in each agent's subgraph
% TODO: rewrite this using matlab "conncomp" function?
visited = false(size(subgraphAdjacency, 1), 1);
components = {};
for jj = 1:size(subgraphAdjacency, 1)
if ~visited(jj)
reachable = bfs(subgraphAdjacency, jj);
visited(reachable) = true;
components{end+1} = obj.agents{ii}.lesserNeighbors(reachable);
end
end
% Connect to the greatest index in each connected component in the
% lesser neighborhood of this agent
for jj = 1:size(components, 2)
constraintAdjacencyMatrix(ii, max(components{jj})) = true;
constraintAdjacencyMatrix(max(components{jj}), ii) = true;
end
end
obj.constraintAdjacencyMatrix = constraintAdjacencyMatrix | constraintAdjacencyMatrix';
end
function cComp = bfs(subgraphAdjacency, startIdx)
n = size(subgraphAdjacency, 1);
visited = false(1, n);
queue = startIdx;
cComp = startIdx;
visited(startIdx) = true;
while ~isempty(queue)
current = queue(1);
queue(1) = [];
% Find all neighbors of current node in the subgraph
neighbors = find(subgraphAdjacency(current, :));
for neighbor = neighbors
if ~visited(neighbor)
visited(neighbor) = true;
cComp = [cComp, neighbor];
queue = [queue, neighbor];
end
end
end
cComp = sort(cComp);
end

77
@miSim/miSim.m Normal file
View File

@@ -0,0 +1,77 @@
classdef miSim
% multiagent interconnection simulation
% Simulation parameters
properties (SetAccess = private, GetAccess = public)
timestep = NaN; % delta time interval for simulation iterations
timestepIndex = NaN; % index of the current timestep (useful for time-indexed arrays)
partitioningFreq = NaN; % number of simulation timesteps at which the partitioning routine is re-run
maxIter = NaN; % maximum number of simulation iterations
domain = rectangularPrism;
objective = sensingObjective;
obstacles = cell(0, 1); % geometries that define obstacles within the domain
agents = cell(0, 1); % agents that move within the domain
adjacency = NaN; % Adjacency matrix representing communications network graph
constraintAdjacencyMatrix = NaN; % Adjacency matrix representing desired lesser neighbor connections
sensorPerformanceMinimum = 1e-6; % minimum sensor performance to allow assignment of a point in the domain to a partition
partitioning = NaN;
perf; % sensor performance timeseries array
performance = 0; % simulation performance timeseries vector
barrierGain = 100; % collision avoidance parameter
minAlt = 1; % minimum allowed altitude constraint
fPerf; % performance plot figure
end
properties (Access = private)
% Sim
t = NaN; % current sim time
times;
partitioningTimes;
% Plot objects
makePlots = true; % enable/disable simulation plotting (performance implications)
makeVideo = true; % enable/disable VideoWriter (performance implications)
f; % main plotting tiled layout figure
connectionsPlot; % objects for lines connecting agents in spatial plots
graphPlot; % objects for abstract network graph plot
partitionPlot; % objects for partition plot
performancePlot; % objects for sensor performance plot
posHist; % data for trail plot
trailPlot; % objects for agent trail plot
% Indicies for various plot types in the main tiled layout figure
spatialPlotIndices = [6, 4, 3, 2];
objectivePlotIndices = [6, 4];
networkGraphIndex = 5;
partitionGraphIndex = 1;
% CBF plotting
h; % h function values
hf; % h function plotting figure
caPlot; % objects for collision avoidance h function plot
obsPlot; % objects for obstacle h function plot
domPlot; % objects for domain h function plot
end
methods (Access = public)
[obj] = initialize(obj, domain, objective, agents, timestep, partitoningFreq, maxIter, obstacles);
[obj] = run(obj);
[obj] = lesserNeighbor(obj);
[obj] = constrainMotion(obj);
[obj] = partition(obj);
[obj] = updateAdjacency(obj);
[obj] = plot(obj);
[obj] = plotConnections(obj);
[obj] = plotPartitions(obj);
[obj] = plotGraph(obj);
[obj] = plotTrails(obj);
[obj] = plotH(obj);
[obj] = updatePlots(obj, updatePartitions);
validate(obj);
end
methods (Access = private)
[v] = setupVideoWriter(obj);
end
end

33
@miSim/partition.m Normal file
View File

@@ -0,0 +1,33 @@
function obj = partition(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Assess sensing performance of each agent at each sample point
% in the domain
agentPerformances = cellfun(@(x) reshape(x.sensorModel.sensorPerformance(x.pos, x.pan, x.tilt, [obj.objective.X(:), obj.objective.Y(:), zeros(size(obj.objective.X(:)))]), size(obj.objective.X)), obj.agents, 'UniformOutput', false);
agentPerformances{end + 1} = obj.sensorPerformanceMinimum * ones(size(agentPerformances{end})); % add additional layer to represent the threshold that has to be cleared for assignment to any partiton
agentPerformances = cat(3, agentPerformances{:});
% Get highest performance value at each point
[~, idx] = max(agentPerformances, [], 3);
% Collect agent indices in the same way as performance
indices = 1:size(obj.agents, 1);
agentInds = squeeze(tensorprod(indices, ones(size(obj.objective.X))));
if size(agentInds, 1) ~= size(obj.agents, 1)
agentInds = reshape(agentInds, [size(obj.agents, 1), size(agentInds)]); % needed for cases with 1 agent where prior squeeze is too agressive
end
agentInds = num2cell(agentInds, 2:3);
agentInds = cellfun(@(x) squeeze(x), agentInds, 'UniformOutput', false);
agentInds{end + 1} = zeros(size(agentInds{end})); % index for no assignment
agentInds = cat(3, agentInds{:});
% Use highest performing agent's index to form partitions
[m, n, ~] = size(agentInds);
[jj, kk] = ndgrid(1:m, 1:n);
obj.partitioning = agentInds(sub2ind(size(agentInds), jj, kk, idx));
end

54
@miSim/plot.m Normal file
View File

@@ -0,0 +1,54 @@
function obj = plot(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% fast exit when plotting is disabled
if ~obj.makePlots
return;
end
% Plot domain
[obj.domain, obj.f] = obj.domain.plotWireframe(obj.spatialPlotIndices);
% Plot obstacles
for ii = 1:size(obj.obstacles, 1)
[obj.obstacles{ii}, obj.f] = obj.obstacles{ii}.plotWireframe(obj.spatialPlotIndices, obj.f);
end
% Plot objective gradient
obj.f = obj.domain.objective.plot(obj.objectivePlotIndices, obj.f);
% Plot agents and their collision/communications geometries
for ii = 1:size(obj.agents, 1)
[obj.agents{ii}, obj.f] = obj.agents{ii}.plot(obj.spatialPlotIndices, obj.f);
end
% Plot communication links
obj = obj.plotConnections();
% Plot abstract network graph
obj = obj.plotGraph();
% Plot domain partitioning
obj = obj.plotPartitions();
% Plot agent trails
obj = obj.plotTrails();
% Enforce plot limits
for ii = 1:size(obj.spatialPlotIndices, 2)
xlim(obj.f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(1), obj.domain.maxCorner(1)]);
ylim(obj.f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(2), obj.domain.maxCorner(2)]);
zlim(obj.f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(3), obj.domain.maxCorner(3)]);
end
% Plot performance
obj = obj.plotPerformance();
% Plot h functions
obj = obj.plotH();
end

42
@miSim/plotConnections.m Normal file
View File

@@ -0,0 +1,42 @@
function obj = plotConnections(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Iterate over lower triangle off-diagonal region of the
% adjacency matrix to plot communications links between agents
X = []; Y = []; Z = [];
for ii = 2:size(obj.constraintAdjacencyMatrix, 1)
for jj = 1:(ii - 1)
if obj.constraintAdjacencyMatrix(ii, jj)
X = [X; obj.agents{ii}.pos(1), obj.agents{jj}.pos(1)];
Y = [Y; obj.agents{ii}.pos(2), obj.agents{jj}.pos(2)];
Z = [Z; obj.agents{ii}.pos(3), obj.agents{jj}.pos(3)];
end
end
end
X = X'; Y = Y'; Z = Z';
% Plot the connections
if isnan(obj.spatialPlotIndices)
hold(obj.f.CurrentAxes, "on");
o = plot3(obj.f.CurrentAxes, X, Y, Z, 'Color', 'g', 'LineWidth', 2, 'LineStyle', '--');
hold(obj.f.CurrentAxes, "off");
else
hold(obj.f.Children(1).Children(obj.spatialPlotIndices(1)), "on");
o = plot3(obj.f.Children(1).Children(obj.spatialPlotIndices(1)), X, Y, Z, 'Color', 'g', 'LineWidth', 2, 'LineStyle', '--');
hold(obj.f.Children(1).Children(obj.spatialPlotIndices(1)), "off");
end
% Copy to other plots
if size(obj.spatialPlotIndices, 2) > 1
for ii = 2:size(obj.spatialPlotIndices, 2)
o = [o, copyobj(o(:, 1), obj.f.Children(1).Children(obj.spatialPlotIndices(ii)))];
end
end
obj.connectionsPlot = o;
end

28
@miSim/plotGraph.m Normal file
View File

@@ -0,0 +1,28 @@
function obj = plotGraph(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Form graph from adjacency matrix
G = graph(obj.constraintAdjacencyMatrix, 'omitselfloops');
% Plot graph object
if isnan(obj.networkGraphIndex)
hold(obj.f.CurrentAxes, 'on');
o = plot(obj.f.CurrentAxes, G, 'LineStyle', '--', 'EdgeColor', 'g', 'NodeColor', 'k', 'LineWidth', 2);
hold(obj.f.CurrentAxes, 'off');
else
hold(obj.f.Children(1).Children(obj.networkGraphIndex(1)), 'on');
o = plot(obj.f.Children(1).Children(obj.networkGraphIndex(1)), G, 'LineStyle', '--', 'EdgeColor', 'g', 'NodeColor', 'k', 'LineWidth', 2);
hold(obj.f.Children(1).Children(obj.networkGraphIndex(1)), 'off');
if size(obj.networkGraphIndex, 2) > 1
for ii = 2:size(ind, 2)
o = [o; copyobj(o(1), obj.f.Children(1).Children(obj.networkGraphIndex(ii)))];
end
end
end
obj.graphPlot = o;
end

61
@miSim/plotH.m Normal file
View File

@@ -0,0 +1,61 @@
function obj = plotH(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
obj.hf = figure;
tiledlayout(obj.hf, 4, 1, "TileSpacing", "tight", "Padding", "compact");
nexttile(obj.hf.Children(1));
axes(obj.hf.Children(1).Children(1));
grid(obj.hf.Children(1).Children(1), "on");
xlabel(obj.hf.Children(1).Children(1), "Time (s)"); % ylabel(obj.hf.Children(1).Children(1), "");
title(obj.hf.Children(1).Children(1), "Collision Avoidance");
hold(obj.hf.Children(1).Children(1), "on");
obj.caPlot = plot(obj.h(1:(size(obj.agents, 1) * (size(obj.agents, 1) - 1) / 2), :)');
legendStrings = [];
for ii = 2:size(obj.agents, 1)
for jj = 1:(ii - 1)
legendStrings = [legendStrings; sprintf("A%d A%d", jj, ii)];
end
end
legend(obj.hf.Children(1).Children(1), legendStrings, 'Location', 'bestoutside');
hold(obj.hf.Children(1).Children(2), "off");
nexttile(obj.hf.Children(1));
axes(obj.hf.Children(1).Children(1));
grid(obj.hf.Children(1).Children(1), "on");
xlabel(obj.hf.Children(1).Children(1), "Time (s)"); % ylabel(obj.hf.Children(1).Children(2), "");
title(obj.hf.Children(1).Children(1), "Obstacles");
hold(obj.hf.Children(1).Children(1), "on");
obj.obsPlot = plot(obj.h((1 + (size(obj.agents, 1) * (size(obj.agents, 1) - 1) / 2)):(((size(obj.agents, 1) * (size(obj.agents, 1) - 1) / 2)) + size(obj.agents, 1) * size(obj.obstacles, 1)), :)');
legendStrings = [];
for ii = 1:size(obj.obstacles, 1)
for jj = 1:size(obj.agents, 1)
legendStrings = [legendStrings; sprintf("A%d O%d", jj, ii)];
end
end
legend(obj.hf.Children(1).Children(1), legendStrings, 'Location', 'bestoutside');
hold(obj.hf.Children(1).Children(2), "off");
nexttile(obj.hf.Children(1));
axes(obj.hf.Children(1).Children(1));
grid(obj.hf.Children(1).Children(1), "on");
xlabel(obj.hf.Children(1).Children(1), "Time (s)"); % ylabel(obj.hf.Children(1).Children(1), "");
title(obj.hf.Children(1).Children(1), "Domain");
hold(obj.hf.Children(1).Children(1), "on");
obj.domPlot = plot(obj.h((1 + (((size(obj.agents, 1) * (size(obj.agents, 1) - 1) / 2)) + size(obj.agents, 1) * size(obj.obstacles, 1))):size(obj.h, 1), 1:end)');
legend(obj.hf.Children(1).Children(1), ["X Min"; "X Max"; "Y Min"; "Y Max"; "Z Min"; "Z Max";], 'Location', 'bestoutside');
hold(obj.hf.Children(1).Children(2), "off");
nexttile(obj.hf.Children(1));
axes(obj.hf.Children(1).Children(1));
grid(obj.hf.Children(1).Children(1), "on");
xlabel(obj.hf.Children(1).Children(1), "Time (s)"); % ylabel(obj.hf.Children(1).Children(1), "");
title(obj.hf.Children(1).Children(1), "Communications");
% skipped this for now because it is very complicated
end

24
@miSim/plotPartitions.m Normal file
View File

@@ -0,0 +1,24 @@
function obj = plotPartitions(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
if isnan(obj.partitionGraphIndex)
hold(obj.f.CurrentAxes, 'on');
o = imagesc(obj.f.CurrentAxes, obj.partitioning);
hold(obj.f.CurrentAxes, 'off');
else
hold(obj.f.Children(1).Children(obj.partitionGraphIndex(1)), 'on');
o = imagesc(obj.f.Children(1).Children(obj.partitionGraphIndex(1)), obj.partitioning);
hold(obj.f.Children(1).Children(obj.partitionGraphIndex(1)), 'on');
if size(obj.partitionGraphIndex, 2) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(1), obj.f.Children(1).Children(obj.partitionGraphIndex(ii)))];
end
end
end
obj.partitionPlot = o;
end

45
@miSim/plotPerformance.m Normal file
View File

@@ -0,0 +1,45 @@
function obj = plotPerformance(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% fast exit when plotting is disabled
if ~obj.makePlots
return;
end
obj.fPerf = figure;
axes(obj.fPerf);
title(obj.fPerf.Children(1), "Sensor Performance");
xlabel(obj.fPerf.Children(1), 'Time (s)');
ylabel(obj.fPerf.Children(1), 'Sensor Performance');
grid(obj.fPerf.Children(1), 'on');
% Plot current cumulative performance
hold(obj.fPerf.Children(1), 'on');
o = plot(obj.fPerf.Children(1), obj.perf(end, :));
warning('off', 'MATLAB:gui:array:InvalidArrayShape'); % suppress this warning to avoid polluting output
o.XData = NaN(1, obj.maxIter); % correct time will be set at runtime
o.YData = [0, NaN(1, obj.maxIter - 1)];
hold(obj.fPerf.Children(1), 'off');
% Plot current agent performance
for ii = 1:(size(obj.perf, 1) - 1)
hold(obj.fPerf.Children(1), 'on');
o = [o; plot(obj.fPerf.Children(1), obj.perf(ii, :))];
o(end).XData = NaN(1, obj.maxIter); % correct time will be set at runtime
o(end).YData = [0, NaN(1, obj.maxIter - 1)];
hold(obj.fPerf.Children(1), 'off');
end
% Add legend
agentStrings = string(cellfun(@(x) x.label, obj.agents, 'UniformOutput', false));
agentStrings = ["Total"; agentStrings];
legend(obj.fPerf.Children(1), agentStrings, 'Location', 'northwest');
obj.performancePlot = o;
end

26
@miSim/plotTrails.m Normal file
View File

@@ -0,0 +1,26 @@
function obj = plotTrails(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')}
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')}
end
% fast exit when plotting is disabled
if ~obj.makePlots
return;
end
% Plot full range of position history on each spatial plot axes
o = [];
for ii = 1:(size(obj.posHist, 1))
hold(obj.f.Children(1).Children(obj.spatialPlotIndices(1)), 'on');
o = [o; plot3(obj.f.Children(1).Children(obj.spatialPlotIndices(1)), obj.posHist(ii, 1:obj.maxIter, 1), obj.posHist(ii, 1:obj.maxIter, 2), obj.posHist(ii, 1:obj.maxIter, 3), 'Color', 'k', 'LineWidth', 1)];
hold(obj.f.Children(1).Children(obj.spatialPlotIndices(1)), 'off');
end
% Copy trails to other figures?
obj.trailPlot = o;
% Add legend?
end

68
@miSim/run.m Normal file
View File

@@ -0,0 +1,68 @@
function [obj] = run(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Start video writer
if obj.makeVideo
v = obj.setupVideoWriter();
v.open();
end
for ii = 1:size(obj.times, 1)
% Display current sim time
obj.t = obj.times(ii);
obj.timestepIndex = ii;
fprintf("Sim Time: %4.2f (%d/%d)\n", obj.t, ii, obj.maxIter + 1);
% Validate current simulation configuration
obj.validate();
% Check if it's time for new partitions
updatePartitions = false;
if ismember(obj.t, obj.partitioningTimes)
updatePartitions = true;
obj = obj.partition();
end
% Determine desired communications links
obj = obj.lesserNeighbor();
% Iterate over agents to simulate their unconstrained motion
for jj = 1:size(obj.agents, 1)
obj.agents{jj} = obj.agents{jj}.run(obj.domain, obj.partitioning, obj.t, jj);
end
% Adjust motion determined by unconstrained gradient ascent using
% CBF constraints solved by QP
obj = constrainMotion(obj);
% Finished simulation for this timestep, do accounting
% Update agent position history array
obj.posHist(1:size(obj.agents, 1), obj.timestepIndex + 1, 1:3) = reshape(cell2mat(cellfun(@(x) x.pos, obj.agents, 'UniformOutput', false)), size(obj.agents, 1), 1, 3);
% Update total performance
obj.performance = [obj.performance, sum(cellfun(@(x) x.performance(end), obj.agents))];
% Update adjacency matrix
obj = obj.updateAdjacency();
% Update plots
obj = obj.updatePlots(updatePartitions);
% Write frame in to video
if obj.makeVideo
I = getframe(obj.f);
v.writeVideo(I);
end
end
if obj.makeVideo
% Close video file
v.close();
end
end

View File

@@ -1,6 +1,6 @@
function v = setupVideoWriter(timestep) function v = setupVideoWriter(obj)
arguments (Input) arguments (Input)
timestep (1, 1) double; obj (1, 1) {mustBeA(obj, 'miSim')};
end end
arguments (Output) arguments (Output)
v (1, 1) {mustBeA(v, 'VideoWriter')}; v (1, 1) {mustBeA(v, 'VideoWriter')};
@@ -9,9 +9,9 @@ function v = setupVideoWriter(timestep)
if ispc || ismac if ispc || ismac
v = VideoWriter(fullfile('sandbox', strcat(string(datetime('now'), 'yyyy_MM_dd_HH_mm_ss'), '_miSimHist')), 'MPEG-4'); v = VideoWriter(fullfile('sandbox', strcat(string(datetime('now'), 'yyyy_MM_dd_HH_mm_ss'), '_miSimHist')), 'MPEG-4');
elseif isunix elseif isunix
v = VideoWriter(fullfile('sandbox', strcat(string(datetime('now'), 'yyyy_MM_dd_HH_mm_ss'), '_miSimHist')), 'Motion JPEG AVI'); v = VideoWriter(fullfile('.', strcat(string(datetime('now'), 'yyyy_MM_dd_HH_mm_ss'), '_miSimHist')), 'Motion JPEG AVI');
end end
v.FrameRate = 1/timestep; v.FrameRate = 1 / obj.timestep;
v.Quality = 90; v.Quality = 90;
end end

35
@miSim/updateAdjacency.m Normal file
View File

@@ -0,0 +1,35 @@
function obj = updateAdjacency(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Initialize assuming only self-connections
A = true(size(obj.agents, 1));
% Check lower triangle off-diagonal connections
for ii = 2:size(A, 1)
for jj = 1:(ii - 1)
% Check that agents are not out of range
if norm(obj.agents{ii}.pos - obj.agents{jj}.pos) > min([obj.agents{ii}.commsGeometry.radius, obj.agents{jj}.commsGeometry.radius])
A(ii, jj) = false; % comm range violation
continue;
end
% % Check that agents do not have their line of sight obstructed
% for kk = 1:size(obj.obstacles, 1)
% if obj.obstacles{kk}.containsLine(obj.agents{jj}.pos, obj.agents{ii}.pos)
% A(ii, jj) = false;
% end
% end
end
end
obj.adjacency = A & A';
if any(obj.adjacency - obj.constraintAdjacencyMatrix < 0, 'all')
warning("Eliminated network connections that were necessary");
end
end

74
@miSim/updatePlots.m Normal file
View File

@@ -0,0 +1,74 @@
function [obj] = updatePlots(obj, updatePartitions)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
updatePartitions (1, 1) logical = false;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Fast exit when plotting is disabled
if ~obj.makePlots
return;
end
% Update agent positions, collision/communication geometries
for ii = 1:size(obj.agents, 1)
obj.agents{ii}.updatePlots();
end
% The remaining updates might should all be possible to do in a clever
% way that moves existing lines instead of clearing and
% re-plotting, which is much better for performance boost
% Update agent connections plot
delete(obj.connectionsPlot);
obj = obj.plotConnections();
% Update network graph plot
delete(obj.graphPlot);
obj = obj.plotGraph();
% Update partitioning plot
if updatePartitions
delete(obj.partitionPlot);
obj = obj.plotPartitions();
end
% reset plot limits to fit domain
for ii = 1:size(obj.spatialPlotIndices, 2)
xlim(obj.f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(1), obj.domain.maxCorner(1)]);
ylim(obj.f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(2), obj.domain.maxCorner(2)]);
zlim(obj.f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(3), obj.domain.maxCorner(3)]);
end
% Update agent trails
for ii = 1:size(obj.agents, 1)
obj.trailPlot(ii).XData(obj.timestepIndex) = obj.posHist(ii, obj.timestepIndex, 1);
obj.trailPlot(ii).YData(obj.timestepIndex) = obj.posHist(ii, obj.timestepIndex, 2);
obj.trailPlot(ii).ZData(obj.timestepIndex) = obj.posHist(ii, obj.timestepIndex, 3);
end
drawnow;
% Update performance plot
% Re-normalize performance plot
normalizingFactor = 1/max(obj.performance(end));
obj.performancePlot(1).YData(1:length(obj.performance)) = obj.performance * normalizingFactor;
obj.performancePlot(1).XData(obj.timestepIndex) = obj.t;
for ii = 2:(size(obj.agents, 1) + 1)
obj.performancePlot(ii).YData(1:length(obj.performance)) = obj.agents{ii - 1}.performance * normalizingFactor;
obj.performancePlot(ii).XData(obj.timestepIndex) = obj.t;
end
% Update h function plots
for ii = 1:size(obj.caPlot, 1)
obj.caPlot(ii).YData(obj.timestepIndex) = obj.h(ii, obj.timestepIndex);
end
for ii = 1:size(obj.obsPlot, 1)
obj.obsPlot(ii).YData(obj.timestepIndex) = obj.h(ii + size(obj.caPlot, 1), obj.timestepIndex);
end
for ii = 1:size(obj.domPlot, 1)
obj.domPlot(ii).YData(obj.timestepIndex) = obj.h(ii + size(obj.caPlot, 1) + size(obj.obsPlot, 1), obj.timestepIndex);
end
end

12
@miSim/validate.m Normal file
View File

@@ -0,0 +1,12 @@
function validate(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
end
if max(conncomp(graph(obj.adjacency))) ~= 1
warning("Network is not connected");
end
end

View File

@@ -0,0 +1,43 @@
function obj = initialize(obj, objectiveFunction, domain, discretizationStep, protectedRange)
arguments (Input)
obj (1,1) {mustBeA(obj, 'sensingObjective')};
objectiveFunction (1, 1) {mustBeA(objectiveFunction, 'function_handle')};
domain (1, 1) {mustBeGeometry};
discretizationStep (1, 1) double = 1;
protectedRange (1, 1) double = 1;
end
arguments (Output)
obj (1,1) {mustBeA(obj, 'sensingObjective')};
end
obj.discretizationStep = discretizationStep;
obj.groundAlt = domain.minCorner(3);
obj.protectedRange = protectedRange;
% Extract footprint limits
xMin = min(domain.footprint(:, 1));
xMax = max(domain.footprint(:, 1));
yMin = min(domain.footprint(:, 2));
yMax = max(domain.footprint(:, 2));
xGrid = unique([xMin:obj.discretizationStep:xMax, xMax]);
yGrid = unique([yMin:obj.discretizationStep:yMax, yMax]);
% Store grid points for plotting later
[obj.X, obj.Y] = meshgrid(xGrid, yGrid);
% Evaluate function over grid points
obj.objectiveFunction = objectiveFunction;
obj.values = reshape(obj.objectiveFunction(obj.X, obj.Y), size(obj.X));
% Normalize
obj.values = obj.values ./ max(obj.values, [], "all");
% store ground position
idx = obj.values == 1;
obj.groundPos = [obj.X(idx), obj.Y(idx)];
obj.groundPos = obj.groundPos(1, 1:2); % for safety, in case 2 points are maximal (somehow)
assert(domain.distance([obj.groundPos, domain.center(3)]) > protectedRange, "Domain is crowding the sensing objective")
end

View File

@@ -0,0 +1,27 @@
function obj = initializeRandomMvnpdf(obj, domain, discretizationStep, protectedRange)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'sensingObjective')};
domain (1, 1) {mustBeGeometry};
discretizationStep (1, 1) double = 1;
protectedRange (1, 1) double = 1;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'sensingObjective')};
end
% Set random objective position
mu = domain.minCorner;
while domain.distance(mu) < protectedRange
mu = domain.random();
end
mu = mu(1:2);
% Set random distribution parameters
sig = [2 + rand * 2, 1; 1, 2 + rand * 2];
% Set up random bivariate normal distribution function
objectiveFunction = @(x, y) mvnpdf([x(:), y(:)], mu, sig);
% Regular initialization
obj = obj.initialize(objectiveFunction, domain, discretizationStep, protectedRange);
end

35
@sensingObjective/plot.m Normal file
View File

@@ -0,0 +1,35 @@
function f = plot(obj, ind, f)
arguments (Input)
obj (1,1) {mustBeA(obj, 'sensingObjective')};
ind (1, :) double = NaN;
f (1,1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
f (1,1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Plot gradient on the "floor" of the domain
if isnan(ind)
hold(f.CurrentAxes, "on");
o = surf(f.CurrentAxes, obj.X, obj.Y, repmat(obj.groundAlt, size(obj.X)), obj.values ./ max(obj.values, [], "all"), 'EdgeColor', 'none');
o.HitTest = 'off';
o.PickableParts = 'none';
hold(f.CurrentAxes, "off");
else
hold(f.Children(1).Children(ind(1)), "on");
o = surf(f.Children(1).Children(ind(1)), obj.X, obj.Y, repmat(obj.groundAlt, size(obj.X)), obj.values ./ max(obj.values, [], "all"), 'EdgeColor', 'none');
o.HitTest = 'off';
o.PickableParts = 'none';
hold(f.Children(1).Children(ind(1)), "off");
end
% Add to other perspectives
if size(ind, 2) > 1
for ii = 2:size(ind, 2)
copyobj(o, f.Children(1).Children(ind(ii)));
end
end
end

View File

@@ -0,0 +1,20 @@
classdef sensingObjective
% Sensing objective definition parent class
properties (SetAccess = private, GetAccess = public)
label = "";
groundAlt = 0;
groundPos = [0, 0];
discretizationStep = 1;
objectiveFunction = @(x, y) 0; % define objective functions over a grid in this manner
X = [];
Y = [];
values = [];
protectedRange = 1; % keep obstacles from crowding objective
end
methods (Access = public)
[obj] = initialize(obj, objectiveFunction, domain, discretizationStep, protectedRange);
[obj] = initializeRandomMvnpdf(obj, domain, protectedRange, discretizationStep, protectedRange);
[f ] = plot(obj, ind, f);
end
end

167
agent.m
View File

@@ -1,167 +0,0 @@
classdef agent
properties (SetAccess = private, GetAccess = public)
% Identifiers
index = NaN;
label = "";
% Sensor
sensorModel;
sensingLength = 0.05; % length parameter used by sensing function
% Guidance
guidanceModel;
% State
lastPos = NaN(1, 3); % position from previous timestep
pos = NaN(1, 3); % current position
vel = NaN(1, 3); % current velocity
pan = NaN; % pan angle
tilt = NaN; % tilt angle
% Collision
collisionGeometry;
% FOV cone
fovGeometry;
% Communication
comRange = NaN;
% Plotting
scatterPoints;
end
methods (Access = public)
function obj = initialize(obj, pos, vel, pan, tilt, collisionGeometry, sensorModel, guidanceModel, comRange, index, label)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
pos (1, 3) double;
vel (1, 3) double;
pan (1, 1) double;
tilt (1, 1) double;
collisionGeometry (1, 1) {mustBeGeometry};
sensorModel (1, 1) {mustBeSensor}
guidanceModel (1, 1) {mustBeA(guidanceModel, 'function_handle')};
comRange (1, 1) double = NaN;
index (1, 1) double = NaN;
label (1, 1) string = "";
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'agent')};
end
obj.pos = pos;
obj.vel = vel;
obj.pan = pan;
obj.tilt = tilt;
obj.collisionGeometry = collisionGeometry;
obj.sensorModel = sensorModel;
obj.guidanceModel = guidanceModel;
obj.comRange = comRange;
obj.index = index;
obj.label = label;
% Initialize FOV cone
obj.fovGeometry = cone;
obj.fovGeometry = obj.fovGeometry.initialize([obj.pos(1:2), 0], obj.sensorModel.r, obj.pos(3), REGION_TYPE.FOV, sprintf("%s FOV", obj.label));
end
function obj = run(obj, sensingObjective, domain, partitioning)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
sensingObjective (1, 1) {mustBeA(sensingObjective, 'sensingObjective')};
domain (1, 1) {mustBeGeometry};
partitioning (:, :) double;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'agent')};
end
% Do sensing
[sensedValues, sensedPositions] = obj.sensorModel.sense(obj, sensingObjective, domain, partitioning);
% Determine next planned position
nextPos = obj.guidanceModel(sensedValues, sensedPositions, obj.pos);
% Move to next position
% (dynamics not modeled at this time)
obj.lastPos = obj.pos;
obj.pos = nextPos;
% Calculate movement
d = obj.pos - obj.collisionGeometry.center;
% Reinitialize collision geometry in the new position
obj.collisionGeometry = obj.collisionGeometry.initialize([obj.collisionGeometry.minCorner; obj.collisionGeometry.maxCorner] + d, obj.collisionGeometry.tag, obj.collisionGeometry.label);
end
function updatePlots(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
end
arguments (Output)
end
% Scatterplot point positions
for ii = 1:size(obj.scatterPoints, 1)
obj.scatterPoints(ii).XData = obj.pos(1);
obj.scatterPoints(ii).YData = obj.pos(2);
obj.scatterPoints(ii).ZData = obj.pos(3);
end
% Find change in agent position since last timestep
deltaPos = obj.pos - obj.lastPos;
% Collision geometry edges
for jj = 1:size(obj.collisionGeometry.lines, 2)
% Update plotting
for ii = 1:size(obj.collisionGeometry.lines(:, jj), 1)
obj.collisionGeometry.lines(ii, jj).XData = obj.collisionGeometry.lines(ii, jj).XData + deltaPos(1);
obj.collisionGeometry.lines(ii, jj).YData = obj.collisionGeometry.lines(ii, jj).YData + deltaPos(2);
obj.collisionGeometry.lines(ii, jj).ZData = obj.collisionGeometry.lines(ii, jj).ZData + deltaPos(3);
end
end
% Update FOV geometry surfaces
for jj = 1:size(obj.fovGeometry.surface, 2)
% Update each plot
obj.fovGeometry.surface(jj).XData = obj.fovGeometry.surface(jj).XData + deltaPos(1);
obj.fovGeometry.surface(jj).YData = obj.fovGeometry.surface(jj).YData + deltaPos(2);
obj.fovGeometry.surface(jj).ZData = obj.fovGeometry.surface(jj).ZData + deltaPos(3);
end
end
function [obj, f] = plot(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'agent')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'agent')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Plot points representing the agent position
hold(f.Children(1).Children(end), "on");
o = scatter3(f.Children(1).Children(end), obj.pos(1), obj.pos(2), obj.pos(3), 'filled', 'ko', 'SizeData', 25);
hold(f.Children(1).Children(end), "off");
% Check if this is a tiled layout figure
if strcmp(f.Children(1).Type, 'tiledlayout')
% Add to other perspectives
o = [o; copyobj(o(1), f.Children(1).Children(2))];
o = [o; copyobj(o(1), f.Children(1).Children(3))];
o = [o; copyobj(o(1), f.Children(1).Children(4))];
end
obj.scatterPoints = o;
% Plot collision geometry
[obj.collisionGeometry, f] = obj.collisionGeometry.plotWireframe(ind, f);
% Plot FOV geometry
[obj.fovGeometry, f] = obj.fovGeometry.plot(ind, f);
end
end
end

22
geometries/@cone/cone.m Normal file
View File

@@ -0,0 +1,22 @@
classdef cone
% Conical geometry
properties (SetAccess = private, GetAccess = public)
% Meta
tag = REGION_TYPE.INVALID;
label = "";
% Spatial
center = NaN;
radius = NaN;
height = NaN;
% Plotting
surface;
n = 32;
end
methods (Access = public)
[obj ] = initialize(obj, center, radius, height, tag, label);
[obj, f] = plot(obj, ind, f);
end
end

View File

@@ -0,0 +1,19 @@
function obj = initialize(obj, center, radius, height, tag, label)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'cone')};
center (1, 3) double;
radius (1, 1) double;
height (1, 1) double;
tag (1, 1) REGION_TYPE = REGION_TYPE.INVALID;
label (1, 1) string = "";
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'cone')};
end
obj.center = center;
obj.radius = radius;
obj.height = height;
obj.tag = tag;
obj.label = label;
end

43
geometries/@cone/plot.m Normal file
View File

@@ -0,0 +1,43 @@
function [obj, f] = plot(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'cone')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'cone')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Plot cone
[X, Y, Z] = cylinder([obj.radius, 0], obj.n);
% Scale to match height
Z = Z * obj.height;
% Move to center location
X = X + obj.center(1);
Y = Y + obj.center(2);
Z = Z + obj.center(3);
% Plot
if isnan(ind)
o = surf(f.CurrentAxes, X, Y, Z);
else
hold(f.Children(1).Children(ind(1)), "on");
o = surf(f.Children(1).Children(ind(1)), X, Y, Z, ones([size(Z), 1]) .* reshape(obj.tag.color, 1, 1, 3), 'FaceAlpha', 0.25, 'EdgeColor', 'none');
hold(f.Children(1).Children(ind(1)), "off");
end
% Copy to other requested tiles
if numel(ind) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(:, 1), f.Children(1).Children(ind(ii)))];
end
end
obj.surface = o;
end

View File

@@ -0,0 +1,19 @@
function cPos = closestToPoint(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
cPos (:, 3) double;
end
cPos = NaN(1, 3);
for ii = 1:3
if pos(ii) < obj.minCorner(ii)
cPos(ii) = obj.minCorner(ii);
elseif pos(ii) > obj.maxCorner(ii)
cPos(ii) = obj.maxCorner(ii);
else
cPos(ii) = pos(ii);
end
end
end

View File

@@ -0,0 +1,10 @@
function c = contains(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
c (:, 1) logical
end
c = all(pos >= repmat(obj.minCorner, size(pos, 1), 1), 2) & all(pos <= repmat(obj.maxCorner, size(pos, 1), 1), 2);
end

View File

@@ -0,0 +1,46 @@
function c = containsLine(obj, pos1, pos2)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos1 (1, 3) double;
pos2 (1, 3) double;
end
arguments (Output)
c (1, 1) logical
end
d = pos2 - pos1;
% endpoint contained (trivial case)
if obj.contains(pos1) || obj.contains(pos2)
c = true;
return;
end
% parameterize the line segment to check for an intersection
tMin = 0;
tMax = 1;
for ii = 1:3
% line is parallel to geometry
if abs(d(ii)) < 1e-12
if pos1(ii) < obj.minCorner(ii) || pos1(ii) > obj.maxCorner(ii)
c = false;
return;
end
else
t1 = (obj.minCorner(ii) - pos1(ii)) / d(ii);
t2 = (obj.maxCorner(ii) - pos1(ii)) / d(ii);
tLow = min(t1, t2);
tHigh = max(t1, t2);
tMin = max(tMin, tLow);
tMax = min(tMax, tHigh);
if tMin > tMax
c = false;
return;
end
end
end
c = true;
end

View File

@@ -0,0 +1,32 @@
function d = distance(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
d (:, 1) double;
end
if obj.contains(pos)
% Queried point is inside geometry
% find minimum distance to any face
d = min([pos(1) - obj.minCorner(1), ...
pos(2) - obj.minCorner(2), ...
pos(3) - obj.minCorner(3), ...
obj.maxCorner(1) - pos(1), ...
obj.maxCorner(2) - pos(2), ...
obj.maxCorner(3) - pos(3)]);
else
% Queried point is outside geometry
cPos = NaN(1, 3);
for ii = 1:3
if pos(ii) < obj.minCorner(ii)
cPos(ii) = obj.minCorner(ii);
elseif pos(ii) > obj.maxCorner(ii)
cPos(ii) = obj.maxCorner(ii);
else
cPos(ii) = pos(ii);
end
end
d = norm(cPos - pos);
end
end

View File

@@ -0,0 +1,42 @@
function g = distanceGradient(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
g (:, 3) double
end
% find nearest point on surface to query position
q = min(max(pos, obj.minCorner), obj.maxCorner);
% Find distance and direction between pos and q
v = pos - q;
vNorm = norm(v);
% position is outside geometry
if vNorm > 0
% gradient is normalized vector from q to p
g = v / vNorm;
return;
end
% position is on or in geometry
% find distances to each face in each dimension
distances = [pos(1) - obj.minCorner(1), obj.maxCorner(1) - pos(1), pos(2) - obj.minCorner(2), obj.maxCorner(2) - pos(2), pos(3) - obj.minCorner(3), obj.maxCorner(3) - pos(3)];
[~, idx] = min(distances);
% I think there needs to be additional handling here for the
% edge/corner cases, where there are ways to balance or resolve ties
% when two faces are equidistant to the query position
assert(sum(idx) == idx, "Implement edge case handling");
% select gradient that brings us quickest to the nearest face
g = [ 1, 0, 0; ...
-1, 0, 0; ...
0, 1, 0; ...
0, -1, 0; ...
0, 0, 1; ...
0, 0, -1;];
g = g(idx, :);
end

View File

@@ -0,0 +1,60 @@
function obj = initialize(obj, bounds, tag, label, objectiveFunction, discretizationStep)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
bounds (2, 3) double;
tag (1, 1) REGION_TYPE = REGION_TYPE.INVALID;
label (1, 1) string = "";
objectiveFunction (1, 1) function_handle = @(x, y) 1;
discretizationStep (1, 1) double = 1;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
end
obj.tag = tag;
obj.label = label;
% Define geometry bounds by LL corner and UR corner
obj.minCorner = bounds(1, 1:3);
obj.maxCorner = bounds(2, 1:3);
% Compute L, W, H
obj.dimensions = [obj.maxCorner(1) - obj.minCorner(1), obj.maxCorner(2) - obj.minCorner(2), obj.maxCorner(3) - obj.minCorner(3)];
% Compute center
obj.center = obj.minCorner + obj.dimensions ./ 2;
% Compute a (fake) radius
% fully contains the rectangular prism from the center
obj.radius = (1/2) * sqrt(sum(obj.dimensions.^2));
% Compute vertices
obj.vertices = [obj.minCorner;
obj.maxCorner(1), obj.minCorner(2:3);
obj.maxCorner(1:2), obj.minCorner(3);
obj.minCorner(1), obj.maxCorner(2), obj.minCorner(3);
obj.minCorner(1:2), obj.maxCorner(3);
obj.maxCorner(1), obj.minCorner(2), obj.maxCorner(3);
obj.minCorner(1), obj.maxCorner(2:3)
obj.maxCorner;];
% Compute footprint
obj.footprint = [obj.minCorner(1:2); ...
[obj.minCorner(1), obj.maxCorner(2)]; ...
[obj.maxCorner(1), obj.minCorner(2)]; ...
obj.maxCorner(1:2)];
% Instantiate sensingObjective only for DOMAIN-type regions
if tag == REGION_TYPE.DOMAIN
obj.objective = sensingObjective;
end
% Initialize CBF
% first part evaluates to +/-1 if the point is outside/inside the collision geometry
% Second part determines the distance from the point to the boundary of the collision geometry
obj.barrierFunction = @(x) (1 - 2 * obj.collisionGeometry.contains(x)) * obj.collisionGeometry.distance(x); % x is 1x3
% gradient of barrier function
obj.dBarrierFunction = @(x) obj.collisionGeometry.distanceGradient(x); % x is 1x3
% as long as the collisionGeometry object is updated during runtime,
% these functions never have to be updated again
end

View File

@@ -0,0 +1,45 @@
function [obj] = initializeRandom(obj, tag, label, minDimension, maxDimension, domain, minAlt)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
tag (1, 1) REGION_TYPE = REGION_TYPE.INVALID;
label (1, 1) string = "";
minDimension (1, 1) double = 10;
maxDimension (1, 1) double = 20;
domain (1, 1) {mustBeGeometry} = rectangularPrism;
minAlt (1, 1) double = 0;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
end
% Produce random bounds based on region type
if tag == REGION_TYPE.DOMAIN
% Domain
L = ceil(minDimension + rand * (maxDimension - minDimension));
bounds = [zeros(1, 3); L * ones(1, 3)];
else
% Obstacle
% Produce a corners that are contained in the domain
ii = 0;
candidateMaxCorner = domain.maxCorner + ones(1, 3);
candidateMinCorner = domain.minCorner - ones(1, 3);
% Continue until the domain contains the obstacle without crowding the objective
while ~domain.contains(candidateMaxCorner) || all(domain.objective.groundPos + domain.objective.protectedRange >= candidateMinCorner(1:2), 2) && all(domain.objective.groundPos - domain.objective.protectedRange <= candidateMaxCorner(1:2), 2)
if ii == 0 || ii > 10
candidateMinCorner = domain.random();
candidateMinCorner(3) = minAlt; % bind to floor (plus minimum altitude constraint)
ii = 1;
end
candidateMaxCorner = candidateMinCorner + minDimension + rand(1, 3) * (maxDimension - minDimension);
ii = ii + 1;
end
bounds = [candidateMinCorner; candidateMaxCorner;];
end
% Regular initialization
obj = obj.initialize(bounds, tag, label);
end

View File

@@ -0,0 +1,37 @@
function [obj, f] = plotWireframe(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Create plotting inputs from vertices and edges
X = [obj.vertices(obj.edges(:,1),1), obj.vertices(obj.edges(:,2),1)]';
Y = [obj.vertices(obj.edges(:,1),2), obj.vertices(obj.edges(:,2),2)]';
Z = [obj.vertices(obj.edges(:,1),3), obj.vertices(obj.edges(:,2),3)]';
% Plot the boundaries of the geometry into 3D view
if isnan(ind)
o = plot3(f.CurrentAxes, X, Y, Z, '-', 'Color', obj.tag.color, 'LineWidth', 2);
else
hold(f.Children(1).Children(ind(1)), "on");
o = plot3(f.Children(1).Children(ind(1)), X, Y, Z, '-', 'Color', obj.tag.color, 'LineWidth', 2);
hold(f.Children(1).Children(ind(1)), "off");
end
% Copy to other requested tiles
if numel(ind) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(:, 1), f.Children(1).Children(ind(ii)))];
end
end
obj.lines = o;
end

View File

@@ -0,0 +1,9 @@
function r = random(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
end
arguments (Output)
r (1, 3) double
end
r = (obj.vertices(1, 1:3) + rand(1, 3) .* obj.vertices(8, 1:3) - obj.vertices(1, 1:3))';
end

View File

@@ -0,0 +1,45 @@
classdef rectangularPrism
% Rectangular prism geometry
properties (SetAccess = private, GetAccess = public)
% Meta
tag = REGION_TYPE.INVALID;
% Spatial
minCorner = NaN(1, 3);
maxCorner = NaN(1, 3);
dimensions = NaN(1, 3);
center = NaN;
footprint = NaN(4, 2);
radius = NaN; % fake radius
% Graph
vertices = NaN(8, 3);
edges = [1 2; 2 3; 3 4; 4 1; % bottom square
5 6; 6 8; 8 7; 7 5; % top square
1 5; 2 6; 3 8; 4 7]; % vertical edges
% Plotting
lines;
% collision
barrierFunction;
dBarrierFunction;
end
properties (SetAccess = public, GetAccess = public)
label = "";
% Sensing objective (for DOMAIN region type only)
objective;
end
methods (Access = public)
[obj ] = initialize(obj, bounds, tag, label, objectiveFunction, discretizationStep);
[obj ] = initializeRandom(obj, tag, label, minDimension, maxDimension, domain);
[r ] = random(obj);
[c ] = contains(obj, pos);
[cPos ] = closestToPoint(obj, pos);
[d ] = distance(obj, pos);
[g ] = distanceGradient(obj, pos);
[c ] = containsLine(obj, pos1, pos2);
[obj, f] = plotWireframe(obj, ind, f);
end
end

View File

@@ -0,0 +1,10 @@
function c = contains(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'spherical')};
pos (:, 3) double;
end
arguments (Output)
c (:, 1) logical
end
c = norm(obj.center - pos) <= obj.radius;
end

View File

@@ -0,0 +1,28 @@
function c = containsLine(obj, pos1, pos2)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'spherical')};
pos1 (1, 3) double;
pos2 (1, 3) double;
end
arguments (Output)
c (1, 1) logical
end
d = pos2 - pos1;
f = pos1 - obj.center;
a = dot(d, d);
b = 2 * dot(f, d);
c = dot(f, f) - obj.radius^2;
disc = b^2 - 4*a*c;
if disc < 0
c = false;
return;
end
t = [(-b - sqrt(disc)) / (2 * a), (-b + sqrt(disc)) / (2 * a)];
c = (t(1) >= 0 && t(1) <= 1) || (t(2) >= 0 && t(2) <= 1);
end

View File

@@ -0,0 +1,42 @@
function obj = initialize(obj, center, radius, tag, label)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'spherical')};
center (1, 3) double;
radius (1, 1) double;
tag (1, 1) REGION_TYPE = REGION_TYPE.INVALID;
label (1, 1) string = "";
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'spherical')};
end
obj.tag = tag;
obj.label = label;
% Define geometry
obj.center = center;
obj.radius = radius;
obj.diameter = 2 * obj.radius;
% Initialize CBF
obj.barrierFunction = @(x) NaN;
% gradient of barrier function
obj.dBarrierFunction = @(x) NaN;
% fake vertices in a cross pattern
obj.vertices = [obj.center + [obj.radius, 0, 0]; ...
obj.center - [obj.radius, 0, 0]; ...
obj.center + [0, obj.radius, 0]; ...
obj.center - [0, obj.radius, 0]; ...
obj.center + [0, 0, obj.radius]; ...
obj.center - [0, 0, obj.radius]];
% fake edges in two perpendicular rings
obj.edges = [1, 3; ...
3, 2; ...
2, 4; ...
4, 1; ...
1, 5; ...
5, 2; ...
2, 6; ...
6, 1];
end

View File

@@ -0,0 +1,43 @@
function [obj, f] = plotWireframe(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'spherical')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'spherical')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Create plotting inputs
[X, Y, Z] = sphere(8);
% Scale
X = X * obj.radius;
Y = Y * obj.radius;
Z = Z * obj.radius;
% Shift
X = X + obj.center(1);
Y = Y + obj.center(2);
Z = Z + obj.center(3);
% Plot the boundaries of the geometry into 3D view
if isnan(ind)
o = plot3(f.CurrentAxes, X, Y, Z, '-', 'Color', obj.tag.color, 'LineWidth', 2);
else
hold(f.Children(1).Children(ind(1)), "on");
o = plot3(f.Children(1).Children(ind(1)), X, Y, Z, '-', 'Color', obj.tag.color, 'LineWidth', 2);
hold(f.Children(1).Children(ind(1)), "off");
end
% Copy to other requested tiles
if numel(ind) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(:, 1), f.Children(1).Children(ind(ii)))];
end
end
obj.lines = o;
end

View File

@@ -0,0 +1,15 @@
function r = random(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'spherical')};
end
arguments (Output)
r (1, 3) double
end
y = (rand - 0.5) * 2; % uniform draw on [-1, 1]
R = sqrt(1 - y^2);
lon = (rand - 0.5) * 2 * pi; % uniform draw on [-pi, pi]
s = [R * sin(lon), y, R * cos(lon)]; % random point on surface
r = s * rand^(1/3); % scaled to random normalized radius [0, 1]
r = obj.center + obj.radius * r;
end

View File

@@ -0,0 +1,37 @@
classdef spherical
% Rectangular prism geometry
properties (SetAccess = private, GetAccess = public)
% Spatial
center = NaN;
radius = NaN;
diameter = NaN;
vertices; % fake vertices
edges; % fake edges
% Plotting
lines;
% collision
barrierFunction;
dBarrierFunction;
end
properties (SetAccess = public, GetAccess = public)
% Meta
tag = REGION_TYPE.INVALID;
label = "";
% Sensing objective (for DOMAIN region type only)
objective;
end
methods (Access = public)
[obj ] = initialize(obj, center, radius, tag, label);
[r ] = random(obj);
[c ] = contains(obj, pos);
[d ] = distance(obj, pos);
[g ] = distanceGradient(obj, pos);
[c ] = containsLine(obj, pos1, pos2);
[obj, f] = plotWireframe(obj, ind, f);
end
end

View File

@@ -9,6 +9,7 @@ classdef REGION_TYPE
OBSTACLE (2, [255, 127, 127]); % obstacle region OBSTACLE (2, [255, 127, 127]); % obstacle region
COLLISION (3, [255, 255, 128]); % collision avoidance region COLLISION (3, [255, 255, 128]); % collision avoidance region
FOV (4, [255, 165, 0]); % field of view region FOV (4, [255, 165, 0]); % field of view region
COMMS (5, [0, 255, 0]); % comunications region
end end
methods methods
function obj = REGION_TYPE(id, color) function obj = REGION_TYPE(id, color)

View File

@@ -1,82 +0,0 @@
classdef cone
% Conical geometry
properties (SetAccess = private, GetAccess = public)
% Meta
tag = REGION_TYPE.INVALID;
label = "";
% Spatial
center = NaN;
radius = NaN;
height = NaN;
% Plotting
surface;
n = 32;
end
methods
function obj = initialize(obj, center, radius, height, tag, label)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'cone')};
center (1, 3) double;
radius (1, 1) double;
height (1, 1) double;
tag (1, 1) REGION_TYPE = REGION_TYPE.INVALID;
label (1, 1) string = "";
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'cone')};
end
obj.center = center;
obj.radius = radius;
obj.height = height;
obj.tag = tag;
obj.label = label;
end
function [obj, f] = plot(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'cone')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'cone')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Plot cone
[X, Y, Z] = cylinder([obj.radius, 0], obj.n);
% Scale to match height
Z = Z * obj.height;
% Move to center location
X = X + obj.center(1);
Y = Y + obj.center(2);
Z = Z + obj.center(3);
% Plot
if isnan(ind)
o = surf(f.CurrentAxes, X, Y, Z);
else
hold(f.Children(1).Children(ind(1)), "on");
o = surf(f.Children(1).Children(ind(1)), X, Y, Z, ones([size(Z), 1]) .* reshape(obj.tag.color, 1, 1, 3), 'FaceAlpha', 0.25, 'EdgeColor', 'none');
hold(f.Children(1).Children(ind(1)), "off");
end
% Copy to other requested tiles
if numel(ind) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(:, 1), f.Children(1).Children(ind(ii)))];
end
end
obj.surface = o;
end
end
end

View File

@@ -1,204 +0,0 @@
classdef rectangularPrism
% Rectangular prism geometry
properties (SetAccess = private, GetAccess = public)
% Meta
tag = REGION_TYPE.INVALID;
label = "";
% Spatial
minCorner = NaN(1, 3);
maxCorner = NaN(1, 3);
dimensions = NaN(1, 3);
center = NaN;
footprint = NaN(4, 2);
% Graph
vertices = NaN(8, 3);
edges = [1 2; 2 3; 3 4; 4 1; % bottom square
5 6; 6 8; 8 7; 7 5; % top square
1 5; 2 6; 3 8; 4 7]; % vertical edges
% Plotting
lines;
end
methods (Access = public)
function obj = initialize(obj, bounds, tag, label)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
bounds (2, 3) double;
tag (1, 1) REGION_TYPE = REGION_TYPE.INVALID;
label (1, 1) string = "";
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
end
obj.tag = tag;
obj.label = label;
%% Define geometry bounds by LL corner and UR corner
obj.minCorner = bounds(1, 1:3);
obj.maxCorner = bounds(2, 1:3);
% Compute L, W, H
obj.dimensions = [obj.maxCorner(1) - obj.minCorner(1), obj.maxCorner(2) - obj.minCorner(2), obj.maxCorner(3) - obj.minCorner(3)];
% Compute center
obj.center = obj.minCorner + obj.dimensions ./ 2;
% Compute vertices
obj.vertices = [obj.minCorner;
obj.maxCorner(1), obj.minCorner(2:3);
obj.maxCorner(1:2), obj.minCorner(3);
obj.minCorner(1), obj.maxCorner(2), obj.minCorner(3);
obj.minCorner(1:2), obj.maxCorner(3);
obj.maxCorner(1), obj.minCorner(2), obj.maxCorner(3);
obj.minCorner(1), obj.maxCorner(2:3)
obj.maxCorner;];
% Compute footprint
obj.footprint = [obj.minCorner(1:2); ...
[obj.minCorner(1), obj.maxCorner(2)]; ...
[obj.maxCorner(1), obj.minCorner(2)]; ...
obj.maxCorner(1:2)];
end
function r = random(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
end
arguments (Output)
r (1, 3) double
end
r = (obj.vertices(1, 1:3) + rand(1, 3) .* obj.vertices(8, 1:3) - obj.vertices(1, 1:3))';
end
function d = distance(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
d (:, 1) double
end
assert(~obj.contains(pos), "Cannot determine distance for a point inside of the geometry");
cPos = NaN(1, 3);
for ii = 1:3
if pos(ii) < obj.minCorner(ii)
cPos(ii) = obj.minCorner(ii);
elseif pos(ii) > obj.maxCorner(ii)
cPos(ii) = obj.maxCorner(ii);
else
cPos(ii) = pos(ii);
end
end
d = norm(cPos - pos);
end
function d = interiorDistance(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
d (:, 1) double
end
assert(obj.contains(pos), "Cannot determine interior distance for a point outside of the geometry");
% find minimum distance to any face
d = min([pos(1) - obj.minCorner(1), ...
pos(2) - obj.minCorner(2), ...
pos(3) - obj.minCorner(3), ...
obj.maxCorner(1) - pos(1), ...
obj.maxCorner(2) - pos(2), ...
obj.maxCorner(3) - pos(3)]);
end
function c = contains(obj, pos)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos (:, 3) double;
end
arguments (Output)
c (:, 1) logical
end
c = all(pos >= repmat(obj.minCorner, size(pos, 1), 1), 2) & all(pos <= repmat(obj.maxCorner, size(pos, 1), 1), 2);
end
function c = containsLine(obj, pos1, pos2)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
pos1 (1, 3) double;
pos2 (1, 3) double;
end
arguments (Output)
c (1, 1) logical
end
d = pos2 - pos1;
% edge case where the line is parallel to the geometry
if abs(d) < 1e-12
% check if it happens to start or end inside or outside of
% the geometry
if obj.contains(pos1) || obj.contains(pos2)
c = true;
else
c = false;
end
return;
end
tmin = -inf;
tmax = inf;
% Standard case
for ii = 1:3
t1 = (obj.minCorner(ii) - pos1(ii)) / d(ii);
t2 = (obj.maxCorner(ii) - pos2(ii)) / d(ii);
tmin = max(tmin, min(t1, t2));
tmax = min(tmax, max(t1, t2));
if tmin > tmax
c = false;
return;
end
end
c = (tmax >= 0) && (tmin <= 1);
end
function [obj, f] = plotWireframe(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'rectangularPrism')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Create plotting inputs from vertices and edges
X = [obj.vertices(obj.edges(:,1),1), obj.vertices(obj.edges(:,2),1)]';
Y = [obj.vertices(obj.edges(:,1),2), obj.vertices(obj.edges(:,2),2)]';
Z = [obj.vertices(obj.edges(:,1),3), obj.vertices(obj.edges(:,2),3)]';
% Plot the boundaries of the geometry into 3D view
if isnan(ind)
o = plot3(f.CurrentAxes, X, Y, Z, '-', 'Color', obj.tag.color, 'LineWidth', 2);
else
hold(f.Children(1).Children(ind(1)), "on");
o = plot3(f.Children(1).Children(ind(1)), X, Y, Z, '-', 'Color', obj.tag.color, 'LineWidth', 2);
hold(f.Children(1).Children(ind(1)), "off");
end
% Copy to other requested tiles
if numel(ind) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(:, 1), f.Children(1).Children(ind(ii)))];
end
end
obj.lines = o;
end
end
end

View File

@@ -1,26 +0,0 @@
function nextPos = gradientAscent(sensedValues, sensedPositions, pos, rate)
arguments (Input)
sensedValues (:, 1) double;
sensedPositions (:, 3) double;
pos (1, 3) double;
rate (1, 1) double = 0.1;
end
arguments (Output)
nextPos(1, 3) double;
end
% As a default, maintain current position
if size(sensedValues, 1) == 0 && size(sensedPositions, 1) == 0
nextPos = pos;
return;
end
% Select next position by maximum sensed value
nextPos = sensedPositions(sensedValues == max(sensedValues), :);
nextPos = [nextPos(1, 1:2), pos(3)]; % just in case two get selected, simply pick one
% rate-limit motion
v = nextPos - pos;
nextPos = pos + (v / norm(v, 2)) * rate;
end

379
miSim.m
View File

@@ -1,379 +0,0 @@
classdef miSim
% multiagent interconnection simulation
% Simulation parameters
properties (SetAccess = private, GetAccess = public)
timestep = NaN; % delta time interval for simulation iterations
partitioningFreq = NaN; % number of simulation timesteps at which the partitioning routine is re-run
maxIter = NaN; % maximum number of simulation iterations
domain = rectangularPrism;
objective = sensingObjective;
obstacles = cell(0, 1); % geometries that define obstacles within the domain
agents = cell(0, 1); % agents that move within the domain
adjacency = NaN; % Adjacency matrix representing communications network graph
partitioning = NaN;
end
properties (Access = private)
% Plot objects
connectionsPlot; % objects for lines connecting agents in spatial plots
graphPlot; % objects for abstract network graph plot
partitionPlot; % objects for partition plot
% Indicies for various plot types in the main tiled layout figure
spatialPlotIndices = [6, 4, 3, 2];
objectivePlotIndices = [6, 4];
networkGraphIndex = 5;
partitionGraphIndex = 1;
end
methods (Access = public)
function [obj, f] = initialize(obj, domain, objective, agents, timestep, partitoningFreq, maxIter, obstacles)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
domain (1, 1) {mustBeGeometry};
objective (1, 1) {mustBeA(objective, 'sensingObjective')};
agents (:, 1) cell;
timestep (:, 1) double = 0.05;
partitoningFreq (:, 1) double = 0.25
maxIter (:, 1) double = 1000;
obstacles (:, 1) cell {mustBeGeometry} = cell(0, 1);
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Define simulation time parameters
obj.timestep = timestep;
obj.maxIter = maxIter;
% Define domain
obj.domain = domain;
obj.partitioningFreq = partitoningFreq;
% Add geometries representing obstacles within the domain
obj.obstacles = obstacles;
% Define objective
obj.objective = objective;
% Define agents
obj.agents = agents;
% Compute adjacency matrix
obj = obj.updateAdjacency();
% Create initial partitioning
obj = obj.partition();
% Set up initial plot
% Set up axes arrangement
% Plot domain
[obj.domain, f] = obj.domain.plotWireframe(obj.spatialPlotIndices);
% Plot obstacles
for ii = 1:size(obj.obstacles, 1)
[obj.obstacles{ii}, f] = obj.obstacles{ii}.plotWireframe(obj.spatialPlotIndices, f);
end
% Plot objective gradient
f = obj.objective.plot(obj.objectivePlotIndices, f);
% Plot agents and their collision geometries
for ii = 1:size(obj.agents, 1)
[obj.agents{ii}, f] = obj.agents{ii}.plot(obj.spatialPlotIndices, f);
end
% Plot communication links
[obj, f] = obj.plotConnections(obj.spatialPlotIndices, f);
% Plot abstract network graph
[obj, f] = obj.plotGraph(obj.networkGraphIndex, f);
% Plot domain partitioning
[obj, f] = obj.plotPartitions(obj.partitionGraphIndex, f);
end
function [obj, f] = run(obj, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Create axes if they don't already exist
f = firstPlotSetup(f);
% Set up times to iterate over
times = linspace(0, obj.timestep * obj.maxIter, obj.maxIter+1)';
partitioningTimes = times(obj.partitioningFreq:obj.partitioningFreq:size(times, 1));
% Start video writer
v = setupVideoWriter(obj.timestep);
v.open();
for ii = 1:size(times, 1)
% Display current sim time
t = times(ii);
fprintf("Sim Time: %4.2f (%d/%d)\n", t, ii, obj.maxIter)
% Check if it's time for new partitions
updatePartitions = false;
if ismember(t, partitioningTimes)
updatePartitions = true;
obj = obj.partition();
end
% Iterate over agents to simulate their motion
for jj = 1:size(obj.agents, 1)
obj.agents{jj} = obj.agents{jj}.run(obj.objective, obj.domain, obj.partitioning);
end
% Update adjacency matrix
obj = obj.updateAdjacency;
% Update plots
[obj, f] = obj.updatePlots(f, updatePartitions);
% Write frame in to video
I = getframe(f);
v.writeVideo(I);
end
% Close video file
v.close();
end
function obj = partition(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Assess sensing performance of each agent at each sample point
% in the domain
agentPerformances = cellfun(@(x) reshape(x.sensorModel.sensorPerformance(x.pos, x.pan, x.tilt, [obj.objective.X(:), obj.objective.Y(:), zeros(size(obj.objective.X(:)))]), size(obj.objective.X)), obj.agents, 'UniformOutput', false);
agentPerformances = cat(3, agentPerformances{:});
% Get highest performance value at each point
[~, idx] = max(agentPerformances, [], 3);
% Collect agent indices in the same way
agentInds = cellfun(@(x) x.index * ones(size(obj.objective.X)), obj.agents, 'UniformOutput', false);
agentInds = cat(3, agentInds{:});
% Get highest performing agent's index
[m,n,~] = size(agentInds);
[i,j] = ndgrid(1:m, 1:n);
obj.partitioning = agentInds(sub2ind(size(agentInds), i, j, idx));
end
function [obj, f] = updatePlots(obj, f, updatePartitions)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
updatePartitions (1, 1) logical = false;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Update agent positions, collision geometries
for ii = 1:size(obj.agents, 1)
obj.agents{ii}.updatePlots();
end
% The remaining updates might be possible to do in a clever way
% that moves existing lines instead of clearing and
% re-plotting, which is much better for performance boost
% Update agent connections plot
delete(obj.connectionsPlot);
[obj, f] = obj.plotConnections(obj.spatialPlotIndices, f);
% Update network graph plot
delete(obj.graphPlot);
[obj, f] = obj.plotGraph(obj.networkGraphIndex, f);
% Update partitioning plot
if updatePartitions
delete(obj.partitionPlot);
[obj, f] = obj.plotPartitions(obj.partitionGraphIndex, f);
end
% reset plot limits to fit domain
for ii = 1:size(obj.spatialPlotIndices, 2)
xlim(f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(1), obj.domain.maxCorner(1)]);
ylim(f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(2), obj.domain.maxCorner(2)]);
zlim(f.Children(1).Children(obj.spatialPlotIndices(ii)), [obj.domain.minCorner(3), obj.domain.maxCorner(3)]);
end
drawnow;
end
function obj = updateAdjacency(obj)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
end
% Initialize assuming only self-connections
A = logical(eye(size(obj.agents, 1)));
% Check lower triangle off-diagonal connections
for ii = 2:size(A, 1)
for jj = 1:(ii - 1)
if norm(obj.agents{ii}.pos - obj.agents{jj}.pos) <= min([obj.agents{ii}.comRange, obj.agents{jj}.comRange])
% Make sure that obstacles don't obstruct the line
% of sight, breaking the connection
for kk = 1:size(obj.obstacles, 1)
if ~obj.obstacles{kk}.containsLine(obj.agents{ii}.pos, obj.agents{jj}.pos)
A(ii, jj) = true;
end
end
% need extra handling for cases with no obstacles
if isempty(obj.obstacles)
A(ii, jj) = true;
end
end
end
end
obj.adjacency = A | A';
end
function [obj, f] = plotConnections(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Iterate over lower triangle off-diagonal region of the
% adjacency matrix to plot communications links between agents
X = []; Y = []; Z = [];
for ii = 2:size(obj.adjacency, 1)
for jj = 1:(ii - 1)
if obj.adjacency(ii, jj)
X = [X; obj.agents{ii}.pos(1), obj.agents{jj}.pos(1)];
Y = [Y; obj.agents{ii}.pos(2), obj.agents{jj}.pos(2)];
Z = [Z; obj.agents{ii}.pos(3), obj.agents{jj}.pos(3)];
end
end
end
X = X'; Y = Y'; Z = Z';
% Plot the connections
if isnan(ind)
hold(f.CurrentAxes, "on");
o = plot3(f.CurrentAxes, X, Y, Z, 'Color', 'g', 'LineWidth', 2, 'LineStyle', '--');
hold(f.CurrentAxes, "off");
else
hold(f.Children(1).Children(ind(1)), "on");
o = plot3(f.Children(1).Children(ind(1)), X, Y, Z, 'Color', 'g', 'LineWidth', 2, 'LineStyle', '--');
hold(f.Children(1).Children(ind(1)), "off");
end
% Copy to other plots
if size(ind, 2) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(:, 1), f.Children(1).Children(ind(ii)))];
end
end
obj.connectionsPlot = o;
end
function [obj, f] = plotPartitions(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
if isnan(ind)
hold(f.CurrentAxes, 'on');
o = imagesc(f.CurrentAxes, obj.partitioning);
hold(f.CurrentAxes, 'off');
else
hold(f.Children(1).Children(ind(1)), 'on');
o = imagesc(f.Children(1).Children(ind(1)), obj.partitioning);
hold(f.Children(1).Children(ind(1)), 'on');
if size(ind, 2) > 1
for ii = 2:size(ind, 2)
o = [o, copyobj(o(1), f.Children(1).Children(ind(ii)))];
end
end
end
obj.partitionPlot = o;
end
function [obj, f] = plotGraph(obj, ind, f)
arguments (Input)
obj (1, 1) {mustBeA(obj, 'miSim')};
ind (1, :) double = NaN;
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')} = figure;
end
arguments (Output)
obj (1, 1) {mustBeA(obj, 'miSim')};
f (1, 1) {mustBeA(f, 'matlab.ui.Figure')};
end
% Form graph from adjacency matrix
G = graph(obj.adjacency, 'omitselfloops');
% Plot graph object
if isnan(ind)
hold(f.CurrentAxes, 'on');
o = plot(f.CurrentAxes, G, 'LineStyle', '--', 'EdgeColor', 'g', 'NodeColor', 'k', 'LineWidth', 2);
hold(f.CurrentAxes, 'off');
else
hold(f.Children(1).Children(ind(1)), 'on');
o = plot(f.Children(1).Children(ind(1)), G, 'LineStyle', '--', 'EdgeColor', 'g', 'NodeColor', 'k', 'LineWidth', 2);
hold(f.Children(1).Children(ind(1)), 'off');
if size(ind, 2) > 1
for ii = 2:size(ind, 2)
o = [o; copyobj(o(1), f.Children(1).Children(ind(ii)))];
end
end
end
obj.graphPlot = o;
end
end
methods (Access = private)
function validateInitialization(obj)
% Assert obstacles do not intersect with the domain
% Assert obstacles do not intersect with each other
% Assert the objective has only one maxima within the domain
% Assert the objective's sole maximum is not inaccessible due
% to the placement of an obstacle
end
function validateLoop(obj)
% Assert that agents are safely inside the domain
% Assert that agents are not in proximity to obstacles
% Assert that agents are not in proximity to each other
% Assert that agents form a connected graph
end
end
end

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="@fixedCardinalSensor" type="File"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="@sigmoidSensor" type="File"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="sensingModels" Type="Relative"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="420d04e4-3880-4a45-8609-11cb30d87302" type="Reference"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="util/validators" Type="Relative"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="1bb12f2e-385b-41a4-83e8-f9a9326d95ee" type="Reference"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="test" Type="Relative"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="89c37511-fb1f-420e-919a-c5b38c02b501" type="Reference"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="util/validators/arguments" Type="Relative"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="30f974f9-50a8-405c-9a83-e7fd84333f0e" type="Reference"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="guidanceModels" Type="Relative"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="1d8d2b42-2863-4985-9cf2-980917971eba" type="Reference"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="validators" Type="Relative"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="5f96e524-3aac-4fa1-95df-67fd6ce02ff3" type="Reference"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="validators/arguments" Type="Relative"/>

View File

@@ -1,2 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="b7c7eec5-a318-4c17-adb2-b13a21bf0609" type="Reference"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="sensorModels" Type="Relative"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="d143c27d-6824-4569-9093-8150b60976cb" type="Reference"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info Ref="util" Type="Relative"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="2e3f60de-3b82-4ad5-af81-57781353dcbf" type="Reference"/>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info>
<Category UUID="FileClassCategory">
<Label UUID="test"/>
</Category>
</Info>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="test_sigmoidSensor.m" type="File"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="random.m" type="File"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="containsLine.m" type="File"/>

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Info location="spherical.m" type="File"/>

Some files were not shown because too many files have changed in this diff Show More