plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github
|
Roboy/roboy_darkroom-master
|
datadump.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/datadump.m
| 1,072 |
utf_8
|
a6d8c5d1e2c330b66626e585e43ff721
|
function datadump(data)
recurse(data, 0, []);
end
function result = recurse(data, level, addit)
indent = repmat(' | ',1,level);
if iscell(data) && ~ismymatrix(data)
result = iter_cell(data, level, addit);
elseif isstruct(data)
result = iter_struct(data, level, addit);
else
fprintf([indent,' +-Some data: ']);
disp(data);
result = data;
end;
end
function result = iter_cell(data, level, addit)
indent = repmat(' | ',1,level);
result = {};
fprintf([indent,'cell {\n']);
for i = 1:length(data)
result{i} = recurse(data{i}, level + 1, addit);
end;
fprintf([indent,'} cell\n']);
end
function result = iter_struct(data, level, addit)
indent = repmat(' | ',1,level);
result = struct();
fprintf([indent,'struct {\n']);
for i = fields(data)'
fld = char(i);
fprintf([indent,' +-field ',fld,':\n']);
result.(fld) = recurse(data.(fld), level + 1, addit);
end;
fprintf([indent,'} struct\n']);
end
|
github
|
Roboy/roboy_darkroom-master
|
ReadYaml.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/ReadYaml.m
| 2,780 |
utf_8
|
434901add453af4ae87764737b8b421c
|
%==========================================================================
% Actually reads YAML file and transforms it using several mechanisms:
%
% - Transforms mappings and lists into Matlab structs and cell arrays,
% for timestamps uses DateTime class, performs all imports (when it
% finds a struct field named 'import' it opens file(s) named in the
% field content and substitutes the filename by their content.
% - Deflates outer imports into inner imports - see deflateimports(...)
% for details.
% - Merges imported structures with the structure from where the import
% was performed. This is actually the same process as inheritance with
% the difference that parent is located in a different file.
% - Does inheritance - see doinheritance(...) for details.
% - Makes matrices from cell vectors - see makematrices(...) for details.
%
% Parameters:
% filename ... name of an input yaml file
% nosuchfileaction ... Determines what to do if a file to read is missing
% 0 or not present - missing file will only throw a
% warning
% 1 - missing file throws an
% exception and halts the process
% makeords ... Determines whether to convert cell array to
% ordinary matrix whenever possible (1).
% dictionary ... Dictionary of of labels that will be replaced,
% struct is expected
function result = ReadYaml(filename, nosuchfileaction, makeords, treatasdata, dictionary)
if ~exist('nosuchfileaction','var')
nosuchfileaction = 0;
end;
if ~ismember(nosuchfileaction,[0,1])
error('nosuchfileexception parameter must be 0,1 or missing.');
end;
if ~exist('makeords','var')
makeords = 0;
end;
if ~ismember(makeords,[0,1])
error('makeords parameter must be 0,1 or missing.');
end;
if(~exist('treatasdata','var'))
treatasdata = 0;
end;
if ~ismember(treatasdata,[0,1])
error('treatasdata parameter must be 0,1 or missing.');
end;
ry = ReadYamlRaw(filename, 0, nosuchfileaction, treatasdata);
ry = deflateimports(ry);
if iscell(ry) && ...
length(ry) == 1 && ...
isstruct(ry{1}) && ...
length(fields(ry{1})) == 1 && ...
isfield(ry{1},'import')
ry = ry{1};
end;
ry = mergeimports(ry);
ry = doinheritance(ry);
ry = makematrices(ry, makeords);
if exist('dictionary','var')
ry = dosubstitution(ry, dictionary);
end;
result = ry;
clear global nsfe;
end
|
github
|
Roboy/roboy_darkroom-master
|
doinheritance.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/doinheritance.m
| 3,279 |
utf_8
|
8ab1f9998935c4994858f87c9669cac9
|
%==========================================================================
% Searches through some hierarchy and performs inheritance. Whenever finds
% struct field named 'parent' it tries to find all points, defined by its
% content and uses them as the struct ancestors. Example:
%
% Given:
%
% s.a.a = 1
% s.a.b = 2
% s.a.parent: 'b'
%
% s.b.a = 3
% s.b.c = 4
%
% the result of r = doinheritance(s) is:
%
% r.a = 1
% r.c = 4
% r.b = 2
% r.parent = 'b'
%
% Multiple inheritance is allowed using cell array of parent point strings
% instead of one simple string.
%
%==========================================================================
function result = doinheritance(r, tr)
if ~exist('tr','var')
tr = r;
end;
result = recurse(r, 0, {tr});
end
function result = recurse(data, level, addit)
if iscell(data) && ~ismymatrix(data)
result = iter_cell(data, level, addit);
elseif isstruct(data)
result = iter_struct(data, level, addit);
else
result = data;
end;
end
function result = iter_cell(data, level, addit)
result = {};
for i = 1:length(data)
result{i} = recurse(data{i}, level + 1, addit);
end;
for i = 1:length(data)
if isstruct(result{i}) && isfield(result{i}, kwd_parent())
result{i} = inherit(result{i}, result{i}.(kwd_parent()), [], addit{1}, {}); % !!!
end;
end;
end
function result = iter_struct(data, level, addit)
result = data;
for i = fields(data)'
fld = char(i);
result.(fld) = recurse(data.(fld), level + 1, addit);
end;
for i = fields(result)'
fld = char(i);
if isstruct(result.(fld)) && isfield(result.(fld), kwd_parent())
result.(fld) = inherit(result.(fld), result.(fld).(kwd_parent()), [], addit{1}, {});
end;
end;
end
function result = inherit(child, parent_chr, container, oaroot, loc_imported)
result = child;
if ~iscell(parent_chr)
parent_chr = {parent_chr};
end;
for i = length(parent_chr):-1:1
if contains(loc_imported, parent_chr{i})
error('MATLAB:MATYAML:inheritedtwice',['Cyclic inheritance: ', parent_chr{i}]);
end;
try
parentstruct = eval(['oaroot.',parent_chr{i}]);
catch ex
switch ex.identifier
case {'MATLAB:nonExistentField', 'MATLAB:badsubscript'}
error('MATLAB:MATYAML:NonExistentParent', ['Parent was not found: ',parent_chr{i}]);
end;
rethrow(ex);
end;
if isstruct(parentstruct) && isfield(parentstruct, kwd_parent())
next_loc_imported = loc_imported;
next_loc_imported{end + 1} = parent_chr{i};
result = merge_struct(inherit(parentstruct, parentstruct.(kwd_parent()), [], oaroot, next_loc_imported), result, {'import'});
end;
result = merge_struct(parentstruct, result, {'import'});
end;
end
function result = contains(list, chr)
for i = 1:length(list)
if strcmp(list{i}, chr)
result = true;
return;
end;
end;
result = false;
end
|
github
|
Roboy/roboy_darkroom-master
|
WriteYaml.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/WriteYaml.m
| 7,008 |
utf_8
|
9b2a88b3fbb0257a77af09222129699c
|
%==========================================================================
% Recursively walks through a Matlab hierarchy and converts it to the
% hierarchy of java.util.ArrayListS and java.util.MapS. Then calls
% Snakeyaml to write it to a file.
%=========================================================================
function result = WriteYaml(filename, data, flowstyle)
if ~exist('flowstyle','var')
flowstyle = 0;
end;
if ~ismember(flowstyle, [0,1])
error('Flowstyle must be 0,1 or empty.');
end;
result = [];
[pth,~,~] = fileparts(mfilename('fullpath'));
try
import('org.yaml.snakeyaml.*');
javaObject('Yaml');
catch
dp = [pth filesep 'external' filesep 'snakeyaml-1.9.jar'];
if not(ismember(dp, javaclasspath ('-dynamic')))
javaaddpath(dp); % javaaddpath clears global variables...!?
end
import('org.yaml.snakeyaml.*');
end;
javastruct = scan(data);
dumperopts = DumperOptions();
dumperopts.setLineBreak(...
javaMethod('getPlatformLineBreak',...
'org.yaml.snakeyaml.DumperOptions$LineBreak'));
if flowstyle
classes = dumperopts.getClass.getClasses;
flds = classes(3).getDeclaredFields();
fsfld = flds(1);
if ~strcmp(char(fsfld.getName), 'FLOW')
error(['Accessed another field instead of FLOW. Please correct',...
'class/field indices (this error maybe caused by new snakeyaml version).']);
end;
dumperopts.setDefaultFlowStyle(fsfld.get([]));
end;
yaml = Yaml(dumperopts);
output = yaml.dump(javastruct);
if ~isempty(filename)
fid = fopen(filename,'w');
fprintf(fid,'%s',char(output) );
fclose(fid);
else
result = output;
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan(r)
if ischar(r)
result = scan_char(r);
elseif iscell(r)
result = scan_cell(r);
elseif isord(r)
result = scan_ord(r);
elseif isstruct(r)
result = scan_struct(r);
elseif isnumeric(r)
result = scan_numeric(r);
elseif islogical(r)
result = scan_logical(r);
elseif isa(r,'DateTime')
result = scan_datetime(r);
else
error(['Cannot handle type: ' class(r)]);
end
end
%--------------------------------------------------------------------------
%
%
function result = scan_numeric(r)
if isempty(r)
result = java.util.ArrayList();
else
result = java.lang.Double(r);
end
end
%--------------------------------------------------------------------------
%
%
function result = scan_logical(r)
if isempty(r)
result = java.util.ArrayList();
else
result = java.lang.Boolean(r);
end
end
%--------------------------------------------------------------------------
%
%
function result = scan_char(r)
if isempty(r)
result = java.util.ArrayList();
else
result = java.lang.String(r);
end
end
%--------------------------------------------------------------------------
%
%
function result = scan_datetime(r)
% datestr 30..in ISO8601 format
%java.text.SimpleDateFormat('yyyymmdd'T'HH:mm:ssz" );
[Y, M, D, H, MN,S] = datevec(double(r));
result = java.util.GregorianCalendar(Y, M-1, D, H, MN,S);
result.setTimeZone(java.util.TimeZone.getTimeZone('UTC'));
%tz = java.util.TimeZone.getTimeZone('UTC');
%cal = java.util.GregorianCalendar(tz);
%cal.set
%result = java.util.Date(datestr(r));
end
%--------------------------------------------------------------------------
%
%
function result = scan_cell(r)
if(isrowvector(r))
result = scan_cell_row(r);
elseif(iscolumnvector(r))
result = scan_cell_column(r);
elseif(ismymatrix(r))
result = scan_cell_matrix(r);
elseif(issingle(r));
result = scan_cell_single(r);
elseif(isempty(r))
result = java.util.ArrayList();
else
error('Unknown cell content.');
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_ord(r)
if(isrowvector(r))
result = scan_ord_row(r);
elseif(iscolumnvector(r))
result = scan_ord_column(r);
elseif(ismymatrix(r))
result = scan_ord_matrix(r);
elseif(issingle(r))
result = scan_ord_single(r);
elseif(isempty(r))
result = java.util.ArrayList();
else
error('Unknown ordinary array content.');
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_cell_row(r)
result = java.util.ArrayList();
for ii = 1:size(r,2)
result.add(scan(r{ii}));
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_cell_column(r)
result = java.util.ArrayList();
for ii = 1:size(r,1)
tmp = r{ii};
if ~iscell(tmp)
tmp = {tmp};
end;
result.add(scan(tmp));
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_cell_matrix(r)
result = java.util.ArrayList();
for ii = 1:size(r,1)
i = r(ii,:);
result.add(scan_cell_row(i));
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_cell_single(r)
result = java.util.ArrayList();
result.add(scan(r{1}));
end
%--------------------------------------------------------------------------
%
%
function result = scan_ord_row(r)
result = java.util.ArrayList();
for i = r
result.add(scan(i));
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_ord_column(r)
result = java.util.ArrayList();
for i = 1:size(r,1)
result.add(scan_ord_row(r(i)));
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_ord_matrix(r)
result = java.util.ArrayList();
for i = r'
result.add(scan_ord_row(i'));
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_ord_single(r)
result = java.util.ArrayList();
for i = r'
result.add(r);
end;
end
%--------------------------------------------------------------------------
%
%
function result = scan_struct(r)
result = java.util.LinkedHashMap();
for i = fields(r)'
key = i{1};
val = r.(key);
result.put(key,scan(val));
end;
end
|
github
|
Roboy/roboy_darkroom-master
|
selftest_yamlmatlab.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/Tests/selftest_yamlmatlab.m
| 2,954 |
utf_8
|
4b0ea27db95878c651e0c46855f39e18
|
function selftest_yamlmatlab(varargin)
% This function tests consistency of YAMLMatlab, by default, the results
% are stored in selftest_report.html in current work folder.
% Example
% >> selftest_yamlmatlab()
% >> selftest_yamlmatlab(outFileName)
%
% %======================================================================
%{
Copyright (c) 2011
This program is a result of a joined cooperation of Energocentrum
PLUS, s.r.o. and Czech Technical University (CTU) in Prague.
The program is maintained by Energocentrum PLUS, s.r.o. and
licensed under the terms of MIT license. Full text of the license
is included in the program release.
Author(s):
Jiri Cigler, Dept. of Control Engineering, CTU Prague
Jan Siroky, Energocentrum PLUS s.r.o.
Implementation and Revisions:
Auth Date Description of change
---- --------- -------------------------------------------------
jc 25-May-11 First implementation
%}
%======================================================================
fprintf('Running tests.\n');
outFname = 'selftest_report.html';
if numel(varargin)
outFname = varargin{1};
end
outStr = getHTMLHeader();
outStr = strcat(outStr,'<h1>Selftest report from:',datestr(now),'</h1>');
tests = dir([fileparts(which('selftest_yamlmatlab')) filesep 'test*.m']);
for test=tests'
[~,func]=fileparts(test.name);
fhandle = str2func(func);
stat = fhandle();
outStr = strcat(outStr, '<div id="MainTest"> <h2>',func, '</h2>', stat2html(stat,func),'</div>');
end
outStr = strcat(outStr,'</BODY></HTML>');
fid = fopen(outFname,'w');
fprintf(fid,outStr);
fclose(fid);
fprintf('Opening internal browser.\n');
web(outFname,'-new');
end
function html = stat2html(stat,name)
if not(isstruct(stat))
error('Input argument must be a struct');
end
html = '';
fn = fieldnames(stat);
if all(ismember({'ok','desc'},fn))
if stat.ok
flag = 'Passed';
else
flag = '<b style="color:red">Failed</b>,';
end
html = strcat(html,'<div id="Test"><h3>',name,': </h3> ', flag, ' <i>', stat.desc,'</i> </div>' );
end
html = [html, '<table>'];
for test = setdiff(fn',{'ok','desc'})
html = [html, '<tr>'];
html = strcat(html, stat2html(stat.(test{1}),test{1}));
html = [html, '</tr>'];
end
html = [html, '</table>'];
end
function str = getHTMLHeader()
str = [ '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' ...
'<HTML> ' ...
'<HEAD>'...
'<TITLE>::SELFTEST REPORT::</TITLE><STYLE> H2{color:blue} #MainTest{border: 1px blue solid;} h3,h4,h5,h6 {display: inline;} </STYLE>'...
'</HEAD><BODY style="font-family:Arial, helvetica">'];
end
|
github
|
Roboy/roboy_darkroom-master
|
test_ReadYaml.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/Tests/test_ReadYaml.m
| 8,883 |
utf_8
|
1647e455763d95a6c10948a007741f02
|
function stat = test_ReadYaml()
% this function tests reading in the yaml file
stat.ok = 1;
stat.desc = '';
try
%stat.test_ReadYaml_SimpleStructure = test_ReadYaml_SimpleStructure();
%stat.test_ReadYaml_DateTime = test_ReadYaml_DateTime();
fprintf('Testing read ');
stat.test_RY_Matrices = test_RY_Matrices();
fprintf('.');
stat.test_RY_Whitespaces = test_RY_Whitespaces();
fprintf('.');
stat.test_RY_FloatingPoints = test_RY_FloatingPoints();
fprintf('.');
stat.test_RY_Indentation = test_RY_Indentation();
fprintf('.');
stat.test_RY_SequenceMapping = test_RY_SequenceMapping();
fprintf('.');
stat.test_RY_Simple = test_RY_Simple();
fprintf('.');
stat.test_RY_Time = test_RY_Time();
fprintf('.');
stat.test_RY_TimeVariants = test_RY_TimeVariants();
fprintf('.');
stat.test_RY_Import = test_RY_Import();
fprintf('.');
stat.test_RY_ImportDef = test_RY_ImportDef();
fprintf('.');
stat.test_RY_ImportNonex = test_RY_ImportNonex();
fprintf('.');
stat.test_RY_Inheritance = test_RY_Inheritance();
fprintf('.');
stat.test_RY_InheritanceMultiple = test_RY_InheritanceMultiple();
fprintf('.');
stat.test_RY_InheritanceLoop = test_RY_InheritanceLoop();
fprintf('.');
stat.test_RY_usecase_01 = test_RY_usecase_01();
fprintf('.\n');
catch
stat.ok = 0;
stat.desc = 'Program crash';
end
end
function result = PTH_PRIMITIVES()
result = sprintf('Data%stest_primitives%s',filesep,filesep);
end
function result = PTH_IMPORT()
result = sprintf('Data%stest_import%s',filesep,filesep);
end
function result = PTH_INHERITANCE()
result = sprintf('Data%stest_inheritance%s',filesep,filesep);
end
function stat = test_RY_Matrices()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'matrices.yaml']);
tv = load([PTH_PRIMITIVES() 'matrices.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_FloatingPoints()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'floating_points.yaml']);
tv = load([PTH_PRIMITIVES() 'floating_points.mat']);
if ~isequalwithequalnans(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_Indentation()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'indentation.yaml']);
tv = load([PTH_PRIMITIVES() 'indentation.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_SequenceMapping()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'sequence_mapping.yaml']);
tv = load([PTH_PRIMITIVES() 'sequence_mapping.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_Simple()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'simple.yaml']);
tv = load([PTH_PRIMITIVES() 'simple.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_Time()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'time.yaml']);
tv = load([PTH_PRIMITIVES() 'time.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_TimeVariants()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'time_variants.yaml']);
tv = load([PTH_PRIMITIVES() 'time_variants.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_Import()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_IMPORT() 'import.yaml']);
tv = load([PTH_IMPORT() 'import.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_ImportDef()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_IMPORT() 'import_def.yaml']);
tv = load([PTH_IMPORT() 'import_def.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_ImportNonex()
stat.ok = 0;
stat.desc = 'Did not end with any exception.';
try
try
ry = ReadYaml([PTH_IMPORT() 'import_nonex.yaml'],1);
catch ex
if strcmp(ex.identifier, 'MATLAB:MATYAML:FileNotFound')
stat.desc = '';
stat.ok = 1;
else
rethrow(ex);
end;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_Inheritance()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_INHERITANCE() 'inheritance.yaml']);
tv = load([PTH_INHERITANCE() 'inheritance.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_InheritanceMultiple()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_INHERITANCE() 'inheritance_multiple.yaml']);
tv = load([PTH_INHERITANCE() 'inheritance_multiple.mat']);
if ~isequal(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_InheritanceLoop()
stat.ok = 0;
stat.desc = 'Did not end with any exception.';
try
try
ry = ReadYaml([PTH_INHERITANCE() 'inheritance_loop.yaml']);
catch ex
if strcmp(ex.identifier, 'MATLAB:MATYAML:inheritedtwice')
stat.desc = '';
stat.ok = 1;
else
rethrow(ex);
end;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_Whitespaces()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'whitespaces.yaml']);
if ~isfield(ry,'ImageFile') || ~isfield(ry,'ContoursCount')
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_RY_usecase_01()
stat.ok = 1;
stat.desc = '';
try
ry = ReadYaml([PTH_PRIMITIVES() 'usecase_struct_01.yaml']);
tv = load([PTH_PRIMITIVES() 'usecase_struct_01.mat']);
if ~isequalwithequalnans(ry, tv.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
function stat = test_ReadYaml_SimpleStructure()
stat.ok = 1;
stat.desc = '';
try
s = ReadYaml('simple.yaml');
ages = [s.age];
if not(isequal([33 27], ages)) || not(all(ismember({'John Smith', 'Mary Smith'}, {s.name}) ))
stat.desc = ' Wrong values loaded';
stat.ok = 0;
end
catch
stat.desc = 'Program crash';
stat.ok = 0;
end
end
function stat = test_ReadYaml_DateTime()
stat.ok = 1;
stat.desc = '';
try
s = ReadYaml('time.yaml');
if ~isa(s.Data.B1_S_SW{1},'DateTime')
stat.desc = ' Wrong data type of datetick';
stat.ok = 0;
end
if isa(s.Data.B1_S_SW{2},'DateTime')
stat.desc = ' Wrong data type of datetick';
stat.ok = 0;
end
catch
stat.desc = 'Program crash';
stat.ok = 0;
end
end
|
github
|
Roboy/roboy_darkroom-master
|
test_WriteYaml.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/YAMLREADER/Tests/test_WriteYaml.m
| 1,745 |
utf_8
|
de37cbde8a33d40a7b1f05ef8e7f16cf
|
function stat = test_WriteYaml()
stat.ok = 1;
stat.desc = '';
try
fprintf('Testing write ');
stat.test_WY_Matrices = test_WY_Universal(PTH_PRIMITIVES(), 'matrices');
fprintf('.');
stat.test_WY_FloatingPoints = test_WY_Universal(PTH_PRIMITIVES(), 'floating_points');
fprintf('.');
stat.test_WY_Indentation = test_WY_Universal(PTH_PRIMITIVES(), 'indentation');
fprintf('.');
stat.test_WY_SequenceMapping = test_WY_Universal(PTH_PRIMITIVES(), 'sequence_mapping');
fprintf('.');
stat.test_WY_Simple = test_WY_Universal(PTH_PRIMITIVES(), 'simple');
fprintf('.');
stat.test_WY_Time = test_WY_Universal(PTH_PRIMITIVES(), 'time');
fprintf('.');
stat.test_WY_ComplexStructure = test_WY_Universal(PTH_IMPORT(), 'import');
fprintf('.');
stat.test_WY_usecase_01 = test_WY_Universal(PTH_PRIMITIVES(), 'usecase_struct_01');
fprintf('.\n');
catch
stat.ok = 0;
stat.desc = 'Program crash';
end
end
function result = PTH_PRIMITIVES()
result = sprintf('Data%stest_primitives%s',filesep,filesep);
end
function result = PTH_IMPORT()
result = sprintf('Data%stest_import%s',filesep,filesep);
end
function result = PTH_INHERITANCE()
result = sprintf('Data%stest_inheritance%s',filesep,filesep);
end
function stat = test_WY_Universal(path, filename)
stat.ok = 1;
stat.desc = '';
try
data = load([path, filesep, filename, '.mat']);
WriteYaml('~temporary.yaml',data.testval);
ry = ReadYaml('~temporary.yaml');
if ~isequalwithequalnans(ry, data.testval)
stat.desc = 'Wrong values loaded';
stat.ok = 0;
end;
catch
stat.ok = 0;
stat.desc = 'Crash';
end;
end
|
github
|
Roboy/roboy_darkroom-master
|
calibration.m
|
.m
|
roboy_darkroom-master/darkroom/scripts/calibration/calibration.m
| 7,516 |
utf_8
|
9d4ef0c4049d2da1a69de8df06209b24
|
%% read the relative sensor locations from yaml
clear all
close all
config = ReadYaml('calibration.yaml');
rel_pos = cell2mat(config.sensor_relative_locations(:,2:end));
%% pose estimation
lighthouse_pose = eye(4);
% this is lighthouse to world pose
lighthouse_pose(2,4) = 1
numberOfFrames = 100
plot = false
pose_generator = 'random'
translation_range = 1
object_poses = cell(numberOfFrames,1);
object_pose_estimates = cell(numberOfFrames,1);
angles_true = cell(numberOfFrames,1);
angles_measured = cell(numberOfFrames,1);
calibration_scale = 10
calibration_values = [(rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale (rand()-0.5)/calibration_scale]
% calibration_values = [0 0 0.5 0.4 0 0 0 0];
if(plot)
g.figure1=figure('Name','simulated calibration values');
%config 3d plot
g.axes=axes('Linewidth',2,'DataAspectRatio',[1 1 1], ...
'XGrid','on','YGrid','on','ZGrid','on', ...
'XLim',[-1 1],'YLim',[0 1],'ZLim',[-1 1]);
view(0,0)
hold on
for i=90:10:90
elevation = i/180*pi;
for j=0:10:180
azimuth = j/180*pi;
ray = [cos(azimuth)*sin(elevation), sin(azimuth)*sin(elevation), -sin(azimuth)*cos(elevation)];
ray = ray/norm(ray);
[ele_calib, azi_calib] = applyCalibrationModel(elevation, azimuth, calibration_values);
ray_calib = [cos(azi_calib)*sin(ele_calib), sin(azi_calib)*sin(ele_calib), -sin(azi_calib)*cos(ele_calib)];
ray_calib = ray_calib/norm(ray_calib);
plot3([0 ray(1)],[0 ray(2)],[0 ray(3)],'g--')
plot3([0 ray_calib(1)],[0 ray_calib(2)],[0 ray_calib(3)],'r')
end
end
end
for frame=1:numberOfFrames
object_pose = eye(4);
switch(pose_generator)
case 'random'
% generate random object pose
phi = rand()*2*pi*0.1;
theta = rand()*pi*0.1;
psi = rand()*2*pi*0.1;
x = (rand()-0.5);
y = (rand()-0.5);
z = (rand()-0.5);
object_pose = [cos(psi) * cos(phi) - cos(theta) * sin(phi) * sin(psi), cos(psi) * sin(phi) + cos(theta) * cos(phi) * sin(psi), sin(psi) * sin(theta), x;
-sin(psi) * cos(phi) - cos(theta) * sin(phi) * cos(psi), -sin(psi) * sin(phi) + cos(theta) * cos(phi) * cos(psi), cos(psi) * sin(theta), y;
sin(theta) * sin(phi), -sin(theta) * cos(phi), cos(theta), z;
0, 0, 0, 1];
case 'rot_x'
% generate random object pose by rotation around x axis
phi = rand()*2*pi;
object_pose = [1 0 0 0;
0 cos(phi) -sin(phi) 0;
0 sin(phi) cos(phi) 0;
0 0 0 1];
case 'rot_y'
phi = rand()*2*pi;
object_pose = [cos(phi) 0 sin(phi) 0;
0 1 0 0;
-sin(phi) 0 cos(phi) 0;
0 0 0 1];
case 'rot_z'
phi = rand()*2*pi;
object_pose = [cos(phi) -sin(phi) 0 0;
sin(phi) cos(phi) 0 0;
0 0 1 0;
0 0 0 1];
case 'x'
x = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [x;0;0];
case 'y'
y = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [0;y;0];
case 'z'
z = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [0;0;z];
case 'xy'
x = (rand()-0.5)*translation_range;
y = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [x;y;0];
case 'yz'
y = (rand()-0.5)*translation_range;
z = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [0;y;z];
case 'xz'
x = (rand()-0.5)*translation_range;
z = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [x;0;z];
case 'xyz'
x = (rand()-0.5)*translation_range;
y = (rand()-0.5)*translation_range;
z = (rand()-0.5)*translation_range;
object_pose(1:3,4) = [x;y;z];
end
object_poses{frame} = object_pose;
true_pose = lighthouse_pose*object_pose;
[elevations_measured,azimuths_measured,elevations_true,azimuths_true] = calculateLighthouseAngles(rel_pos,true_pose,calibration_values);
ang_true = [elevations_true azimuths_true];
ang_measured = [elevations_measured azimuths_measured];
angles_true{frame} = ang_true;
angles_measured{frame} = ang_measured;
fun = @(x) poseMultiLighthouse(x, rel_pos, ang_measured, lighthouse_pose) ;
x0 = [0,0,0,0,0,0];
options = optimset('Display','off');
x = fsolve(fun,x0,options);
object_pose_estimate = createRTfrom(x);
object_pose_estimates{frame} = object_pose_estimate;
error = norm(object_pose_estimate-object_pose);
if(plot)
%config 3d plot
h.axes=axes('Linewidth',2,'DataAspectRatio',[1 1 1], ...
'XGrid','on','YGrid','on','ZGrid','on', ...
'XLim',[-0.5 0.5],'YLim',[-1 0.2],'ZLim',[-0.5 0.5]);
view(0,0)
plotCoordinateFrame(inv(lighthouse_pose),0.2,'lighthouse1')
plotCoordinateFrame(object_pose,0.2,'object')
plotLighthouseSensors(rel_pos,object_pose,'gx',8)
plotCoordinateFrame(object_pose_estimate,0.2,'object estimate')
plotLighthouseSensors(rel_pos,object_pose_estimate,'ro',8)
if(error<0.00001)
str = ['pose estimation successsful with error ' num2str(error)];
disp(str)
else
str = ['pose estimation failed with error ' num2str(error)];
disp(str)
end
object_pose
object_pose_estimate
pause;
clf
end
disp(frame)
end
%% calibration estimation
calibration_value_estimate = ones(size(calibration_values))*0.0001;
% calibration_value_estimate = [0 0 0.15 0.22 0 0 0 0];
fun = @(x) calibrationEstimator(x, rel_pos, object_poses, lighthouse_pose, angles_measured) ;
options = optimoptions('fsolve');
options.FunctionTolerance = 1.0000e-08;
options.OptimalityTolerance = 1.0000e-08;
calibration_values
calibration_value_estimate = fsolve(fun,calibration_value_estimate,options)
norm(calibration_value_estimate-calibration_values)
angles_estimate = angles_true;
angle_error = zeros(size(angles_true{1}));
for frame=1:numberOfFrames
[elevation_estimate, azimuth_estimate] = applyCalibrationModel(angles_true{frame}(:,1),angles_true{frame}(:,2),calibration_value_estimate);
angles_estimate{frame} = [elevation_estimate azimuth_estimate];
angle_error = angle_error + (angles_estimate{frame}-angles_measured{frame}).^2;
end
disp(angle_error)
function F = calibrationEstimator(x, rel_pos, object_poses, lighthouse_pose, angles_measured)
F = [0;0];
for frame=1:length(object_poses)
[elevations_estimate,azimuths_estimate] = calculateLighthouseAngles(rel_pos,lighthouse_pose*object_poses{frame},x);
for i=1:length(elevations_estimate)
F(1) = F(1) + (angles_measured{frame}(i,1)-elevations_estimate(i));
F(2) = F(2) + (angles_measured{frame}(i,2)-azimuths_estimate(i));
end
end
end
|
github
|
zhaohuajing/V2V-network-sensitivity-analysis-master
|
mean_err_MC_uniform.m
|
.m
|
V2V-network-sensitivity-analysis-master/mean_err_MC_uniform.m
| 2,596 |
utf_8
|
d1b354e64d6192a89888453831bff41e
|
%Numerically calculate an unbiased estimator for the expected CMM error by Monte Carlo simulation
function [nv,m_err]=mean_err_MC_uniform(sig_n2)
%load rand_angle.mat
% for N_v=15:15
% N_v
% angle=2*pi*rand(1,10);
% angle=[4.18473579635023,4.76497989105900,1.87071752652456,3.01069347870357,1.92007770503973,1.26918034736393,2.85125031627114,0.214647648900359];
% for jj=1:60
% for kk=1:60
% jj
% angle(11)=2*pi/60*jj;
% angle(12)=2*pi/60*kk;
% er(jj,kk)=square_error(angle,2,0.09);
% end
% end
for jj=10:50
% jj
angle=rand(1,jj)*2*pi;
%angle(9)=2*pi/60*jj;
clearvars -except jj mm N_v mean_error angle sig_n2
for mm=1:100
%mm
Np=1000;
%angle=(0:4*N_v-1)*pi/2;
%angle=rand(1,N_v)*2*pi;
%angle=[2.84054158477136,0.581356079534006,0.270717219775257,2.59491150573350,3.32870592904893,5.14107148506157,4.32780123945169,1.47165259096693,2.18578161834098,0.391802737491801];
%angle=2*pi/N_v*(0:N_v-1);
N=length(angle);
%N=8;
%large_noise=zeros(1,N);
% for k=1:N/4
% large_noise(4*k-floor(4*rand(1)))=1; %used to insert a large n-common error to the corresponding vehicles
% end
% if N_v>10
% large_noise(11:end)=1;
% end
width=2;
unit_vector=[];
points=[];
for k=1:N
unit_vector=[unit_vector,[cos(angle(k));sin(angle(k))]];
points=[points,width*[cos(angle(k));sin(angle(k))]];
end
common=[0;0];
n_common=[];
%sig_n2=1;
for k=1:N
n_common=[n_common,mvnrnd([0;0],(sig_n2)*[1,0;0,1])'];%+*large_noise(k)*(rand(2,1)-0.5)];
end
cor=(rand(2,Np)-0.5*ones(2,Np))*12;
% for k=1:Np
% cor(:,k)=mvnrnd([0;0],10*[1,0;0,1]);
% end
for k=1:Np;
pf(:,k)=cor(:,k)+common; %particle location
end
for k=1:Np
weight(1,k)=1;
for j=1:N
d=pf(:,k)+n_common(:,j)-points(:,j);
if dot(d,unit_vector(:,j))>0
d2=dot(d,unit_vector(:,j));
weight(1,k)=weight(1,k)*exp(-0.5/sig_n2*d2^2);
% weight(1,k)=0;
% break; %here is no break!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
end
end
end
weight=weight/sum(weight); %normilize the weight
common_cor(:,mm)=[0;0];
for k=1:Np
common_cor(:,mm)=common_cor(:,mm)+weight(k)*cor(:,k);
end
er(mm)=norm(common_cor(:,mm)+common);
er2(mm)=er(mm)^2;
if isnan(er2(mm))&mm>1
er2(mm)=mean(er2);
end
if isnan(er2(mm))&mm==1
er2(mm)=10;
end
end
mean_error(jj-9)=mean(er2);
end
nv=10:50;
m_err=mean_error;
end
%corr(a.',b.','type','Spearman')
%common_cor(:,mm)+common
|
github
|
zhaohuajing/V2V-network-sensitivity-analysis-master
|
MC_analytic.m
|
.m
|
V2V-network-sensitivity-analysis-master/MC_analytic.m
| 1,047 |
utf_8
|
075393ab09db204332273466018d9689
|
%Numerically calculate an unbiased estimator for the expected CMM error at a crossroad by Monte Carlo simulation
function [nv,m_err]=MC_analytic(sig)
for N_v_each=3:12;
% sig2=0.09;
% sig=sqrt(sig2);
for mm=1:5000
X1=max(randn(1,N_v_each)*sig);
X2=max(randn(1,N_v_each)*sig);
X3=max(randn(1,N_v_each)*sig);
X4=max(randn(1,N_v_each)*sig);
er2(mm)=0.25*(X1-X3)^2+0.25*(X2-X4)^2;
end
mean_error(N_v_each-2)=mean(er2);
end
nv=4*(3:12);
m_err=mean_error;
end
% clear all
%
% for N_v=10:50;
% sig2=0.09;
% sig=sqrt(sig2);
%
% for mm=1:5000
% N_each=ones(4,1);
% for k=1:N_v-4 %to ensure at least have one vehicle on one side
% a1=rand(1);
% N_each(ceil(a1/0.25))=N_each(ceil(a1/0.25))+1;
% end
%
%
% X1=max(randn(1,N_each(1))*sig);
% X2=max(randn(1,N_each(2))*sig);
% X3=max(randn(1,N_each(3))*sig);
% X4=max(randn(1,N_each(4))*sig);
% er2(mm)=0.25*(X1-X3)^2+0.25*(X2-X4)^2;
% end
% mean_error(N_v-9)=mean(er2);
% end
|
github
|
skojaku/km_config-master
|
km_config.m
|
.m
|
km_config-master/src/matlab/km_config.m
| 1,100 |
utf_8
|
6a78d3e991ee915e825171939fb5ac78
|
%
% MATLAB client for the KM-config algorithm
%
%
% An algorithm for finding multiple core-periphery pairs in networks
%
%
% Core-periphery structure requires something else in the network
% Sadamori Kojaku and Naoki Masuda
% Preprint arXiv:1710.07076
%
%
% Please do not distribute without contacting the authors.
%
%
% AUTHOR - Sadamori Kojaku
%
%
% DATE - 11 Oct 2017
function [cids, x, Q, q, p_vals] = km_config(A, varargin)
num_of_runs = 10;
num_of_rand_nets = 500;
alpha = 1;
if nargin >= 2; num_of_runs = varargin{1}; end
if nargin >= 3; alpha = varargin{2}; end
if nargin == 4; num_of_rand_nets = varargin{3}; end
if alpha > 1-1e-4; num_of_rand_nets = 0; end
[node_ids1, node_ids2, w] = find(triu(A, 1));
N = size(A, 1);
[cids, x, Q, q, p_vals] = km_config_mex([node_ids1, node_ids2, w], N, length(node_ids1), num_of_runs, num_of_rand_nets);
if alpha > 1-1e-4; return; end %
K = max(cids);
significant = p_vals <= ( 1 - (1 - alpha) ^(1 / size(K, 2)) );
x(~significant(cids)) = NaN;
cids(~significant(cids)) = NaN;
p_vals = p_vals(significant);
q = q(significant);
Q = sum(q);
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
compareGOannotations.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Genes/compareGOannotations.m
| 3,845 |
utf_8
|
7f9635759e746ee89717d759e5416403
|
% check if there are genes in worm from the categories used in mouse
% get a list of go categories in mouse and compare to the list in worm (for
% all posible genes)
% ------------------------------------------------------------------------------
% read in all txt files from mouse and combine unique GO categories in a
% list
function GOtable = compareGOannotations(C,G)
%-------------------------------------------------------------------------------
% Aurina Arnatkeviciute 13-04-2017
%
% This function compares GO annotations found in mouse by Fulcher PNAS 2016 to GO annotations available in C. elegans"
% 1. to all possible GO annotations in C elegans (from GO annotation file for the worm - all possible annotations generated using
% 2. to GO annotations for genes in C.elegans dataset (948 genes)
% 3. to GO annotations for genes in C.elegans dataset that were used for connected vs unconnected analysis (577 genes)
% 4. to GO annotations for genes in C.elegans dataset that were used for rich/feeder vs peripheral analysis (390 genes)
% INPUT: C and G structures.
% OUTPUT: a list of genes for each GO category that was matched geneListinSample (948, 577,390 gene samples used)
%-------------------------------------------------------------------------------
load('GOAnnotation.mat');
types = {'conBP', 'conBPCC', 'rfBP', 'rfBPCC'};
GOmouse = cell(length(types),1);
for t=1:length(types)
filePath = sprintf('Data/ermineJdata/mouseGO%s.txt', types{t});
fid = fopen(filePath,'r');
% headings = textscan(fid,'%s %s %s %s %s %s %s %s %s %s %s %s %s',1,'Delimiter','\t','CollectOutput',1);
GOmouse{t} = textscan(fid,'%s%s%*[^\n\r]','Delimiter','\t'); %,'EndOfLine','\n');
fclose(fid);
%textscan(fid,'%s%s%s%*[^\n\r]','Delimiter',' & ','EndOfLine','\n');
end
GOids = [GOmouse{1}{1,1};GOmouse{2}{1,1};GOmouse{3}{1,1};GOmouse{4}{1,1}];
GOnames = [GOmouse{1}{1,2};GOmouse{2}{1,2};GOmouse{3}{1,2};GOmouse{4}{1,2}];
f_ind = @(x)str2num(x(5:end));
GOlistmouse = cellfun(f_ind,GOids);
[~, indGOmouseANDworm] = intersect(allGOCategories, GOlistmouse);
[~, indS] = intersect(GOlistmouse, allGOCategories);
GOmouseANDwormNames = GOnames(indS);
% ------------------------------------------------------------------------------
% get genes with matching categories in worm
genesWORM = geneAcronymAnnotations(indGOmouseANDworm);
% for each GO category, check how many genes we have in our list of 948
% genes.
% all genes
geneListALL = G.geneAcronyms.Direct;
% genes for connected vs unconnected analysis
[~,geneScoresCON,~] = GCCbinomial(C,G,'Connected',true,false);
geneListCON= geneScoresCON.geneName;
%genes for Rich feeder analysis
[~,geneScoresRF,~] = GCCbinomial(C,G,'RichFeeder',true,false);
geneListRF= geneScoresRF.geneName;
geneListinSample = cell(length(genesWORM),4);
analysis = {'all', 'connected', 'richfeeder'};
for anal=analysis
for j=1:length(genesWORM)
GOcategory = genesWORM{j};
if strcmp(anal,'all')
geneListinSample{j,1} = intersect(GOcategory, geneListALL);
elseif strcmp(anal,'connected')
geneListinSample{j,2} = intersect(GOcategory, geneListCON);
elseif strcmp(anal,'richfeeder')
geneListinSample{j,3} = intersect(GOcategory, geneListRF);
end
end
end
geneListinSample(:,4) = GOmouseANDwormNames;
GOtable = table();
GOtable.list948genesALL = geneListinSample(:,1);
GOtable.list577genesCON = geneListinSample(:,2);
GOtable.list390genesRF = geneListinSample(:,3);
GOtable.GOcategories = geneListinSample(:,4);
filePath = fullfile('Data','ermineJdata','GOannotationsCompared.mat');
save(filePath,'GOtable');
fprintf(1,'Saved to %s\n',filePath);
%-------------------------------------------------------------------------------
%-------------------------------------------------------------------------------
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
AdjLabelNodes.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Both/AdjLabelNodes.m
| 2,442 |
utf_8
|
efff47d0cbf1f2161c5dedaa203b43e4
|
% Ben Fulcher, 2014-10-01
% Labels nodes according to their links to/from the rich club
% Modified by Taqi Ali 17-7-15
% ------------------------------------------------------------------------------
function [nodeLabels,labelNames,nodeData] = AdjLabelNodes(labelWhat,Adj,extraParam,networkType)
if nargin < 4
networkType = 'bd';
end
numNodes = length(Adj);
% ------------------------------------------------------------------------------
% Basic functions:
% ------------------------------------------------------------------------------
% Total degree:
switch networkType
case {'bu','wu'}
totDegree = @(x) sum(x,2); % just choose one sided connections
case {'bd','wd'}
totDegree = @(x) (sum(x,1)' + sum(x,2)); % outputs a column vector
end
% ------------------------------------------------------------------------------
% Do the labeling:
% ------------------------------------------------------------------------------
switch labelWhat
case {'hub-kth','hub-topN'}
if strcmp(labelWhat,'hub-topN')
warning('hub-topN doesn''t work the best yet');
end
if nargin < 3
extraParam = {'degree',50};
end
whatDegree = extraParam{1};
switch whatDegree
case 'degree'
nodeData = totDegree(Adj);
end
kth = extraParam{2};
isHub = (nodeData > kth);
nodeLabels = isHub + 1;
labelNames = {'non-hub',sprintf('hub (k > %u)',kth)};
case 'RichFeed'
% Ben Fulcher, 2014-10-01
kth = extraParam{2}; % threshold on degree to count as rich
% 1. Get total degree of each node:
nodeData = totDegree(Adj);
isHub = (nodeData >= kth);
nodeLabels = zeros(numNodes,1);
linksToHub = (Adj*isHub > 0);
linksFromHub = (isHub'*Adj > 0)';
nodeLabels(isHub) = 1; % Hubs
nodeLabels(~isHub & linksToHub & ~linksFromHub) = 2; % Feed-in
nodeLabels(~isHub & ~linksToHub & linksFromHub) = 3; % Feed-out
nodeLabels(~isHub & linksToHub & linksFromHub) = 4; % Feed-in-out
nodeLabels(~isHub & ~linksToHub & ~linksFromHub) = 5; % Local
labelNames = {sprintf('hub (%u)',sum(sum(nodeLabels==1))),...
sprintf('feed-in (%u)',sum(sum(nodeLabels==2))),...
sprintf('feed-out (%u)',sum(sum(nodeLabels==3))),...
sprintf('feed-in-out (%u)',sum(sum(nodeLabels==4))),...
sprintf('local (%u)',sum(sum(nodeLabels==5)))};
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
coexpELCHUncon.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Both/coexpELCHUncon.m
| 3,600 |
utf_8
|
c8c9715b1605bf0a956bbd4428bc0bd0
|
%% [p, stats] = coexpConnUncon (C, G, connectivityType, anatomyPart, dorankedTest)
% ------------------------------------------------------------------------------
% function compares and plots coexpression between pairs of neurons that are connected with electrical, chemical synapses as well as pairs of unconnected neurons.
% links in Celegans connectome.
% ------------------------------------------------------------------------------
% Inputs
% ------------------------------------------------------------------------------
% C (connectivity structure), G (gene structure) should be loaded;
% coexpMeasure - choose coexpression measure as defined in G.Corr. default Pearson_noLR
% dorankedTest - true (will do ranksum test to compare distributions), false - will do ttest2 to compare distributions.
%% ------------------------------------------------------------------------------
% Outputs
% ------------------------------------------------------------------------------
% p - p value from the test comparing distributions for connected and unconnected links
% stats - stats output from the test comparing distributions for connected and unconnected links.
% ------------------------------------------------------------------------------
% Aurina Arnatkeviciute, 2016-12-20
% ------------------------------------------------------------------------------
function [dataCell, S,P] = coexpELCHUncon (C, G, dorankedTest, doOnly)
if nargin < 3
dorankedTest = true;
fprintf(1,'Using rank test BY DEFAULT\n');
end
if nargin < 4
doOnly = false;
end
Adj = GiveMeAdj(C);
maskisLR = GiveMeLRMask(C);
if doOnly == true
mask = GiveMeMask(C,'hubType','bu',Adj);
Chemical = mask.chemicalOnly & ~maskisLR;
Electrical = mask.electricalOnly & ~maskisLR;
%Unc = mask.none;
else
mask = GiveMeMask(C,'hubType','bu', Adj);
Chemical=GiveMeAdj(C,'zeroBinary', 'ch') & ~maskisLR;
Electrical=GiveMeAdj(C,'zeroBinary', 'el') & ~maskisLR;
end
coexpression = GiveMeCoexpression(G,[],false);
coexpression = coexpression.*~maskisLR;
Both = mask.chelboth|mask.chelboth' & ~maskisLR;
Con = mask.either;
Con = Con|Con' & ~maskisLR;
Unc = ~Con & ~maskisLR;
Con = triu(Con,1);
Unc = triu(Unc,1);
Uncon = coexpression.*Unc;
Chemical = Chemical|Chemical';
Chemical = triu(coexpression.*Chemical,1);
Electrical = Electrical|Electrical';
Electrical = triu(coexpression.*Electrical,1);
Con = coexpression.*Con;
Both = triu(coexpression.*Both,1);
% exclude zeros
Uncon = nonzeros(Uncon);
Chemical = nonzeros(Chemical);
Electrical = nonzeros(Electrical);
Both = nonzeros(Both);
Con = nonzeros(Con);
% compare distributions
if dorankedTest==false
[~,P.pEC,~,S.statsEC] = ttest2(Electrical,Chemical, 'Vartype','unequal');
[~,P.pCU,~,S.statsCU] = ttest2(Con,Uncon, 'Vartype','unequal');
elseif dorankedTest==true
[P.pEC,~,S.statsEC] = ranksum(Electrical,Chemical);
[P.pCU,~,S.statsCU] = ranksum(Con, Uncon);
%[P.pBC,~,S.statsBC] = ranksum(Both, Chemical);
%[P.pBE,~,S.statsBE] = ranksum(Both, Electrical);
end
if doOnly==true
dataCell{1,1} = Electrical; dataCell{2,1} = Chemical; dataCell{3,1} = Both; dataCell{4,1} = Uncon;
else
dataCell{1,1} = Electrical; dataCell{2,1} = Chemical; dataCell{3,1} = Uncon;
end
% xLabels = {'Connected', 'Unconnected'};
%
% JitteredParallelScatter(dataCell)
%
% set(gca,'Xtick', [1 2], 'XTickLabel',xLabels, 'FontSize', 15);
% set(gca,'Ytick', [0 0.2 0.4 0.6 0.8 1], 'YTickLabel',[0 0.2 0.4 0.6 0.8 1], 'FontSize', 15);
% set(gca,'box','off');
% ylabel('Coexpression','FontSize', 15);
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
coexpRecUnidirUncon.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Both/coexpRecUnidirUncon.m
| 2,470 |
utf_8
|
6d35b058bd9a3ac9c65d337b2ff4b552
|
% ------------------------------------------------------------------------------
% Aurina Arnatkeviciute
% ------------------------------------------------------------------------------
% script for checking reciplocally/unidirctionally connected and unconnected link coexpression using
% Pearson coexpression
% ------------------------------------------------------------------------------
function [p, S, dataCell] = coexpRecUnidirUncon (C, G, conType, anatomyPart, test)
% test - ttest or ranksum
if nargin < 3
Adj = GiveMeAdj(C,'zeroBinary');
end
if nargin < 4
anatomyPart = 'whole';
end
if nargin < 5
test = 'ranksum';
fprintf(1,'Comparing distributions with ranksum test BY DEFAULT\n');
end
if nargin < 6
coexpression = GiveMeCoexpression(G,[],true);
end
switch anatomyPart
case 'whole'
coexpression = GiveMeCoexpression(G,[],true);
case 'head'
head = C.RegionM(:,9);
Adj = Adj(head == 1, head == 1);
coexpression = coexpression(head == 1, head == 1);
end
NaNmatrix = nan(size(coexpression,1),size(coexpression,1));
NaNmatrix = tril(NaNmatrix);
Adj = Adj+Adj';
maskRecip = Adj==2;
maskRecip = maskRecip+NaNmatrix;
maskUnidir = Adj==1;
maskUnidir = maskUnidir+NaNmatrix;
% Adj(Adj == 0) = NaN;
Unc = Adj == 0;
Unc = Unc+NaNmatrix;
Uncon = coexpression.*Unc;
Rec = coexpression.*maskRecip;
Unidir = coexpression.*maskUnidir;
% if only electrical synapses are chosen, use one half of the matrix
% (symetrical)
if strcmp(conType, 'el')
Uncon = triu(Uncon,1);
Con = triu(Con,1);
end
Rec = nonzeros(Rec);
Rec=(Rec(~isnan(Rec)));
Unidir = nonzeros(Unidir);
Unidir=(Unidir(~isnan(Unidir)));
Uncon = nonzeros(Uncon);
Uncon=(Uncon(~isnan(Uncon)));
%JitteredParallelScatter(dataCell)
%ylabel('Average coexpression'); legend('Connecteced', 'Unconnected');
switch test
case 'ttest'
[~,p.RecUnidir,~,S.RecUnidir] = ttest2(Rec,Unidir, 'Vartype','unequal');
[~,p.UnidirUncon,~,S.UnidirUncon] = ttest2(Unidir,Uncon, 'Vartype','unequal');
[~,p.RecUncon,~,S.RecUncon] = ttest2(Rec,Uncon, 'Vartype','unequal');
dataCell{1,1} = Rec; dataCell{2,1} = Unidir; dataCell{3,1} = Uncon;
case 'ranksum'
[p.RecUnidir,~,S.RecUnidir] = ranksum(Rec,Unidir);
[p.UnidirUncon,~,S.UnidirUncon] = ranksum(Unidir,Uncon);
[p.RecUncon,~,S.RecUncon] = ranksum(Rec,Uncon);
dataCell{1,1} = Rec; dataCell{2,1} = Unidir; dataCell{3,1} = Uncon;
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
coexpConnUncon.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Both/coexpConnUncon.m
| 3,265 |
utf_8
|
8794762ceb527d6f932a3fff97cc603f
|
%% [p, stats] = coexpConnUncon (C, G, connectivityType, anatomyPart, dorankedTest)
% ------------------------------------------------------------------------------
% function compares and plots coexpression for connected and unconnected
% links in Celegans connectome.
% ------------------------------------------------------------------------------
% Inputs
% ------------------------------------------------------------------------------
% C (connectivity structure), G (gene structure) should be loaded;
% coexpMeasure - choose coexpression measure as defined in G.Corr. default Pearson_noLR
% connectivityType: chemical synapses - 'ch', electrical synapses - 'el', chemical + electrical synapses - 'all'
% anatomyPart: perform calculation on the whole nervous system - 'wholeNervousSystem'; perform calculations only on head neurons - 'headOnly'
% dorankedTest - true (will do ranksum test to compare distributions), false - will do ttest2 to compare distributions.
%% ------------------------------------------------------------------------------
% Outputs
% ------------------------------------------------------------------------------
% p - p value from the test comparing distributions for connected and unconnected links
% stats - stats output from the test comparing distributions for connected and unconnected links.
% ------------------------------------------------------------------------------
% Aurina Arnatkeviciute, 2016-12-20
% ------------------------------------------------------------------------------
function [dataCell, p, stats] = coexpConnUncon (C, G, anatomyPart, dorankedTest)
if nargin < 3
anatomyPart = 'wholeNervousSystem';
fprintf(1,'Using whole nervous system BY DEFAULT\n');
end
if nargin < 4
dorankedTest = true;
fprintf(1,'Using rank test BY DEFAULT\n');
end
coexpression = GiveMeCoexpression(G,[],true);
Adj = GiveMeAdj(C,'zeroBinary');
numNeurons = size(Adj,1);
switch anatomyPart
case 'wholeNervousSystem'
coexpression = GiveMeCoexpression(G,[],true); %Pearson_noLR;
case 'headOnly'
coexpression = GiveMeCoexpression(G,[],true);
head = C.RegionM(:,9);
Adj = Adj(head == 1, head == 1);
coexpression = coexpression(head == 1, head == 1);
end
NaNmatrix = nan(numNeurons,numNeurons);
NaNmatrix = tril(NaNmatrix,-1);
Adj = triu(logical(Adj+Adj'),1)+0;
Adj = Adj+NaNmatrix;
% get a mask for unconnected links
Unc = Adj == 0;
% get a mask for connected links
Con = Adj == 1;
Uncon = coexpression.*Unc;
Con = coexpression.*Con;
Uncon(1:size(Uncon,1)+1:end) = nan;
Con(1:size(Con,1)+1:end) = nan;
% exclude NaNs and zeros
Uncon = nonzeros(Uncon);
Uncon=(Uncon(~isnan(Uncon)));
Con = nonzeros(Con);
Con=(Con(~isnan(Con)));
% compare distributions
if dorankedTest==false
[h,p,ci,stats] = ttest2(Con,Uncon, 'Vartype','unequal');
elseif dorankedTest==true
[p,h,stats] = ranksum(Con,Uncon);
end
dataCell{1,1} = Con; dataCell{2,1} = Uncon;
% xLabels = {'Connected', 'Unconnected'};
%
% JitteredParallelScatter(dataCell)
%
% set(gca,'Xtick', [1 2], 'XTickLabel',xLabels, 'FontSize', 15);
% set(gca,'Ytick', [0 0.2 0.4 0.6 0.8 1], 'YTickLabel',[0 0.2 0.4 0.6 0.8 1], 'FontSize', 15);
% set(gca,'box','off');
% ylabel('Coexpression','FontSize', 15);
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
giveDistributions.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Both/giveDistributions.m
| 2,510 |
utf_8
|
9cb9ba4d9fd2592173dbf66cdfc7942b
|
% ------------------------------------------------------------------------------
% Aurina Arnatkeviciute,
% make violin plots for rich/feeder/peripheral/unconnected for a chosen hub
% threshold. Can change to lineage matrix instead of coexpression matrix
% ------------------------------------------------------------------------------
function [dataCell, P2, S2] = giveDistributions(C, G, type)
if nargin <3
type = 'all';
end
Adj = GiveMeAdj(C, 'zeroBinary', type);
[~,~,deg] = degrees_dir(Adj);
Adj = Adj|Adj';
Adj = triu(Adj,1);
NaNmatrix = nan(279,279);
NaNmatrix = tril(NaNmatrix,-1);
Adj = Adj+NaNmatrix;
correlation = GiveMeCoexpression(G,'',true); % C.LineageDistance;GiveMeCoexpression(G,'',true); %
if strcmp(type, 'ch')
D = GiveMeDefault('synaptic');
elseif strcmp(type, 'all')
D = GiveMeDefault('all');
end
k=D.kHub;
%[~,~,deg] = degrees_dir(Adj);
numNeurons = C.numNeurons;
hub = deg>k;
mask = zeros(numNeurons,numNeurons);
mask(hub, hub)=1;
mask(~hub, hub)=2;
mask(hub, ~hub)=3;
mask(~hub,~hub)=4;
mask = mask.*Adj;
rich = mask==1;
rich = nonzeros(rich.*correlation);
dataCell{4,1} = rich(~isnan(rich));
feedin = mask==2;
feedin = nonzeros(feedin.*correlation);
dataCell{2,1} = feedin(~isnan(feedin));
feedout = mask==3;
feedout = nonzeros(feedout.*correlation);
dataCell{3,1} = feedout(~isnan(feedout));
peripheral = mask==4;
peripheral = nonzeros(peripheral.*correlation);
dataCell{1,1} = peripheral(~isnan(peripheral));
%JitteredParallelScatterAA(dataCell)
[P2.RF,~,S2.RF] = ranksum(rich,feedin);
[P2.FinFout,~,S2.FinFout] = ranksum(feedin, feedout); %,'Vartype','unequal','Tail','right');
[P2.FoutP,~,S2.FoutP] = ranksum(feedout,peripheral);%,'Vartype','unequal','Tail','right');
[P2.FinP,~,S2.FinP] = ranksum(feedin,peripheral); %,'Vartype','unequal','Tail','right');
[P2.RP,~,S2.RP] = ranksum(rich,peripheral); %,'Vartype','unequal','Tail','right');
%[~,p6,~,stat6] = ttest2(feedin,nonzeros(peripheral),'Vartype','unequal','Tail','right');
% [~,p1,~,stat1] = ttest2(rich,feedin,'Vartype','unequal','Tail','right');
% [~,p2,~,stat2] = ttest2(feedin, feedout,'Vartype','unequal','Tail','right');
% [~,p3,~,stat3] = ttest2(feedout,nonzeros(peripheral),'Vartype','unequal','Tail','right');
% [~,p4,~,stat4] = ttest2(rich,feedout,'Vartype','unequal','Tail','right');
% [~,p5,~,stat5] = ttest2(rich,nonzeros(peripheral),'Vartype','unequal','Tail','right');
% [~,p6,~,stat6] = ttest2(feedin,nonzeros(peripheral),'Vartype','unequal','Tail','right');
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
degreeDependence.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Both/degreeDependence.m
| 8,980 |
utf_8
|
624d87ab72d87977d1887cafedcc8488
|
%% [data, numberHere] = degreeDependence(C,G, measureTouse, doStrength, conType, chooseCategory, includingCategory, chooseRigth, useKinKout, doNonOverlap, categoryNoOverlap)
% ------------------------------------------------------------------------------
% function plots coexpression for links involving a specific category
% (motor/sensory/interneurons) as a function of degree (or strength).
% ------------------------------------------------------------------------------
% Inputs
% ------------------------------------------------------------------------------
% C (connectivity structure),
% G (gene data structure);
% coexpMeasure - choose coexpression measure as defined in G.Corr. default Pearson_noLR
% measureTouse - mean or median to summarise coexpression at each threshold
% conType - chemical (ch), all(all), electrical(el)
% chooseRight - 0/1; on top of the category chosen, it will filter only
% right side neurons of that category;
% chooseCategory = [] - set of numbers from C.C.neuronAnatomyNames (can be from 1 to 10)
% includingCat = 0/1/2/3
% (0 - exclude connections involving neurons in subcategory;
% 1 - include connections involving neurons in subcategory,
% 2 - include only connections within subcategory (subcategory neurons
% connecting to other subcategory neurons)
% 3 - exclude connections involving neurons within subcategory (e.g. include all connections except interneuron-interneuron connections)
% ------------------------------------------------------------------------------
% Outputs
% ------------------------------------------------------------------------------
% data - degree, coexpression and number fo links for each type of neurons;
% ------------------------------------------------------------------------------
% Aurina Arnatkeviciute, 2017-03-20
% ------------------------------------------------------------------------------
function [data, numberHere] = degreeDependence(C,G, coexpMeasure, measureTouse, doStrength, conType, chooseCategory, includingCategory, chooseRigth, useKinKout, doNonOverlap)
if nargin < 3
correlation = GiveMeCoexpression(G,[],true);
end
if nargin < 4
measureTouse = 'mean';
end
if nargin < 5
doStrength = false;
end
if nargin < 6
conType = 'all';
end
if nargin < 7
chooseCategory = [10 13 17]; %interneuron, motor, sensory;
end
if nargin < 8
includingCategory = 1;
end
if nargin < 9
chooseRigth = false;
end
if nargin < 10
useKinKout = false;
end
if nargin < 11
doNonOverlap = false;
end
Adj = GiveMeAdj(C,'zeroWeighted',conType);
correlation = GiveMeCoexpression(G,coexpMeasure,true);
if doStrength
[kin,kout,deg] = strengths_dir(Adj);
else
[kin,kout,deg] = degrees_dir(Adj);
end
if useKinKout == 1
deg = kout;
end
Adj = logical(Adj);
Adj=logical(Adj+Adj')+0;
nans = tril(nan(279,279)); % make nan matrix and use that to exclude the lower triangle.
Adj = Adj+nans;
coexp = correlation.*Adj;
coexp(coexp==0) = NaN;
data = cell(length(chooseCategory),2);
figure('color', 'w');
set(gcf,'Position',[1000,200,1000,500])
n=ones(1,279);
for k=1:length(chooseCategory)
l = chooseCategory(k);
subCat = C.RegionM(:,l)';
% if useOppositeCat == 1
% subCat = ~subCat;
% end
if doNonOverlap == 1
%subCat(subCat~=3)=0; - interneurons, but not in the head
%subCat(subCat~=1)=0; - head neurons, but not interneurons
subCat(subCat~=1)=0;
subCat = logical(subCat);
end
if chooseRigth == 1
isRight = extractfield(C.RegionStruct, 'Right');
subCat = subCat+isRight;
thr = 2;
else
thr = 1;
end
[uniqueDeg, expHere,numSubcat] = coexpressionDeg(subCat, coexp, includingCategory);
lineStyle = '-'; markerStyle = 'o';
data{k,1} = uniqueDeg;
data{k,2} = expHere;
data{k,3} = numSubcat;
uniqueDegrees = unique(horzcat(data{:,1}));
colorlist = GiveMeColors('InterneuronMotorSensoryMulti'); %('[1 .46 .22; .32 .28 .31; 0 .5 .5];%{'r', 'b', 'c', 'm', 'g', 'k', 'm'};%'color', CM(k,:),
sp2=subplot(2,5,6:8); plot(data{k,1}, data{k,2}, lineStyle, 'color',colorlist(k,:),'LineWidth',2.5); hold on;
plot(data{k,1}, data{k,2},markerStyle,'MarkerEdgeColor',colorlist(k,:),...
'MarkerFaceColor',brighten(colorlist(k,:),+0.5),'LineWidth',1,'MarkerSize',7);
legendInfo{k} = [C.neuronAnatomyNames{l}];box off;
end
pos=get(sp2,'Position');
set(sp2,'Position',[pos(1)*1, pos(2)*2.5, pos(3)*1, pos(4)*0.8]); % [left bottom width height]
%legend(legendInfo);
% if includingCategory == 1
% title('Connections involving category');
% elseif includingCategory == 0
% title('Connections not involving category');
% elseif includingCategory == 2
% title('Connections only between category');
% elseif includingCategory == 3
% title('Connections only between non category');
%end
if doStrength == 1
xlabel('strength>=s', 'FontSize', 12);
else
xlabel('Degree, k', 'FontSize', 12);
end
switch measureTouse
case 'mean'
ylabel('Gene coexpression', 'FontSize', 12);
case 'median'
ylabel('Gene coexpression', 'FontSize', 12);
end
uniqueDegrees = unique(horzcat(data{:,1}));
numberHere = zeros(length(uniqueDegrees), length(chooseCategory));
for p=1:length(uniqueDegrees)
for u=1:length(chooseCategory)
dcat = uniqueDegrees(p);
indHere= find(data{u,1}==dcat);
if isempty(indHere)
numberHere(p,u) = 0;
else
numberHere(p,u) = data{u,3}(indHere);
end
end
end
sp1=subplot(2,5,1:3); H = bar(uniqueDegrees,numberHere, 'stacked', 'EdgeColor', 'w'); xlim([1,max(uniqueDegrees)]); ylim([0,3500]);
set(gca,'Xtick', []);
pos=get(sp1,'Position');
set(sp1,'Position',[pos(1)*1, pos(2)*1, pos(3)*1, pos(4)*0.5]); % [left bottom width height]
%title('Number of links for each category');
if doStrength == 1
ylabel('Number of links', 'FontSize', 12);%xlabel('strength>=s');
else
ylabel('Number of links', 'FontSize', 12);%xlabel('degree>=k');
end
for v=1:length(chooseCategory)
set(H(v),'facecolor',colorlist(v,:));
end
box off; hold on;
%AX=legend(H, {'a','b','c','d','e','f'}, 'Location','Best','FontSize',8);
function [uniqueDeg, expHere, numSubcat] = coexpressionDeg(subCat, coexp,includingCategory)
if includingCategory==1
nc1 = sum(subCat); valsc1=linspace(1,nc1,nc1); c1rank = zeros(279,1); c1rank(subCat==1)=valsc1; valsc12 = linspace(nc1+1,279,279-nc1); c1rank(subCat==0)=valsc12;
[~, valInd] = sort(c1rank);
categoryDeg = deg(valInd);
category = coexp(valInd, valInd);
category((nc1+1):279, (nc1+1):279)=NaN;
% calcCatDeg = categoryDeg(1:nc1);
elseif includingCategory==0
nc1 = sum(~subCat); valsc1=linspace(1,nc1,nc1); c1rank = zeros(279,1); c1rank(subCat==0)=valsc1; valsc12 = linspace(nc1+1,279,279-nc1); c1rank(subCat==1)=valsc12;
[~, valInd] = sort(c1rank);
categoryDeg = deg(valInd);
category = coexp(valInd, valInd);
category((nc1+1):279, (nc1+1):279)=NaN;
% calcCatDeg = categoryDeg(1:nc1);
elseif includingCategory==2
category = coexp(subCat == thr,subCat == thr);
categoryDeg = deg(subCat==thr);
elseif includingCategory==3
subCat=~subCat;
category = coexp(subCat == thr,subCat == thr);
categoryDeg = deg(subCat==thr);
end
uniqueDeg = unique(categoryDeg);
expHere = zeros(length(uniqueDeg),1);
numSubcat = zeros(length(uniqueDeg),1);
for j=1:length(uniqueDeg)
degHere = uniqueDeg(j);
indDeg = find(categoryDeg>degHere);
%calcCatDeg = categoryDeg(
%numSubcat(j) = length(indDeg);
numLinks = category(indDeg,indDeg);
numLinks(isnan(numLinks))=0;
numSubcat(j) = sum(sum(logical(numLinks)));
switch measureTouse
case 'median'
expHere(j) = nanmedian(nanmedian(category(indDeg,indDeg)));
case 'mean'
expHere(j) = nanmean(nanmean(category(indDeg,indDeg)));
end
end
numSubcat(isnan(expHere))=NaN;
uniqueDeg(isnan(expHere))=NaN;
end
% plot non-hub/ hub interneurons
[p, stats, dataCell] = plotInterneuronsDegree(C,G);
hold on;
sp3 = subplot(2,5,4:5);
extraParams = struct('customSpot','');
JitteredParallelScatter(dataCell,0,1,false, extraParams);
xLabels = {'Hub interneurons', 'Non-hub interneurons'};
set(gca,'Xtick', [1 2], 'XTickLabel',xLabels, 'FontSize', 12);
set(gca,'Ytick', [0 0.2 0.4 0.6 0.8 1], 'YTickLabel',[0 0.2 0.4 0.6 0.8 1], 'FontSize', 12);
set(gca,'box','off');
ylabel('Coexpression','FontSize', 12);
pos=get(sp3,'Position');
set(sp3,'Position',[pos(1)*1.05, pos(2)*0.5, pos(3)*1, pos(4)*1.2]); % [left bottom width height]
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
RichClubPhiNorm_A.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Connectome/RichClubPhiNorm_A.m
| 5,364 |
utf_8
|
86916b0bffc1f3fd416b8b7be62d737e
|
function [PhiNorm,PhiTrue,PhiRand, rAdj] = RichClubPhiNorm_A(Adj,kmax,numIter,numRepeats,WhatTypeNetwork,whatNullModel, wei_freq)
% RichClubPhiNorm
%
% INPUTS:
% Adjacency matrix, Adj
% Compares to m randomly permuted version of the same matrix
% Does QE iterations, where E is the number of edges
% In the case of weighted networks, THIS WILL NOT preserve strength of each node
% (i.e., weight of its links) but will preserve the degree of each node.
%
% Rewire the network NumLinks*Q times, and repeat this m times.
%
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-06-16, updated for use in analyzing the mouse connectome.
% Ben Fulcher, 2014-04-28
% ------------------------------------------------------------------------------
% ------------------------------------------------------------------------------
% Check inputs, preliminaries
% ------------------------------------------------------------------------------
if nargin < 2 || isempty(kmax)
kmax = max(sum(Adj));
fprintf(1,'Setting maximum k to k_max = %u\n',kmax);
end
if nargin < 6 || isempty(whatNullModel)
switch WhatTypeNetwork
case 'bu'
whatNullModel = 'randmio_und';
case 'bd'
whatNullModel = 'randmio_dir';
case 'wu'
whatNullModel = 'Randomise_weights_keeping_topology';
case 'wus'
whatNullModel = 'Randomise_weights_keeping_topology';
otherwise
error('Appropriate default null model unavailable.');
end
end
NumNodes = length(Adj);
% ------------------------------------------------------------------------------
% Compute phi for the adjacency matrix
% ------------------------------------------------------------------------------
switch WhatTypeNetwork
case 'wd' % Weighted, directed network:
RichClubFun = @(x) rich_club_wd(x,kmax);
case 'wu' % Weighted, undirected network:
RichClubFun = @(x) rich_club_wu(x,kmax);
case 'wus' % Weighted, undirected network:
RichClubFun = @(x) rich_club_wu_strength(x,kmax);
case 'bu2h' % Weighted, undirected network:
RichClubFun = @(x) rich_club_bu(x,kmax);
case 'bu' % binary, undirected network:
RichClubFun = @(x) rich_club_bu(x,kmax);
case 'bd' % binary, directed network:
% "degree is taken to be the sum of incoming and outgoing connections"
RichClubFun = @(x) rich_club_bd(x,kmax);
otherwise
error('Unknown network type ''%s''',WhatTypeNetwork);
end
% ------------------------------------------------------------------------------
% Compute phi for the real network:
% ------------------------------------------------------------------------------
PhiTrue = RichClubFun(Adj);
% ------------------------------------------------------------------------------
% Compute for randomized versions of the network
% ------------------------------------------------------------------------------
PhiRand = zeros(numRepeats,kmax);
fprintf(1,['Computing %u link-permuted matrices, ' ...
'using %u iterations for each randomization\n'],numRepeats,numIter);
switch whatNullModel
case 'randmio_und'
f_rand_null = @randmio_und;
case 'randmio_dir'
f_rand_null = @randmio_dir;
case 'shuffleWeights' % topology fixed, strength preserved, weight distribution not preserved
f_rand_null = @f_shuffleWeights;
case 'Randomise_weights_keeping_topology' % topology kept, weights distributed randomly
f_rand_null = @Randomise_weights_keeping_topology;
case 'null_model_und_sign'
f_rand_null = @null_model_und_sign;
end
timer = tic;
parfor i = 1:numRepeats
fprintf(1,'[%u/%u] Rewiring each link %u times...',i,numRepeats,numIter);
if strcmp(whatNullModel, 'null_model_und_sign')
[Adj_rand, numRewirings] = f_rand_null(Adj, numIter, wei_freq); % Random graph with preserved in/out degree distribution
else
[Adj_rand, numRewirings] = f_rand_null(Adj, numIter); % Random graph with preserved in/out degree distribution
end
fprintf(1,' %u rewirings performed.\n',numRewirings);
PhiRand(i,:) = RichClubFun(Adj_rand);
% if i==1 || mod(i,numRepeats/10)==0
% fprintf(1,'Approx. %s remaining...\n',BF_thetime(toc(timer)/i*(numRepeats-i)));
% end
end
% ------------------------------------------------------------------------------
% Calculate normalized phi values for the resulting nomalization, PhiNorm
% ------------------------------------------------------------------------------
% Definition in vandenHeuvel:2011he is the following:
meanNotNaN = @(x)mean(x(~isnan(x) & ~isinf(x)));
PhiNorm = PhiTrue./arrayfun(@(x)meanNotNaN(PhiRand(:,x)),1:kmax);
% ------------------------------------------------------------------------------
% Extra functions:
function [rAdj,numRewirings] = f_shuffleWeights(Adj,numIter);
% Ben Fulcher, 2014-12-01
% Shuffles weights, keeping the topology fixed while preserving
% strenght of each node
% Get all elements of link data where a connection exists:
% allActualLinks = Adj(Adj~=0); % Shuffle them
[suffled]=random_weight_distribution(Adj);
allActualLinksDataShuffled = suffled;
% Put them back in the matrix
rAdj = zeros(size(Adj));
rAdj(Adj~=0) = allActualLinksDataShuffled;
% Not relevant to this method:
numRewirings = 0;
end
% ------------------------------------------------------------------------------
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
propLinkDegree.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Connectome/propLinkDegree.m
| 2,564 |
utf_8
|
863e43052e46e7a4057cdd7fa6f41489
|
%% propTypesDegree(C)
% ------------------------------------------------------------------------------
% Function plots the proportion of interneurons/motor/sensory/polymodal neurons as a function of degree.
%-------------------------------------------------------------------------------
% Inputs
% ------------------------------------------------------------------------------
% C (connectivity structure)
% ------------------------------------------------------------------------------
% Aurina Arnatkeviciute 2017-03-20
% ------------------------------------------------------------------------------
function [link, deg] = propLinkDegree(C, whatAdj,whatType)
if nargin<2
whatAdj = 'zeroBinary';
end
if nargin <3
whatType = 'all';
end
%types = [10 13 17 21];
Adj = GiveMeAdj(C,whatAdj,whatType);
% chemical network
%Adj = GiveMeAdj(C,'zeroBinary');
% Compute degree:
[~,~,deg] = degrees_dir(Adj);
kmax = max(deg);
kmin = min(deg);
degsort = (kmin: kmax);
% calculate proportion
%prop = zeros(length(types), length(degsort));
link = zeros(4,length(degsort));
for i = 1:length(degsort)
ind = (deg > degsort(i));
link(1,i) = sum(sum(Adj(ind, ind)))/sum(Adj(:));
link(2,i) = sum(sum(Adj(~ind, ind)))/sum(Adj(:));
link(3,i) = sum(sum(Adj(ind, ~ind)))/sum(Adj(:));
link(4,i) = sum(sum(Adj(~ind, ~ind)))/sum(Adj(:));
% for j=1:size(link,2)
% prop(j,i) = sum(link(:,j))/sum(link(:));
% end
end
end
% plot proportion
% f = figure('color','w');
% subplot(2,1,1)
% kRange = degsort;
% N = arrayfun(@(x)sum(deg==x),kRange);
% bar(kRange,N,'EdgeColor','k','FaceColor','k')
% xlim([min(deg),max(deg)]);
% ylabel('Frequency')
% subplot(2,1,2)
% % Give colors:
% colors = BF_getcmap('spectral',4,1);
% kRange = min(deg):max(deg);
% for i = 1:length(kRange)
% %ind = (deg >= degsort(i));
% %categoriesHere = C.RegionM(ind==1, types);
% proportions = link'; %countcats(categoriesHere)/length(categoriesHere);
% for j = 1:size(proportions,2)
% if proportions(i,j) > 0
% rectangle('Position',[kRange(i),sum(proportions(i,1:j-1)),1,proportions(i,j)], ...
% 'FaceColor',colors{j},'EdgeColor',colors{j})
% end
% end
% end
%Labels = C.neuronAnatomyNames(types);
% where = zeros(length(types),1);
% for w=1:length(types)
% if w==1
% where(w) = proportions(1,w)/2;
% else
% where(w) = sum(proportions(1,1:w-1))+proportions(1,w)/2;
% end
% end
% prop1 = proportions(1,:);
% for j = 1:length(prop1)
% text(kRange(1),where(j),Labels{j})
% end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
RichClubPhiNorm.m
|
.m
|
CElegansConnectomeGeneExpression-master/Analysis/Connectome/RichClubPhiNorm.m
| 9,767 |
utf_8
|
a22de308555e4efd49481ebf187f09f1
|
function [PhiNorm,PhiTrue,PhiRand] = RichClubPhiNorm(Adj,kmax,numIter,numRepeats,WhatTypeNetwork,whatNullModel)
% RichClubPhiNorm
%
% INPUTS:
% Adjacency matrix, Adj
% Compares to m randomly permuted version of the same matrix
% Does QE iterations, where E is the number of edges
% In the case of weighted networks, THIS WILL NOT preserve strength of each node
% (i.e., weight of its links) but will preserve the degree of each node.
%
% Rewire the network NumLinks*Q times, and repeat this m times.
%
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-06-16, updated for use in analyzing the mouse connectome.
% Ben Fulcher, 2014-04-28
% ------------------------------------------------------------------------------
% ------------------------------------------------------------------------------
% Check inputs, preliminaries
% ------------------------------------------------------------------------------
if nargin < 2 || isempty(kmax)
kmax = max(sum(Adj));
fprintf(1,'Setting maximum k to k_max = %u\n',kmax);
end
if nargin < 6 || isempty(whatNullModel)
switch WhatTypeNetwork
case 'bu'
whatNullModel = 'randmio_und';
case 'bd'
whatNullModel = 'randmio_dir';
otherwise
error('Appropriate default null model unavailable.');
end
end
NumNodes = length(Adj);
% ------------------------------------------------------------------------------
% Compute phi for the adjacency matrix
% ------------------------------------------------------------------------------
switch WhatTypeNetwork
case 'wd' % Weighted, directed network:
RichClubFun = @(x) rich_club_wd(x,kmax);
case 'wu' % Weighted, undirected network:
RichClubFun = @(x) rich_club_wu(x,kmax);
case 'bu' % binary, undirected network:
RichClubFun = @(x) rich_club_bu(x,kmax);
case 'bd' % binary, directed network:
% "degree is taken to be the sum of incoming and outgoing connections"
RichClubFun = @(x) rich_club_bd(x,kmax);
otherwise
error('Unknown network type ''%s''',WhatTypeNetwork);
end
% ------------------------------------------------------------------------------
% Compute phi for the real network:
% ------------------------------------------------------------------------------
PhiTrue = RichClubFun(Adj);
% ------------------------------------------------------------------------------
% Compute for randomized versions of the network
% ------------------------------------------------------------------------------
PhiRand = zeros(numRepeats,kmax);
fprintf(1,['Computing %u link-permuted matrices, ' ...
'using %u iterations for each randomization\n'],numRepeats,numIter);
switch whatNullModel
case 'randmio_und'
f_rand_null = @randmio_und;
case 'randmio_dir'
f_rand_null = @randmio_dir;
case 'shuffleWeights'
f_rand_null = @f_shuffleWeights;
end
timer = tic;
parfor i = 1:numRepeats
fprintf(1,'[%u/%u] Rewiring each link %u times...',i,numRepeats,numIter);
[Adj_rand,numRewirings] = f_rand_null(Adj,numIter); % Random graph with preserved in/out degree distribution
fprintf(1,' %u rewirings performed.\n',numRewirings);
PhiRand(i,:) = RichClubFun(Adj_rand);
if i==1 || mod(i,numRepeats/10)==0
fprintf(1,'Approx. %s remaining...\n',BF_thetime(toc(timer)/i*(numRepeats-i)));
end
end
% ------------------------------------------------------------------------------
% Calculate normalized phi values for the resulting nomalization, PhiNorm
% ------------------------------------------------------------------------------
% Definition in vandenHeuvel:2011he is the following:
meanNotNaN = @(x)mean(x(~isnan(x) & ~isinf(x)));
PhiNorm = PhiTrue./arrayfun(@(x)meanNotNaN(PhiRand(:,x)),1:kmax);
% ------------------------------------------------------------------------------
% Extra functions:
function [rAdj,numRewirings] = f_shuffleWeights(Adj,numIter);
% Ben Fulcher, 2014-12-01
% Shuffles weights, keeping the topology fixed
% 1. Find
% Get all elements of link data where a connection exists:
allActualLinks = Adj(Adj~=0);
% Shuffle them:
allActualLinksDataShuffled = allActualLinks(randperm(length(allActualLinks)));
% Put them back in the matrix
rAdj = logical(Adj)+0;
rAdj(Adj~=0) = allActualLinksDataShuffled;
% Not relevant to this method:
numRewirings = 0;
end
% ------------------------------------------------------------------------------
end
% % ------------------------------------------------------------------------------
% % Get normalized phi by comparing to randomized versions
% % (that preserve the degree distribution)
% % ------------------------------------------------------------------------------
% % Rewire numIter times
% % Do this m times
%
% % Much easier in the format NodeLinks = [Node_i,Node_j,weight];
% % AllLinks = Adj(logical(triu(ones(size(Adj)),+1)));
% % Set below-diagonal terms to zero, assuming a symmetric input matrix
% AllLinks = Adj;
% AllLinks(logical(tril(ones(size(Adj)),-1))) = 0;
% [Thei,Thej] = find(AllLinks>0);
% NumLinks = length(Thei);
% numIter = NumLinks*Q;
%
% NodeLinks = zeros(length(Thei),3);
% for i = 1:NumLinks
% NodeLinks(i,1) = Thei(i);
% NodeLinks(i,2) = Thej(i);
% NodeLinks(i,3) = Adj(Thei(i),Thej(i));
% end
%
% k_orig = (sum(Adj>0)); % Degree of each node
%
% fprintf(1,['Computing %u link-permuted matrices, ' ...
% 'using %u iterations for each randomization\n'],m,numIter);
% % (as per Julian J. McAuley et al. Appl. Phys. Lett. 91, 084103, 2007)
% % (the swapping method in Milo et al., arXiv:2004)
% PhiRand = zeros(m,kmax);
% for i = 1:m % m random matrices
% fprintf(1,'\n---------ITERATION%u---------\n',i);
% NodeLinks_ran = NodeLinks; % start the same, then progressively randomize
%
% DidSwap = zeros(numIter,1);
% IterTimer = tic; % time the iterations
% for j = 1:numIter % numIter link permutations
%
% if (mod(j,floor(numIter/10))==0)
% fprintf(1,'Approx %s remaining! We have made %u swaps so far...\n', ...
% BF_thetime(toc(IterTimer)/j*(numIter-j)),sum(DidSwap(1:j-1)))
% end
%
% % Pick two links at random: r1 and r2
% r1 = randi(NumLinks);
% r2 = randi(NumLinks);
% % % Make sure the second link is not same as the first link:
% % notr1 = setxor(1:NumLinks,r1);
% % r2 = notr1(r2);
%
% % Swapping will either have no effect, or produce a self-link
% if length(unique([NodeLinks_ran(r1,1:2),NodeLinks_ran(r2,1:2)])) < 4
% % fprintf(1,'(%u,%u) and (%u,%u) self-link\n', ...
% % NodeLinks_ran(r1,1),NodeLinks_ran(r1,2), ...
% % NodeLinks_ran(r2,1),NodeLinks_ran(r2,2));
% % fprintf(1,'S');
% continue
% end
%
% % Pick start (or end)-point to swap
% n1 = randi(2); % swap node (1) or (2) in first link
% n2 = randi(2); % with node (1) or (2) in the second link
%
% % Swap node n1 of link r1 with node n2 of link r2
% old1 = NodeLinks_ran(r1,1:2);
% old2 = NodeLinks_ran(r2,1:2);
% new1 = old1; new1(n1) = old2(n2); new1 = sort(new1);
% new2 = old2; new2(n2) = old1(n1); new2 = sort(new2);
%
% % Check that these new links don't already exist (else you create a double-link):
% if any(sum(bsxfun(@minus,NodeLinks_ran(:,1:2),new1)==0,2)==2)
% % fprintf(1,'Can''t swap (%u,%u) -> (%u,%u) because it already exists...\n', ...
% % old1(1),old1(2),new1(1),new1(2));
% continue
% elseif any(sum(bsxfun(@minus,NodeLinks_ran(:,1:2),new2)==0,2)==2)
% % fprintf(1,'Can''t swap (%u,%u) -> (%u,%u) because it already exists...\n', ...
% % old2(1),old2(2),new2(1),new2(2));
% % fprintf(1,'E');
% continue
% end
%
% % So we haven't continued yet and can swap!
% % fprintf(1,'Swapped (%u,%u) -> (%u,%u) and (%u,%u) -> (%u,%u)\n', ...
% % old1(1),old1(2),new1(1),new1(2), ...
% % old2(1),old2(2),new2(1),new2(2));
% NodeLinks_ran(r1,1:2) = new1;
% NodeLinks_ran(r2,1:2) = new2;
% DidSwap(j) = 1;
%
% % Adj_rand = zeros(NumNodes);
% % for k = 1:NumLinks
% % Adj_rand(NodeLinks_ran(k,1),NodeLinks_ran(k,2)) = NodeLinks_ran(k,3);
% % end
% % Adj_rand = Adj_rand + Adj_rand';
% % k_rand = (sum(Adj_rand>0));
% % if sum(k_rand-k_orig)~=0
% % fprintf(1,'WOWWOWWOW\n');
% % keyboard
% % end
%
% end
%
% fprintf(1,'Made a total of %u (/%u) link permutations...\n',sum(DidSwap),numIter);
%
% % Convert back to an adjacency matrix to feed into the rich club calculation:
% Adj_rand = zeros(NumNodes);
% for j = 1:NumLinks
% Adj_rand(NodeLinks_ran(j,1),NodeLinks_ran(j,2)) = NodeLinks_ran(j,3);
% end
% Adj_rand = Adj_rand + Adj_rand';
% k_rand = (sum(Adj_rand>0));
% if sum(k_rand-k_orig)~=0
% fprintf(1,'Sorry to break this to you, but degree distributions actually don''t match... :-/\n');
% keyboard
% else
% fprintf(1,'Degree distributions match!\n');
% end
%
% % Visualize the randomized matrix
% % if i==1
% % figure('color','w'); box('on');
% % subplot(2,1,1); pcolor(Adj); shading('flat'); axis square
% % subplot(2,1,2); pcolor(Adj_rand); shading('flat'); axis square
% % end
%
% PhiRand(i,:) = rich_club_wu(Adj_rand,kmax);
% end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
NeuronRegionFinder.m
|
.m
|
CElegansConnectomeGeneExpression-master/DataProcessing/NeuronRegionFinder.m
| 4,349 |
utf_8
|
c7115a0bce8edb2694ed4d71204db3cf
|
function C = NeuronRegionFinder(C,beVocal)
%-------------------------------------------------------------------------------
% 1. Reads in the hierarchy file (from RetrieveHierarchy.py)
% 2. Creates a translation table, and assigns all neurons to specific regions
% 3. Outputs results to matlab file: CElegans_Connectivity_Data.mat
%-------------------------------------------------------------------------------
if nargin < 1
load('CElegansConnectivityData.mat','C');
end
if nargin < 2
beVocal = true;
end
% Extract neuron ID
neuronID = cell2mat({C.RegionStruct.id});
numNeurons = length(neuronID);
%-------------------------------------------------------------------------------
%% Create translation table for parents -> children
%-------------------------------------------------------------------------------
% Read in and parse data from hierarchy.csv
[parentName,childName,parentID,childID] = ReadInHierarchy();
% Find anatomy terms annotated directly under the Neuron anatomy term
index = (parentID==3679); % WBbt:0003679
neuronAnatomyIDs = childID(index);
neuronAnatomyNames = childName(index);
numNeuronAnatomyIDs = length(neuronAnatomyIDs);
fprintf(1,'%u direct neuron anatomy terms in hierarchy\n',numNeuronAnatomyIDs);
% Find subsets of anatomy terms to assign labels to each neuron
RegionM = zeros(numNeurons,numNeuronAnatomyIDs);
% Cycle through neurons:
for m = 1:numNeurons
if beVocal
fprintf(1,'Neuron %u/%u\n',m,numNeurons);
end
% Keep going up the hierarchy, matching, until at the top
RegionM(m,:) = PropagateUp(neuronID(m));
end
% add information about neuron type according to wormatlas for neurons that
% are not assigned to be neither motor/interneuron/sensory neuron. see: http://www.wormatlas.org/neurons/Individual%20Neurons/PLNframeset.html
% ALA, ALNL, ALNR, AUAL, AUAR - interneurons;
% ALA, CEPDL, CEPDR, CEPVL, CEPVR, PLNL PLNR - sensory neurons
RegionM([23 26 27 52 53],10) = 1;
RegionM([23 83 84 85 86 148 149],17) = 1;
isInter = RegionM(:,strcmp(neuronAnatomyNames,'interneuron'));
isSensory = RegionM(:,strcmp(neuronAnatomyNames,'sensory neuron'));
isMotor = RegionM(:,strcmp(neuronAnatomyNames,'motor neuron'));
multi = isInter+isSensory+isMotor; % check if a neuron belongs to more then one category
RegionM(:,21) = 0; % create empty variable
RegionM(multi>1,21) = 1; % populate with ones if neuron is assigned to more than 1 category.
neuronAnatomyNames{21} = 'multimodal';
% edit information about head-tail assignment according to wormatlas.
% ALA (23), AVFL(62), AVFR(63), AVG(64), RIFL(173), RIFR(174), RIGL(175),
% RIGR 176), SABD(206), SABVL(207), SABVR(208), SMDVL(225) - in wormatlas
% locations of these neurons are labeled as head.
% Hierarchy file assignes neither head, nor tail.
% manualy assign those neurons to head.
RegionM([23 62 63 64 173 174 175 176 206 207 208 225],9)=1;
C.RegionM = RegionM;
C.neuronAnatomyNames = neuronAnatomyNames;
C.neuronAnatomyIDs = neuronAnatomyIDs;
%-------------------------------------------------------------------------------
% Save data to file: CElegans_Connectivity_Data.mat
% fileName = 'CElegansConnectivityData.mat';
% save(fileName,'C','-append');
% fprintf(1,'Saved neuronAnatomy term annotation results to %s\n',fileName);
%-------------------------------------------------------------------------------
function annotations = PropagateUp(idStart)
% start at an ID and propagate up the hierarchy, annotating matches on the way
idHere = idStart;
annotations = zeros(1,numNeuronAnatomyIDs);
% find matches to current ID
if any(idHere==neuronAnatomyIDs)
annotations(idHere==neuronAnatomyIDs) = 1;
if beVocal
fprintf(1,'Annotated for %u\n',idStart);
end
else
% Go up hierarchy to parents
idUp = parentID(childID==idHere);
numParents = length(idUp);
if numParents == 0
if beVocal
fprintf(1,'Got to top for %u\n',idStart);
end
else
if beVocal
fprintf(1,'Going up for %u parents\n',numParents);
end
for j = 1:numParents
% go up hierarchy for each parent:
annotate_j = PropagateUp(idUp(j));
annotations(annotate_j==1) = 1;
end
end
end
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
GiveMeQuantileMeans.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/GiveMeQuantileMeans.m
| 950 |
utf_8
|
5226c27e131644e8b97c99433b8a53c4
|
% Outputs the xRange used for the quantiles
% Outputs the means of the yData provided in each quantiled-bin
% Outputs the indices of the data used in each quantile (as a cell)
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-11-05
function [xRange,yMeans,affectedInd] = GiveMeQuantileMeans(xData,yData,numThresholds)
% Set up quantiles for computing distances:
xQuantiles = linspace(0,1,numThresholds + 1);
% xRange = zeros(numThresholds+1,1);
for i = 1:numThresholds+1
xRange(i) = quantile(xData,xQuantiles(i));
end
xRange(1) = xRange(1) - eps;
% affectedInd contains the indices for links in the given distance range (by quantile)
affectedInd = cell(numThresholds,1);
yMeans = zeros(numThresholds,1);
for i = 1:numThresholds
affectedInd{i} = (xData > xRange(i) & xData <= xRange(i+1));
if ~isempty(yData)
yMeans(i) = nanmean(yData(affectedInd{i}));
end
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
BF_thetime.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/BF_thetime.m
| 2,985 |
utf_8
|
f3ce0b3b40c5a21901c4ce987dc0e7cc
|
% ------------------------------------------------------------------------------
% BF_thetime
% ------------------------------------------------------------------------------
%
% Converts the input, tsec, a duration of time in seconds, into an appropriate
% string for output (i.e., converts to minutes or hours or days as appropriate)
% output is something like '25.5 minutes' or '3.2 days' -- always displays to
% one decimal place.
%
%---INPUTS:
% tsec, the duration in seconds
% FormatLong, (i) 0: display short units (like 's' instead of 'seconds')
% [default]
% (ii) 1: display long units (like 'seconds' instead of 's')
%
%---OUTPUT:
% TimeString, an interpretable text version of the input time.
%
% This code is useful for displaying user feedback on tic/toc statements.
%
%---HISTORY:
% Ben Fulcher, 2009
%
% ------------------------------------------------------------------------------
% Copyright (C) 2013, Ben D. Fulcher <[email protected]>,
% <http://www.benfulcher.com>
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------
function TimeString = BF_thetime(tsec,FormatLong)
if nargin < 2 || isempty(FormatLong)
FormatLong = 0; % Set to 1 to use a longer format for the unit
end
if tsec < 1E-3
if FormatLong
TimeString = '< 1 milliseconds';
else
TimeString = '< 1ms';
end
elseif tsec < 1 % less than a second, display in integer number of milliseconds
if FormatLong
TimeString = sprintf('%.0f milliseconds',tsec*1000);
else
TimeString = sprintf('%.0fms',tsec*1000);
end
elseif tsec <= 60 % less than a minute, display in seconds
if FormatLong
TimeString = sprintf('%.1f seconds',tsec);
else
TimeString = sprintf('%.1fs',tsec);
end
elseif tsec <= 60*60 % less than an hour, display in minutes
if FormatLong
TimeString = sprintf('%.1f minutes',tsec/60);
else
TimeString = sprintf('%.1fmin',tsec/60);
end
elseif tsec <= 60*24*60 % less than a day, display in hours
if FormatLong
TimeString = sprintf('%.1f hours',tsec/60/60);
else
TimeString = sprintf('%.1fh',tsec/60/60);
end
% elseif tsec<=60*24*7*60 % less than a week, display in days
else % display in days
TimeString = sprintf('%.1f days',tsec/60/60/24);
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
communicability.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/communicability.m
| 1,229 |
utf_8
|
54866b44e768f75fee441f69e6c20f5d
|
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-09-18
% ------------------------------------------------------------------------------
% Quick implementation of communicability, a measure introduced by Estrada and
% Hatano (2008).
%
%---INPUTS:
% Adj, the adjacency matrix
function G = communicability(Adj)
% Check that diagonal is zero
if ~all(diag(Adj)==0)
fprintf(1,'Setting diagonal to zero.\n');
Adj(logical(eye(size(Adj)))) = 0;
end
if islogical(Adj)
Adj = double(Adj);
end
% ------------------------------------------------------------------------------
% Compute the communicability measure as the exponential of the adjacency matrix.
% ------------------------------------------------------------------------------
% This weights higher order paths between two nodes lower, decreasing as 1/x!
G = expm(Adj);
% Set diagonal to zero:
% G(diag(G)) = 0;
% ------------------------------------------------------------------------------
% Compute mean communicability, meanG:
% ------------------------------------------------------------------------------
% (keeping diagonal terms in the mix when computing the average):
% meanG = mean(G(logical(Adj)));
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
ClusterDown.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/ClusterDown.m
| 4,972 |
utf_8
|
47d0d299d41fca3513d3959292e96e34
|
% Originally TSQ_localcorrm, used in fetal heart rate analysis work.
% Takes in a distance matrix, and clusters it down to a reduced set
% Clusters down a set of operations based on their behavior
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-06-25
% Ben Fulcher, 2011-03-17
% ------------------------------------------------------------------------------
function [DistMat_cl,Cluster_Groupi,ord] = ClusterDown(DistMat,numClusters,opts)
if nargin < 2 || isempty(numClusters)
numClusters = 5; % removes very highly-correlated operations
end
% Additional parameters stored in the opts structure:
if nargin < 3
opts = [];
end
if isfield(opts,'WhatDistance')
% Input is a distance matrix based on correlation coefficient
WhatDistance = opts.WhatDistance;
else
WhatDistance = 'general';
end
if isfield(opts,'errth')
errth = opts.errth;
else
errth = 30; % set error threshold instead of just top number
end
if isfield(opts,'teststat') % necessary to do the thresholding
teststat = opts.teststat;
end
if isfield(opts,'miorcorr')
miorcorr = opts.miorcorr;
else
miorcorr = 'corr'; % 'mi', 'corr'
end
if isfield(opts,'ClusterMeth')
ClusterMeth = opts.ClusterMeth;
else
ClusterMeth = 'linkage'; % 'linkage', 'kmedoids'
end
if isfield(opts,'LinkageMethod')
LinkageMethod = opts.LinkageMethod;
else
LinkageMethod = 'average';
end
if isfield(opts,'plotbig')
plotbig = opts.plotbig;
else
plotbig = 0;
end
% ------------------------------------------------------------------------------
% Cluster down to a reduced number of groups (some very highly-correlated operations):
% ------------------------------------------------------------------------------
figure('color','w');
% Do the linkage clustering:
fprintf(1,'Computing linkage information for %ux%u gene expression data...',length(DistMat),length(DistMat));
links = linkage(DistMat,LinkageMethod);
fprintf(1,' Done.\n');
% Get the dendrogram reordering:
subplot(5,1,1)
[h_dend,~,ord] = dendrogram(links,0);
% Reorder the distance matrix by dendrogram ordering: [could add optimalleaforder]
DistMat_cl = DistMat(ord,ord);
% Make the dendrogram look aight
axis_pos = get(gca,'Position');
axis_pos(1) = 0.26;
axis_pos(3) = 0.42;
set(gca,'Position',axis_pos)
set(h_dend,'color','k','LineWidth',1)
set(gca,'XTickLabel',{})
% Compute clustering into groups for many different cluster numbers:
numClusterings = length(numClusters);
Cluster_Groupi = cell(numClusterings,1);
Cluster_Groupi_cl = cell(numClusterings,1);
ClusterCenters_cl = cell(numClusterings,1);
ClusterCenters = cell(numClusterings,1);
for i = 1:numClusterings
fprintf(1,'Distance-based clustering with %u clusters\n',numClusters(i))
% Cluster the dendrogram:
T = cluster(links,'maxclust',numClusters(i));
numClusters(i) = max(T);
% Reorder members of each cluster by distance to other members of the cluster:
Cluster_Groupi{i} = cell(numClusters(i),1);
for j = 1:numClusters(i)
Cluster_Groupi{i}{j} = find(T==j);
if length(T==j) > 1
% Sort by increasing sum of distances to other members of the cluster
[~,ix] = sort(sum(DistMat(Cluster_Groupi{i}{j},Cluster_Groupi{i}{j})),'ascend');
Cluster_Groupi{i}{j} = Cluster_Groupi{i}{j}(ix);
end
end
% Select the closest to cluster centre in each group
try
ClusterCenters{i} = cellfun(@(x)x(1),Cluster_Groupi{i});
Cluster_Groupi_cl{i} = cellfun(@(x) arrayfun(@(y)find(ord==y),x),Cluster_Groupi{i},'UniformOutput',0);
ClusterCenters_cl{i} = arrayfun(@(y)find(ord==y),ClusterCenters{i});
catch
keyboard
end
end
% ------------------------------------------------------------------------------
% Now plot it:
% ------------------------------------------------------------------------------
% Pick a given clustering and plot it
cLevel = min(1,numClusterings); % plot the first clustering
nlook = length(DistMat_cl);
% Plot as a similarity matrix:
subplot(5,1,2:5)
switch WhatDistance
case 'corr'
% Input is a absolute correlation matrix:
PlotCorrMat(1-DistMat_cl,1);
case 'general'
% Input is a general distance matrix:
PlotCorrMat(DistMat_cl,0);
end
% Add rectangles to indicate highly correlated clusters of statistics:
RectangleColors = BF_getcmap('accent',5,1);
for i = 1:numClusters
% Cluster borders:
rectangle('Position',[min(Cluster_Groupi_cl{cLevel}{i})-0.5,min(Cluster_Groupi_cl{cLevel}{i})-0.5, ...
length(Cluster_Groupi_cl{cLevel}{i}),length(Cluster_Groupi_cl{cLevel}{i})], ...
'EdgeColor',RectangleColors{1},'LineWidth',3);
% Cluster centers:
rectangle('Position',[ClusterCenters_cl{cLevel}(i)-0.5,ClusterCenters_cl{cLevel}(i)-0.5,1,1], ...
'EdgeColor',RectangleColors{5},'LineWidth',3);
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
RemoveNaN_DistMat.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/RemoveNaN_DistMat.m
| 808 |
utf_8
|
9e6741adf3e66bc6c3077a2fd7e31255
|
% Removes NaN entries from an input distance matrix, R
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-06-25
% ------------------------------------------------------------------------------
function [R, keepers] = RemoveNaN_DistMat(R)
keepers = logical(ones(length(R),1));
if any(isnan(R(:)))
AreNaN = 1;
while AreNaN
NumNaNs = sum(isnan(R(keepers,keepers)));
[~,irem] = max(NumNaNs); % the index (of keepers==1) that has the most NaNs
fkeep = find(keepers);
keepers(fkeep(irem)) = 0; % remove this index from the full list, keepers
R_keep_tmp = R(keepers,keepers);
AreNaN = any(isnan(R_keep_tmp(:))); % are there still more NaNs after removing this?
end
R = R(keepers,keepers);
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
BF_NaNCov.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/BF_NaNCov.m
| 2,271 |
utf_8
|
0a261b6d7bf567015ac1fc6a9d689663
|
% Covariance including NaNs for an input matrix, X
% Not exact, because removes full mean across all values, rather than across
% overlapping range, but should a reasonable approximation when number of NaNs
% is small.
% Output can be either the covariance matrix, or matrix of correlation
% coefficients, depending on the second input.
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-06-26
% ------------------------------------------------------------------------------
function C = NaNCov(X,MakeCoeff,MakeDist)
if nargin < 2
MakeCoeff = 1; % by default, convert to correlation coefficients
end
if nargin < 3
MakeDist = 0; % by default, don't convert to distances
end
% Number of rows and columns (should be the same):
[NRow,NCol] = size(X);
if any(isnan(X(:)))
% Indicate non-NaN values:
GoodValues = single(~isnan(X));
% Compute column means, excluding NaNs:
% Problem is with X(~isnan) -> 0
meanNotNan = @(x) mean(x(~isnan(x)));
ColMeans = arrayfun(@(x)meanNotNan(X(:,x)),1:NCol);
% Remove mean from each column, to make centered version:
Xc = bsxfun(@minus,X,ColMeans);
% X0 copies Xc but puts zeros over NaNs:
X0 = Xc;
X0(~GoodValues) = 0; % NaN -> 0
% Count good points (overlapping non-NaN values)
GoodBoth = GoodValues' * GoodValues;
% This is our approximation to the covariance matrix:
C = (X0' * X0) ./ (GoodBoth - 1);
% Convert to a correlation coefficient:
if MakeCoeff
% Normalize by sample standard deviations:
stdNotNan = @(x) std(x(~isnan(x)));
ColStds = arrayfun(@(x)stdNotNan(X(:,x)),1:NCol);
S = ColStds'*ColStds;
C = C./S;
end
else
% no NaNs, use the matlab cov function:
C = cov(X);
if MakeCoeff
% Normalize by sample standard deviations:
ColStds = arrayfun(@(x)std(X(:,x)),1:NCol);
S = ColStds'*ColStds;
C = C./S;
end
end
% ------------------------------------------------------------------------------
% Convert to distances
% ------------------------------------------------------------------------------
if MakeDist && MakeCoeff
C(logical(eye(size(C)))) = 1;
C = 1-C;
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
BF_NormalizeMatrix.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/BF_NormalizeMatrix.m
| 10,527 |
utf_8
|
cbe478d5295aa270b1b6953658b08fdc
|
% ------------------------------------------------------------------------------
% BF_NormalizeMatrix
% ------------------------------------------------------------------------------
%
% Normalizes all columns of an input matrix.
%
%---INPUTS:
% F, the input matrix
% normopt, the normalization method to use (see body of the code for options)
% itrain, learn the normalization parameters just on these indices, then apply
% it on the full dataset (required for training/testing procedures where
% the testing data has to remain unseen).
%
%---OUTPUT:
% F, the normalized matrix
%
% Note that NaNs are ignored -- only real data is used for the normalization
% (assume NaNs are a minority of the data).
%
%---HISTORY:
% Ben Fulcher 28/1/2011 -- Added this NaN capability
% Ben Fulcher 12/9/2011 -- Added itrain input: obtain the transformation
% on this subset, apply it to all the data.
% Ben Fulcher, 2014-06-26 -- Added a mixed sigmoid approach
%
% ------------------------------------------------------------------------------
% Copyright (C) 2013, Ben D. Fulcher <[email protected]>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite:
% B. D. Fulcher, M. A. Little, N. S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2010). DOI: 10.1098/rsif.2013.0048
%
% This function is free software: you can redistribute it and/or modify it under
% the terms of the GNU General Public License as published by the Free Software
% Foundation, either version 3 of the License, or (at your option) any later
% version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
% details.
%
% You should have received a copy of the GNU General Public License along with
% this program. If not, see <http://www.gnu.org/licenses/>.
% ------------------------------------------------------------------------------
function F = BF_NormalizeMatrix(F,normopt,itrain)
% ------------------------------------------------------------------------------
%% Check Inputs
% ------------------------------------------------------------------------------
if nargin < 2 || isempty(normopt)
fprintf(1,'We''re normalizing using sigmoid transform by default\n')
normopt = 'sigmoid';
end
if nargin < 3
itrain = [];
end
N2 = size(F,2);
if isempty(itrain)
FT = F; % train the transformation on the full dataset
else
FT = F(itrain,:); % train the transformation on the specified subset
if ~strcmp(normopt,'scaledSQzscore')
error('TRAINING SPECIFIER ONLY WORKS FOR ''scaledSQzscore''...');
end
end
% ------------------------------------------------------------------------------
% Normalize according to the specified normalizing transformation
% ------------------------------------------------------------------------------
switch normopt
case 'relmean'
% Normalizes each column to a proportion of the mean of that column
F = bsxfun(@rdivide,F,nanmean(F));
case {'maxmin','minmax'}
% Linear rescaling to the unit interval
for i = 1:N2 % cycle through the operations
rr = ~isnan(F(:,i));
kk = F(rr,i);
if (max(kk)==min(kk)) % Rescaling will blow it up
F(rr,i) = NaN;
else
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
case 'MixedSigmoid'
% Ben Fulcher, 2014-06-26
% Runs a normal sigmoid if iqr=0; a scaled sigmoid otherwise
% Computes statistics on non-nans
% Rescale to unit interval:
UnityRescale = @(x) (x-min(x(~isnan(x))))/(max(x(~isnan(x)))-min(x(~isnan(x))));
% Outlier-adjusted sigmoid:
SQ_Sig = @(x) UnityRescale(1./(1 + exp(-(x-median(x(~isnan(x))))/(iqr(x(~isnan(x))/1.35)))));
SQ_Sig_noiqr = @(x) UnityRescale(1./(1 + exp(-(x-mean(x(~isnan(x))))/std(x(~isnan(x))))));
F_norm = zeros(size(F));
for i = 1:N2 % cycle through columns
if max(F(:,i))==min(F(:,i))
% A constant column is set to 0:
F_norm(:,i) = 0;
elseif all(isnan(F(:,i)))
% Everything a NaN, kept at NaN:
F_norm(:,i) = NaN;
elseif iqr(F(~isnan(F(:,i)),i))==0
% iqr of data is zero: perform a normal sigmoidal transformation:
F_norm(:,i) = SQ_Sig_noiqr(F(:,i));
else
% Perform an outlier-robust version of the sigmoid:
F_norm(:,i) = SQ_Sig(F(:,i));
end
end
F = F_norm; % set F_norm to F to output
case 'scaledSQzscore'
% A scaled sigmoided quantile zscore
% Problem is that if iqr=0, we're kind of screwed
for i = 1:N2
rr = ~isnan(F(:,i));
rt = ~isnan(FT(:,i));
FF = FT(rt,i); % good values in the training portion
if iqr(FF)==0
F(:,i) = NaN;
else
% Sigmoid transformation (gets median and iqr only
% from training data FT):
F1 = (F(rr,i)-median(FF))/(iqr(FF)/1.35);
kk = 1./(1+exp(-F1));
% Rescale to unit interval:
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
case 'scaledsigmoid'
% A standard sigmoid transform, then a rescaling to the unit interval
for i = 1:N2 % cycle through the metrics
rr = ~isnan(F(:,i));
FF = F(rr,i);
kk = 1./(1+exp(-zscore(FF)));
if (max(kk)==min(kk)) % rescaling will blow up
F(rr,i) = NaN;
else
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
case 'scaledsigmoid5q'
% First caps at 5th and 95th quantile, then does scaled sigmoid
for i = 1:N2 % cycle through the metrics
rr = ~isnan(F(:,i));
FF = F(rr,i);
qs = quantile(FF,[0.05,0.95]);
qr = (FF>=qs(1) & FF<=qs(2)); % quantile range
% calculate mean and std based on quantile range only
meanF = mean(FF(qr));
stdF = std(FF(qr));
if stdF==0
F(rr,i) = NaN; % avoid +/- Infs
else
% kk = 1./(1+exp(-zscore(FF)));
kk = 1./(1+exp(-(FF-meanF)/stdF));
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
case 'sigmoid'
for i = 1:N2 % cycle through the metrics
rr = ~isnan(F(:,i));
FF = F(rr,i);
% F(:,i) = 1./(1+exp(-pi*zscore(F(:,i))/sqrt(3)));
F(rr,i) = 1./(1+exp(-zscore(FF)));
end
% case 'maxmin'
% for i = 1:N2 % cycle through the metrics
% rr = ~isnan(F(:,i));
% FF = F(rr,i);
% if range(FF)==0
% F(rr,i) = NaN;
% else
% F(rr,i) = (FF-min(FF))/(max(FF)-min(FF));
% end
% end
case 'zscore'
% F = zscore(F);
for i = 1:N2
rr = ~isnan(F(:,i));
F(rr,i) = zscore(F(rr,i));
end
case 'Qzscore'
% quantile zscore
% invented by me.
for i = 1:N2
rr = ~isnan(F(:,i));
FF = F(rr,i);
if iqr(FF)==0 % could get +/- Infs otherwise
F(rr,i) = NaN;
else
F(rr,i) = (FF-median(FF))/(iqr(FF)/1.35);
end
end
case 'SQzscore'
% sigmoided quantile zscore
for i = 1:N2
rr = ~isnan(F(:,i));
FF = F(rr,i);
if iqr(FF)==0 % could get +/- Infs otherwise
F(rr,i) = NaN;
else
F1 = (FF-median(FF))/(iqr(FF)/1.35);
F(rr,i) = 1./(1+exp(-F1));
end
end
case 'scaled2ways'
for i = 1:N2
rr = ~isnan(F(:,i));
FF = F(rr,i);
if iqr(FF)==0
% then there's definitely no outlier problem: can safely do a
% sigmoid
kk = 1./(1+exp(-zscore(FF)));
if (max(kk)==min(kk)) % rescaling will blow up
F(rr,i) = NaN;
else
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
else
% wide distribution -- do a transformation that is not so
% sensitive to outliers
F1 = (FF-median(FF))/(iqr(FF)/1.35);
kk = 1./(1+exp(-F1));
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
case 'LDscaled'
% (i) maxmin
% linear rescaling to the unit interval
for i = 1:N2 % cycle through the metrics
rr = ~isnan(F(:,i));
kk = F(rr,i);
if (max(kk)==min(kk)) % rescaling will blow up
F(rr,i) = 0; % constant column
else
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
% (ii) outliersigmoid or sigmoid or nothing
for i = 1:N2
rr = ~isnan(F(:,i));
FF = F(rr,i);
if iqr(FF)==0
if std(FF)==0
F(rr,i) = 0;
else
% then there's definitely no outlier problem: can safely do a
% normal sigmoid
kk = 1./(1+exp(-zscore(FF)));
if (max(kk)==min(kk)) % rescaling will blow up
F(rr,i) = NaN;
else
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
else
% wide distribution -- do a transformation that is not so
% sensitive to outliers
F1 = (FF-median(FF))/(iqr(FF)/1.35);
kk = 1./(1+exp(-F1));
F(rr,i) = (kk-min(kk))/(max(kk)-min(kk));
end
end
otherwise
error('Invalid normalization method ''%s''', normopt)
end
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
PlotCorrMat.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/PlotCorrMat.m
| 1,444 |
utf_8
|
9aba8801d74815c2322704078cf9aad7
|
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-06-24
% ------------------------------------------------------------------------------
function PlotCorrMat(D_corr,Minus1To1)
if nargin < 2 || isempty(Minus1To1)
Minus1To1 = 1; % assume range from -1 to 1
end
% Make a matrix
if any(size(D_corr)==1)
D_corr = squareform(D_corr);
end
imagesc(D_corr)
axis square
% Set color limits and colormap
if Minus1To1
caxis([-1,1])
colormap([flipud(BF_getcmap('blues',9,0));BF_getcmap('reds',9,0)])
else % assume [0,1] (a normalized distance metric)
caxis([0,1])
colormap(BF_getcmap('reds',9,0))
end
% ------------------------------------------------------------------------------
% Superimpose green/yellow rectangles over NaN values
% ------------------------------------------------------------------------------
if any(isnan(D_corr(:)))
Green = BF_getcmap('greens',3,1);
Red = BF_getcmap('reds',3,1);
[theNaNs_i,theNaNs_j] = find(isnan(D_corr));
fprintf(1,['Superimposing green/red rectangles over all %u NaNs in ' ...
'the data matrix\n'],length(theNaNs_i));
for i = 1:length(theNaNs_i)
rectangle('Position',[theNaNs_j(i)-0.5,theNaNs_i(i)-0.5,1,1],'FaceColor',Green{end}, ...
'EdgeColor',Red{end})
end
end
% Add a colorbar
colorbar
% Remove ticks:
set(gca,'TickLength',[0,0])
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
BF_pdist.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/BF_pdist.m
| 7,563 |
utf_8
|
a9994650d52efdec2c584a240d2e4a04
|
% ------------------------------------------------------------------------------
% BF_pdist
% ------------------------------------------------------------------------------
%
% Same as pdist but then goes through and fills in NaNs with indiviually
% calculated values using an overlapping range of good values.
%
% HISTORY:
% Ben Fulcher, 2014-06-26 -- added support for NaNCorr, which should be a much
% faster approximate implementation for large matrices.
% ------------------------------------------------------------------------------
% Copyright (C) 2013, Ben D. Fulcher <[email protected]>,
% <http://www.benfulcher.com>
%
% If you use this code for your research, please cite:
% B. D. Fulcher, M. A. Little, N. S. Jones, "Highly comparative time-series
% analysis: the empirical structure of time series and their methods",
% J. Roy. Soc. Interface 10(83) 20130048 (2010). DOI: 10.1098/rsif.2013.0048
%
% This work is licensed under the Creative Commons
% Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a copy of
% this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ or send
% a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View,
% California, 94041, USA.
% ------------------------------------------------------------------------------
function R = BF_pdist(F,distMetric,toVector,opts,beSilent,minPropGood)
% ------------------------------------------------------------------------------
% Check Inputs:
% ------------------------------------------------------------------------------
if nargin < 2 || isempty(distMetric)
distMetric = 'euclidean';
fprintf(1,'Using the Euclidean distance metric\n')
end
if nargin < 3 || isempty(toVector)
toVector = 0;
end
if nargin < 4
opts = [];
end
if nargin < 5
beSilent = 0;
end
if nargin < 6
% By default, don't require a minimum proportion of good values to be
% present to compute a pairwise distance
minPropGood = 0;
end
[n1, n2] = size(F); % We're computing for rows (operations are rows)
% ------------------------------------------------------------------------------
% Define the distance function
% ------------------------------------------------------------------------------
switch distMetric
case {'Euclidean','euclidean'}
dij = @(v1,v2) sqrt(sum((v1-v2).^2))/length(v1)*n2; % if less entries, don't bias
case {'corr','correlation','abscorr','Pearson'}
dij = @(v1,v2) subdc(v1,v2,'Pearson');
case 'Spearman'
dij = @(v1,v2) subdc(v1,v2,'Spearman');
end
% ------------------------------------------------------------------------------
% Compute pairwise distances
% ------------------------------------------------------------------------------
switch distMetric
case 'mi'
% Mutual information distances: can't make use of the inbuilt pdist function
if ~isempty(opts)
nbins = opts; % for MI, extra argument specifies nbins
else
nbins = 10;
end
if ~beSilent, fprintf(1,'Using a histogram with %u bins\n',nbins); end
goodies = ~isnan(F); % now we can deal with NaNs into design matrix
mis = zeros(n1);
mitimer = tic; % Way faster to not store the time taken for every iteration
for i = 1:n1
% tic
goodi = goodies(i,:);
for j = i:n1
goodj = goodies(j,:);
goodboth = (goodi & goodj);
mis(i,j) = BF_MutualInformation(F(i,goodboth),F(j,goodboth),'quantile','quantile',nbins); % by quantile with nbins
mis(j,i) = mis(i,j);
end
if (mod(i,floor(n1/50)) == 0)
fprintf(1,'Approximately %s remaining! We''re at %u / %u\n', ...
BF_thetime(toc(mitimer)/i*(n1-i)),i,n1)
end
end
clear mitimer % stop timing
R = mis; clear mis; % not really an R but ok.
case {'corr_fast','abscorr_fast'}
% Try using fast approximation to correlation coefficients when data includes NaNs
% This is an approximation in that it centers columns on their full mean rather than
% the mean of overlapping good values, but it's a start, and a good approximation
% for a small proportion of NaNs.
% Ben Fulcher, 2014-06-26
if ~beSilent,
fprintf(1,'Using BF_NaNCov to approximate correlations between %u objects...',size(F,1));
end
tic
R = BF_NaNCov(F',1,1);
if ~beSilent, fprintf(1,' Done in %s.\n',BF_thetime(toc)); end
case {'euclidean','Euclidean','corr','correlation','abscorr'}
% First use in-built pdist, which is fast
if ~beSilent
fprintf(1,'First computing pairwise distances using pdist...');
end
tic
if strcmp(distMetric,'abscorr')
R = pdist(F,'corr');
else
R = pdist(F,distMetric);
end
R = squareform(R); % Make a matrix
if ~beSilent
fprintf(1,' Done in %s.\n',BF_thetime(toc));
end
% Now go through and fill in any NaNs
[nani, nanj] = find(isnan(R));
if ~isempty(nani) % there are NaNs in R
ij = (nanj >= nani); % only keep diagonal or upper diagonal entries
nani = nani(ij);
nanj = nanj(ij);
NotNaN = ~isnan(F);
if ~beSilent
fprintf(1,['Recalculating distances individually for %u NaN ' ...
'entries in the distance matrix...\n'],length(nani));
end
NaNtimer = tic; % time it
for i = 1:length(nani)
ii = nani(i);
jj = nanj(i);
goodboth = (NotNaN(ii,:) & NotNaN(jj,:));
if mean(goodboth) >= minPropGood
R(ii,jj) = dij(F(ii,goodboth)',F(jj,goodboth)'); % Calculate the distance
else
R(ii,jj) = NaN; % Not enough good, overlapping set of values -- store as NaN.
end
R(jj,ii) = R(ii,jj); % Add the symmetrized entry
% Give update on time remaining after 1000 iterations (if more than 10000 total iterations)
% and then 5 more times...
if ~beSilent && ((i==1000 && length(nani) > 10000) || (mod(i,floor(length(nani)/5))==0))
fprintf(1,'Approximately %s remaining! We''re at %u / %u.\n', ...
BF_thetime(toc(NaNtimer)/i*(length(nani)-i)),i,length(nani))
end
end
clear NaNtimer % stop the timer
end
otherwise
error('Unknown distance metric ''%s''',distMetric);
end
% ------------------------------------------------------------------------------
% Transform from correlation distance to absolute correlation distance:
% ------------------------------------------------------------------------------
if ismember(distMetric,{'abscorr','abscorr_fast'})
R = 1 - abs(1-R);
end
% ------------------------------------------------------------------------------
% Convert from matrix back to a vector:
% ------------------------------------------------------------------------------
if toVector
try
R = squareform(R); % back to vector
catch
error('This metric is not consistant with a pairwise distance matrix...?')
end
end
% ------------------------------------------------------------------------------
function d = subdc(v1,v2,corrType)
rc = corr(v1,v2,'type',corrType);
if isnan(rc)
d = 2; % return maximum distance--for this subset, constant values
else
d = 1 - rc; % Return the (raw) correlation coefficient
end
end
% ------------------------------------------------------------------------------
end
|
github
|
BMHLab/CElegansConnectomeGeneExpression-master
|
BF_removeNaNColumns.m
|
.m
|
CElegansConnectomeGeneExpression-master/PeripheralFunctions/BF_removeNaNColumns.m
| 1,138 |
utf_8
|
ab75a92b242a05c5c2f8817b832a70fa
|
% ------------------------------------------------------------------------------
% Removes columns with NaNs in them
% ------------------------------------------------------------------------------
% Ben Fulcher, 2014-09-23 Added parameter that allows some proportion of bad values
% Ben Fulcher, 2014-07-08
% ------------------------------------------------------------------------------
function [A,KeepCol] = BF_removeNaNColumns(A,propBadTol)
% ------------------------------------------------------------------------------
% Check inputs:
% ------------------------------------------------------------------------------
if nargin < 2
% Can tolerate a proportion propBad of bad values
% Set to 0 by default (no tolerance for any bad values)
propBadTol = 0;
end
% ------------------------------------------------------------------------------
if propBadTol==0
KeepCol = arrayfun(@(x)~any(isnan(A(:,x))),1:size(A,2));
else
% Compute the proportion of NaN values in each column:
propBad = arrayfun(@(x)sum(isnan(A(:,x))),1:size(A,2))/size(A,1);
KeepCol = (propBad > propBadTol);
end
A = A(:,KeepCol);
end
|
github
|
jfrascon/SLAM_AND_PATH_PLANNING_ALGORITHMS-master
|
arrow.m
|
.m
|
SLAM_AND_PATH_PLANNING_ALGORITHMS-master/10-EXTRA_RESOURCES/MATLAB_SCRIPTS/arrow.m
| 59,561 |
utf_8
|
c7638a77607ba7fa39d3d641f7bd4ce7
|
function [h,yy,zz] = arrow(varargin)
% ARROW Draw a line with an arrowhead.
%
% ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points
% should be vectors of length 2 or 3, or matrices with 2 or 3
% columns), and returns the graphics handle of the arrow(s).
%
% ARROW uses the mouse (click-drag) to create an arrow.
%
% ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW.
%
% ARROW may be called with a normal argument list or a property-based list.
% ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is
% the full normal argument list, where all but the Start and Stop
% points are optional. If you need to specify a later argument (e.g.,
% Page) but want default values of earlier ones (e.g., TipAngle),
% pass an empty matrix for the earlier ones (e.g., TipAngle=[]).
%
% ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the
% given properties, using default values for any unspecified or given as
% 'default' or NaN. Some properties used for line and patch objects are
% used in a modified fashion, others are passed directly to LINE, PATCH,
% or SET. For a detailed properties explanation, call ARROW PROPERTIES.
%
% Start The starting points. B
% Stop The end points. /|\ ^
% Length Length of the arrowhead in pixels. /|||\ |
% BaseAngle Base angle in degrees (ADE). //|||\\ L|
% TipAngle Tip angle in degrees (ABC). ///|||\\\ e|
% Width Width of the base in pixels. ////|||\\\\ n|
% Page Use hardcopy proportions. /////|D|\\\\\ g|
% CrossDir Vector || to arrowhead plane. //// ||| \\\\ t|
% NormalDir Vector out of arrowhead plane. /// ||| \\\ h|
% Ends Which end has an arrowhead. //<----->|| \\ |
% ObjectHandles Vector of handles to update. / base ||| \ V
% E angle||<-------->C
% ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle
% vector of handles to previously-created arrows |||
% and/or line objects, will update the previously- |||
% created arrows according to the current view -->|A|<-- width
% and any specified properties, and will convert
% two-point line objects to corresponding arrows. ARROW(H) will update
% the arrows if the current view has changed. Root, figure, or axes
% handles included in H are replaced by all descendant Arrow objects.
%
% A property list can follow any specified normal argument list, e.g.,
% ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to
% the origin, with an arrowhead of length 36 pixels and 60-degree base angle.
%
% Normally, an ARROW is a PATCH object, so any valid PATCH property/value pairs
% can be passed, e.g., ARROW(Start,Stop,'EdgeColor','r','FaceColor','g').
% ARROW will use LINE objects when requested by ARROW(...,'Type','line') or,
% using LINE property/value pairs, ARROW(Start,Stop,'Type','line','Color','b').
%
% The basic arguments or properties can generally be vectorized to create
% multiple arrows with the same call. This is done by passing a property
% with one row per arrow, or, if all arrows are to have the same property
% value, just one row may be specified.
%
% You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change
% the axes on you; ARROW determines the sizes of arrow components BEFORE the
% arrow is plotted, so if ARROW changes axis limits, arrows may be malformed.
%
% This version of ARROW uses features of MATLAB 6.x and is incompatible with
% earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately);
% some problems with perspective plots still exist.
% Copyright (c)1995-2016, Dr. Erik A. Johnson <[email protected]>, 5/25/2016
% http://www.usc.edu/civil_eng/johnsone/
% Revision history:
% 5/25/16 EAJ Add documentation of 'Type','line'
% Add documentation of how to set color
% Add 'Color' property (which sets both 'EdgeColor' and 'FaceColor' for patch objects)
% 5/24/16 EAJ Remove 'EraseMode' in HG2
% 7/16/14 EAJ R2014b HandleGraphics2 compatibility
% 7/14/14 EAJ 5/20/13 patch extension didn't work right in HG2
% so break the arrow along its length instead
% 5/20/13 EAJ Extend patch line one more segment so EPS/PDF printed versions
% have nice rounded tips when the LineWidth is wider
% 2/06/13 EAJ Add ShortenLength property to shorten length if arrow is short
% 1/24/13 EAJ Remove some old comments.
% 5/20/09 EAJ Fix view direction in (3D) demo.
% 6/26/08 EAJ Replace eval('trycmd','catchcmd') with try, trycmd; catch,
% catchcmd; end; -- break's MATLAB 5 compatibility.
% 8/26/03 EAJ Eliminate OpenGL attempted fix since it didn't fix anyway.
% 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals
% 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug
% if zero 'Width' or not double-ended
% 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3.
% 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes.
% 11/10/99 EAJ Update e-mail address.
% 2/10/99 EAJ Some documentation updating.
% 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint.
% 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug.
% 7/21/97 EAJ Fixed a few misc bugs.
% 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles)
% 6/23/97 EAJ MATLAB 5 compatible version, release.
% 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs.
% 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows.
% 5/19/97 EAJ MATLAB 5 compatible version, beta.
% 4/13/97 EAJ MATLAB 5 compatible version, alpha.
% 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords.
% 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified
% 10/24/96 EAJ Fixed bug with log plots and NormalDir specified
% 11/13/95 EAJ Corrected handling for 'reverse' axis directions
% 10/06/95 EAJ Corrected occasional conflict with SUBPLOT
% 4/24/95 EAJ A major rewrite.
% Fall 94 EAJ Original code.
% Things to be done:
% - in the arrow_clicks section, prompt by printing to the screen so that
% the user knows what's going on; also make sure the figure is brought
% to the front.
% - segment parsing, computing, and plotting into separate subfunctions
% - change computing from Xform to Camera paradigms
% + this will help especially with 3-D perspective plots
% + if the WarpToFill section works right, remove warning code
% + when perpsective works properly, remove perspective warning code
% - add cell property values and struct property name/values (like get/set)
% - get rid of NaN as the "default" data label
% + perhaps change userdata to a struct and don't include (or leave
% empty) the values specified as default; or use a cell containing
% an empty matrix for a default value
% - add functionality of GET to retrieve current values of ARROW properties
%
% New list of things to be done:
% - rewrite as a graphics or class object that updates itself in real time
% (but have a 'Static' or 'DoNotUpdate' property to avoid updating)
% Permission is granted to distribute ARROW with the toolboxes for the book
% "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al.
% (Prentice Hall, 1999).
% Permission is granted to Dr. Josef Bigun to distribute ARROW with his
% software to reproduce the figures in his image analysis text.
% global variable initialization
persistent ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS ARROW_AX
if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end;
if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end;
% Handle callbacks
if (nargin>0 & isstr(varargin{1}) & strcmp(lower(varargin{1}),'callback')),
arrow_callback(varargin{2:end}); return;
end;
% Are we doing the demo?
c = sprintf('\n');
if (nargin==1 & isstr(varargin{1})),
arg1 = lower(varargin{1});
if strncmp(arg1,'prop',4), arrow_props;
elseif strncmp(arg1,'demo',4)
clf reset
demo_info = arrow_demo;
if ~strncmp(arg1,'demo2',5),
hh=arrow_demo3(demo_info);
else,
hh=arrow_demo2(demo_info);
end;
if (nargout>=1), h=hh; end;
elseif strncmp(arg1,'fixlimits',3),
arrow_fixlimits(ARROW_AX,ARROW_AXLIMITS);
ARROW_AXLIMITS=[]; ARROW_AX=[];
elseif strncmp(arg1,'help',4),
disp(help(mfilename));
else,
error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1) '''.']);
end;
return;
end;
% Check # of arguments
if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end;
% find first property number
firstprop = nargin+1;
for k=1:length(varargin), if ~isnumeric(varargin{k}) && ~all(ishandle(varargin{k})), firstprop=k; break; end; end; %eaj 5/24/16 for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end;
lastnumeric = firstprop-1;
% check property list
if (firstprop<=nargin),
for k=firstprop:2:nargin,
curarg = varargin{k};
if ~isstr(curarg) | sum(size(curarg)>1)>1,
error([upper(mfilename) ' requires that a property name be a single string.']);
end;
end;
if (rem(nargin-firstprop,2)~=1),
error([upper(mfilename) ' requires that the property ''' ...
varargin{nargin} ''' be paired with a property value.']);
end;
end;
% default output
if (nargout>0), h=[]; end;
if (nargout>1), yy=[]; end;
if (nargout>2), zz=[]; end;
% set values to empty matrices
start = [];
stop = [];
len = [];
baseangle = [];
tipangle = [];
wid = [];
page = [];
crossdir = [];
ends = [];
shorten = [];
ax = [];
oldh = [];
ispatch = [];
defstart = [NaN NaN NaN];
defstop = [NaN NaN NaN];
deflen = 16;
defbaseangle = 90;
deftipangle = 16;
defwid = 0;
defpage = 0;
defcrossdir = [NaN NaN NaN];
defends = 1;
defshorten = 0;
defoldh = [];
defispatch = 1;
% The 'Tag' we'll put on our arrows
ArrowTag = 'Arrow';
% check for oldstyle arguments
if (firstprop==2),
% assume arg1 is a set of handles
oldh = varargin{1}(:);
if isempty(oldh), return; end;
elseif (firstprop>9),
error([upper(mfilename) ' takes at most 8 non-property arguments.']);
elseif (firstprop>2),
{start,stop,len,baseangle,tipangle,wid,page,crossdir};
args = [varargin(1:firstprop-1) cell(1,length(ans)-(firstprop-1))];
[start,stop,len,baseangle,tipangle,wid,page,crossdir] = deal(args{:});
end;
% parse property pairs
extraprops={};
for k=firstprop:2:nargin,
prop = varargin{k};
val = varargin{k+1};
prop = [lower(prop(:)') ' '];
if strncmp(prop,'start' ,5), start = val;
elseif strncmp(prop,'stop' ,4), stop = val;
elseif strncmp(prop,'len' ,3), len = val(:);
elseif strncmp(prop,'base' ,4), baseangle = val(:);
elseif strncmp(prop,'tip' ,3), tipangle = val(:);
elseif strncmp(prop,'wid' ,3), wid = val(:);
elseif strncmp(prop,'page' ,4), page = val;
elseif strncmp(prop,'cross' ,5), crossdir = val;
elseif strncmp(prop,'norm' ,4), if (isstr(val)), crossdir=val; else, crossdir=val*sqrt(-1); end;
elseif strncmp(prop,'end' ,3), ends = val;
elseif strncmp(prop,'shorten',5), shorten = val;
elseif strncmp(prop,'object' ,6), oldh = val(:);
elseif strncmp(prop,'handle' ,6), oldh = val(:);
elseif strncmp(prop,'type' ,4), ispatch = val;
elseif strncmp(prop,'userd' ,5), %ignore it
else,
% make sure it is a valid patch or line property
try
get(0,['DefaultPatch' varargin{k}]);
catch
errstr = lasterr;
try
get(0,['DefaultLine' varargin{k}]);
catch
errstr(1:max(find(errstr==char(13)|errstr==char(10)))) = '';
error([upper(mfilename) ' got ' errstr]);
end
end;
extraprops={extraprops{:},varargin{k},val};
end;
end;
% Check if we got 'default' values
start = arrow_defcheck(start ,defstart ,'Start' );
stop = arrow_defcheck(stop ,defstop ,'Stop' );
len = arrow_defcheck(len ,deflen ,'Length' );
baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' );
tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' );
wid = arrow_defcheck(wid ,defwid ,'Width' );
crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' );
page = arrow_defcheck(page ,defpage ,'Page' );
ends = arrow_defcheck(ends ,defends ,'' );
shorten = arrow_defcheck(shorten ,defshorten ,'' );
oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles');
ispatch = arrow_defcheck(ispatch ,defispatch ,'' );
% check transpose on arguments
[m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end;
[m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end;
[m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end;
% convert strings to numbers
if ~isempty(ends) & isstr(ends),
endsorig = ends;
[m,n] = size(ends);
col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']);
ends = NaN*ones(m,1);
oo = ones(1,m);
ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end;
ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end;
ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end;
ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end;
if any(isnan(ends)),
ii = min(find(isnan(ends)));
error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']);
end;
else,
ends = ends(:);
end;
if ~isempty(ispatch) & isstr(ispatch),
col = lower(ispatch(:,1));
patchchar='p'; linechar='l'; defchar=' ';
mask = col~=patchchar & col~=linechar & col~=defchar;
if any(mask),
error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:)) ''' as a valid ''Type'' value.']);
end;
ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch;
else,
ispatch = ispatch(:);
end;
oldh = oldh(:);
% check object handles
if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end;
% expand root, figure, and axes handles
if ~isempty(oldh),
ohtype = get(oldh,'Type');
mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes');
if any(mask),
oldh = num2cell(oldh);
for ii=find(mask)',
oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)};
end;
oldh = cat(1,oldh{:});
if isempty(oldh), return; end; % no arrows to modify, so just leave
end;
end;
% largest argument length
[mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir);
argsizes = [length(oldh) mstart mstop ...
length(len) length(baseangle) length(tipangle) ...
length(wid) length(page) mcrossdir length(ends) length(shorten)];
args=['length(ObjectHandle) '; ...
'#rows(Start) '; ...
'#rows(Stop) '; ...
'length(Length) '; ...
'length(BaseAngle) '; ...
'length(TipAngle) '; ...
'length(Width) '; ...
'length(Page) '; ...
'#rows(CrossDir) '; ...
'#rows(Ends) '; ...
'length(ShortenLength) '];
if (any(imag(crossdir(:))~=0)),
args(9,:) = '#rows(NormalDir) ';
end;
if isempty(oldh),
narrows = max(argsizes);
else,
narrows = length(oldh);
end;
if (narrows<=0), narrows=1; end;
% Check size of arguments
ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows));
if ~isempty(ii),
s = args(ii',:);
while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))),
s = s(:,1:size(s,2)-1);
end;
s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ...
ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]];
s = s';
s = s(:)';
s = s(1:length(s)-1);
error(setstr(s));
end;
% check element length in Start, Stop, and CrossDir
if ~isempty(start),
[m,n] = size(start);
if (n==2),
start = [start NaN*ones(m,1)];
elseif (n~=3),
error([upper(mfilename) ' requires 2- or 3-element Start points.']);
end;
end;
if ~isempty(stop),
[m,n] = size(stop);
if (n==2),
stop = [stop NaN*ones(m,1)];
elseif (n~=3),
error([upper(mfilename) ' requires 2- or 3-element Stop points.']);
end;
end;
if ~isempty(crossdir),
[m,n] = size(crossdir);
if (n<3),
crossdir = [crossdir NaN*ones(m,3-n)];
elseif (n~=3),
if (all(imag(crossdir(:))==0)),
error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']);
else,
error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']);
end;
end;
end;
% fill empty arguments
if isempty(start ), start = [Inf Inf Inf]; end;
if isempty(stop ), stop = [Inf Inf Inf]; end;
if isempty(len ), len = Inf; end;
if isempty(baseangle ), baseangle = Inf; end;
if isempty(tipangle ), tipangle = Inf; end;
if isempty(wid ), wid = Inf; end;
if isempty(page ), page = Inf; end;
if isempty(crossdir ), crossdir = [Inf Inf Inf]; end;
if isempty(ends ), ends = Inf; end;
if isempty(shorten ), shorten = Inf; end;
if isempty(ispatch ), ispatch = Inf; end;
% expand single-column arguments
o = ones(narrows,1);
if (size(start ,1)==1), start = o * start ; end;
if (size(stop ,1)==1), stop = o * stop ; end;
if (length(len )==1), len = o * len ; end;
if (length(baseangle )==1), baseangle = o * baseangle ; end;
if (length(tipangle )==1), tipangle = o * tipangle ; end;
if (length(wid )==1), wid = o * wid ; end;
if (length(page )==1), page = o * page ; end;
if (size(crossdir ,1)==1), crossdir = o * crossdir ; end;
if (length(ends )==1), ends = o * ends ; end;
if (length(shorten )==1), shorten = o * shorten ; end;
if (length(ispatch )==1), ispatch = o * ispatch ; end;
ax = repmat(gca,narrows,1); %eaj 7/16/14 ax=gca; if ~isnumeric(ax), ax=double(ax); end; ax=o*ax;
% if we've got handles, get the defaults from the handles
if ~isempty(oldh),
for k=1:narrows,
oh = oldh(k);
ud = get(oh,'UserData');
ax(k) = get(oh,'Parent'); %eaj 7/16/14 get(oh,'Parent'); if ~isnumeric(ans), double(ans); end; ax(k)=ans;
ohtype = get(oh,'Type');
if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already
if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end;
% arrow UserData format: [start' stop' len base tip wid page crossdir' ends shorten]
start0 = ud(1:3);
stop0 = ud(4:6);
if (isinf(len(k))), len(k) = ud( 7); end;
if (isinf(baseangle(k))), baseangle(k) = ud( 8); end;
if (isinf(tipangle(k))), tipangle(k) = ud( 9); end;
if (isinf(wid(k))), wid(k) = ud(10); end;
if (isinf(page(k))), page(k) = ud(11); end;
if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end;
if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end;
if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end;
if (isinf(ends(k))), ends(k) = ud(15); end;
if (isinf(shorten(k))), shorten(k) = ud(16); end;
elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or patch
convLineToPatch = 1; %set to make arrow patches when converting from lines.
if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end;
x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end;
y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end;
z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end;
start0 = [x(1) y(1) z(1) ];
stop0 = [x(end) y(end) z(end)];
else,
error([upper(mfilename) ' cannot convert ' ohtype ' objects.']);
end;
ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end;
ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end;
end;
end;
% convert Inf's to NaN's
start( isinf(start )) = NaN;
stop( isinf(stop )) = NaN;
len( isinf(len )) = NaN;
baseangle( isinf(baseangle)) = NaN;
tipangle( isinf(tipangle )) = NaN;
wid( isinf(wid )) = NaN;
page( isinf(page )) = NaN;
crossdir( isinf(crossdir )) = NaN;
ends( isinf(ends )) = NaN;
shorten( isinf(shorten )) = NaN;
ispatch( isinf(ispatch )) = NaN;
% set up the UserData data (here so not corrupted by log10's and such)
ud = [start stop len baseangle tipangle wid page crossdir ends shorten];
% Set Page defaults
page = ~isnan(page) & trueornan(page);
% Get axes limits, range, min; correct for aspect ratio and log scale
axm = zeros(3,narrows);
axr = zeros(3,narrows);
axrev = zeros(3,narrows);
ap = zeros(2,narrows);
xyzlog = zeros(3,narrows);
limmin = zeros(2,narrows);
limrange = zeros(2,narrows);
oldaxlims = zeros(6,narrows);
oneax = all(ax==ax(1));
if (oneax),
T = zeros(4,4);
invT = zeros(4,4);
else,
T = zeros(16,narrows);
invT = zeros(16,narrows);
end;
axnotdone = true(size(ax));
while (any(axnotdone)),
ii = find(axnotdone,1);
curax = ax(ii);
curpage = page(ii);
% get axes limits and aspect ratio
axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')];
ax==curax; oldaxlims(:,ans)=repmat(reshape(axl',[],1),1,sum(ans));
% get axes size in pixels (points)
u = get(curax,'Units');
axposoldunits = get(curax,'Position');
really_curpage = curpage & strcmp(u,'normalized');
if (really_curpage),
curfig = get(curax,'Parent');
pu = get(curfig,'PaperUnits');
set(curfig,'PaperUnits','points');
pp = get(curfig,'PaperPosition');
set(curfig,'PaperUnits',pu);
set(curax,'Units','pixels');
curapscreen = get(curax,'Position');
set(curax,'Units','normalized');
curap = pp.*get(curax,'Position');
else,
set(curax,'Units','pixels');
curapscreen = get(curax,'Position');
curap = curapscreen;
end;
set(curax,'Units',u);
set(curax,'Position',axposoldunits);
% handle non-stretched axes position
str_stretch = { 'DataAspectRatioMode' ; ...
'PlotBoxAspectRatioMode' ; ...
'CameraViewAngleMode' };
str_camera = { 'CameraPositionMode' ; ...
'CameraTargetMode' ; ...
'CameraViewAngleMode' ; ...
'CameraUpVectorMode' };
notstretched = strcmp(get(curax,str_stretch),'manual');
manualcamera = strcmp(get(curax,str_camera),'manual');
if ~arrow_WarpToFill(notstretched,manualcamera,curax),
% give a warning that this has not been thoroughly tested
if 0 & ARROW_STRETCH_WARN,
ARROW_STRETCH_WARN = 0;
strs = {str_stretch{1:2},str_camera{:}};
strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]';
warning([upper(mfilename) ' may not yet work quite right ' ...
'if any of the following are ''manual'':' strs(:).']);
end;
% find the true pixel size of the actual axes
texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ...
axl(2,[1 1 2 2 1 1 2 2]), ...
axl(3,[1 1 1 1 2 2 2 2]),'');
set(texttmp,'Units','points');
textpos = get(texttmp,'Position');
delete(texttmp);
textpos = cat(1,textpos{:});
textpos = max(textpos(:,1:2)) - min(textpos(:,1:2));
% adjust the axes position
if (really_curpage),
% adjust to printed size
textpos = textpos * min(curap(3:4)./textpos);
curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];
else,
% adjust for pixel roundoff
textpos = textpos * min(curapscreen(3:4)./textpos);
curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos];
end;
end;
if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'),
ARROW_PERSP_WARN = 0;
warning([upper(mfilename) ' does not yet work right for 3-D perspective projection.']);
end;
% adjust limits for log scale on axes
curxyzlog = strcmp(get(curax,{'XScale' 'YScale' 'ZScale'})','log');
if (any(curxyzlog)),
ii = find([curxyzlog;curxyzlog]);
if (any(axl(ii)<=0)),
error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']);
else,
axl(ii) = log10(axl(ii));
end;
end;
% correct for 'reverse' direction on axes;
curreverse = strcmp(get(curax,{'XDir' 'YDir' 'ZDir'})','reverse');
ii = find(curreverse);
if ~isempty(ii),
axl(ii,[1 2])=-axl(ii,[2 1]);
end;
% compute the range of 2-D values
try, curT=get(curax,'Xform'); catch, num2cell(get(curax,'View')); curT=viewmtx(ans{:}); end;
lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1];
lim = lim(1:2,:)./([1;1]*lim(4,:));
curlimmin = min(lim')';
curlimrange = max(lim')' - curlimmin;
curinvT = inv(curT);
if (~oneax),
curT = curT.';
curinvT = curinvT.';
curT = curT(:);
curinvT = curinvT(:);
end;
% check which arrows to which cur corresponds
ii = find((ax==curax)&(page==curpage));
oo = ones(1,length(ii));
axr(:,ii) = diff(axl')' * oo;
axm(:,ii) = axl(:,1) * oo;
axrev(:,ii) = curreverse * oo;
ap(:,ii) = curap(3:4)' * oo;
xyzlog(:,ii) = curxyzlog * oo;
limmin(:,ii) = curlimmin * oo;
limrange(:,ii) = curlimrange * oo;
if (oneax),
T = curT;
invT = curinvT;
else,
T(:,ii) = curT * oo;
invT(:,ii) = curinvT * oo;
end;
axnotdone(ii) = zeros(1,length(ii));
end;
% correct for log scales
curxyzlog = xyzlog.';
ii = find(curxyzlog(:));
if ~isempty(ii),
start( ii) = real(log10(start( ii)));
stop( ii) = real(log10(stop( ii)));
if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj
crossdir(ii) = real(log10(crossdir(ii)));
end;
end;
% correct for reverse directions
ii = find(axrev.');
if ~isempty(ii),
start( ii) = -start( ii);
stop( ii) = -stop( ii);
crossdir(ii) = -crossdir(ii);
end;
% transpose start/stop values
start = start.';
stop = stop.';
% take care of defaults, page was done above
ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end;
ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end;
ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end;
ii=find(isnan(len )); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end;
ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) = ones(length(ii),1)*defbaseangle; end;
ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) = ones(length(ii),1)*deftipangle; end;
ii=find(isnan(wid )); if ~isempty(ii), wid(ii) = ones(length(ii),1)*defwid; end;
ii=find(isnan(ends )); if ~isempty(ii), ends(ii) = ones(length(ii),1)*defends; end;
ii=find(isnan(shorten )); if ~isempty(ii), shorten(ii) = ones(length(ii),1)*defshorten; end;
% transpose rest of values
len = len.';
baseangle = baseangle.';
tipangle = tipangle.';
wid = wid.';
page = page.';
crossdir = crossdir.';
ends = ends.';
shorten = shorten.';
ax = ax.';
% given x, a 3xN matrix of points in 3-space;
% want to convert to X, the corresponding 4xN 2-space matrix
%
% tmp1=[(x-axm)./axr; ones(1,size(x,1))];
% if (oneax), X=T*tmp1;
% else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
% tmp2=zeros(4,4*N); tmp2(:)=tmp1(:);
% X=zeros(4,N); X(:)=sum(tmp2)'; end;
% X = X ./ (ones(4,1)*X(4,:));
% for all points with start==stop, start=stop-(verysmallvalue)*(up-direction);
ii = find(all(start==stop));
if ~isempty(ii),
% find an arrowdir vertical on screen and perpendicular to viewer
% transform to 2-D
tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))];
if (oneax), twoD=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1;
tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);
twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end;
twoD=twoD./(ones(4,1)*twoD(4,:));
% move the start point down just slightly
tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii));
% transform back to 3-D
if (oneax), threeD=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1;
tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:);
threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end;
start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii);
end;
% compute along-arrow points
% transform Start points
tmp1=[(start-axm)./axr;ones(1,narrows)];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% transform Stop points
tmp1=[(stop-axm)./axr;ones(1,narrows)];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute pixel distance between points
D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2));
D = D + (D==0); %eaj new 2/24/98
% shorten the length if requested % added 2/6/2013
numends = (ends==1) + (ends==2) + 2*(ends==3);
mask = shorten & D<len.*numends;
len(mask) = D(mask) ./ numends(mask);
% compute and modify along-arrow distances
len1 = len;
len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi);
slen0 = zeros(1,narrows);
slen1 = len1 .* ((ends==2)|(ends==3));
slen2 = len2 .* ((ends==2)|(ends==3));
len0 = zeros(1,narrows);
len1 = len1 .* ((ends==1)|(ends==3));
len2 = len2 .* ((ends==1)|(ends==3));
% for no start arrowhead
ii=find((ends==1)&(D<len2));
if ~isempty(ii),
slen0(ii) = D(ii)-len2(ii);
end;
% for no end arrowhead
ii=find((ends==2)&(D<slen2));
if ~isempty(ii),
len0(ii) = D(ii)-slen2(ii);
end;
len1 = len1 + len0;
len2 = len2 + len0;
slen1 = slen1 + slen0;
slen2 = slen2 + slen0;
% note: the division by D below will probably not be accurate if both
% of the following are true:
% 1. the ratio of the line length to the arrowhead
% length is large
% 2. the view is highly perspective.
% compute stoppoints
tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute tippoints
tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute basepoints
tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute startpoints
tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute stippoints
tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute sbasepoints
tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D));
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1;
tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end;
sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm;
% compute cross-arrow directions for arrows with NormalDir specified
if (any(imag(crossdir(:))~=0)),
ii = find(any(imag(crossdir)~=0));
crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ...
imag(crossdir(:,ii))).*axr(:,ii);
end;
% compute cross-arrow directions
basecross = crossdir + basepoint;
tipcross = crossdir + tippoint;
sbasecross = crossdir + sbasepoint;
stipcross = crossdir + stippoint;
ii = find(all(crossdir==0)|any(isnan(crossdir)));
if ~isempty(ii),
numii = length(ii);
% transform start points
tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)];
tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]);
tmp1 = [tmp1; ones(1,4*numii)];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% transform stop points
tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)];
tmp1 = [tmp1 tmp1 tmp1 tmp1];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute perpendicular directions
pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2;
pixfact = [pixfact pixfact pixfact pixfact];
pixfact = [pixfact;1./pixfact];
[dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:)));
jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj);
jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj));
jj3 = jj1(1:2,:);
Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98
Xp = X0;
Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1);
Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3);
% inverse transform the cross points
if (oneax), Xp=invT*Xp;
else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1;
tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:);
Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end;
Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]);
basecross(:,ii) = Xp(:,0*numii+(1:numii));
tipcross(:,ii) = Xp(:,1*numii+(1:numii));
sbasecross(:,ii) = Xp(:,2*numii+(1:numii));
stipcross(:,ii) = Xp(:,3*numii+(1:numii));
end;
% compute all points
% compute start points
axm11 = [axm axm axm axm axm axm axm axm axm axm axm];
axr11 = [axr axr axr axr axr axr axr axr axr axr axr];
st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint];
tmp1 = (st - axm11) ./ axr11;
tmp1 = [tmp1; ones(1,size(tmp1,2))];
if (oneax), X0=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end;
X0=X0./(ones(4,1)*X0(4,:));
% compute stop points
tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ...
- axm11) ./ axr11;
tmp1 = [tmp1; ones(1,size(tmp1,2))];
if (oneax), Xf=T*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end;
Xf=Xf./(ones(4,1)*Xf(4,:));
% compute lengths
len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi);
slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi);
le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)];
aprange = ap./limrange;
aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange];
D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2));
Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings
tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D));
% inverse transform
if (oneax), tmp3=invT*tmp1;
else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1;
tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:);
tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end;
pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11;
% correct for ones where the crossdir was specified
ii = find(~(all(crossdir==0)|any(isnan(crossdir))));
if ~isempty(ii),
D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ...
pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ...
pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ...
pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ...
pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ...
pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ...
pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ...
pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2;
ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows;
ii = ii(:)';
pts(:,ii) = st(:,ii) + D1;
end;
% readjust for reverse directions
iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).';
tmp1=axrev(:,iicols);
ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end;
% change from starting/ending at the stop point to doing it at the midpoint %eaj 7/14/2014
(pts(:,2*narrows+1:3*narrows)+pts(:,3*narrows+1:4*narrows))/2; %eaj 7/14/2014
pts = [ans pts(:,[3*narrows+1:end narrows+1:3*narrows]) ans]; %eaj 7/14/2014
% readjust for log scale on axes
tmp1=xyzlog(:,iicols);
ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end;
% compute the x,y,z coordinates of the patches;
ii = narrows*(0:size(pts,2)/narrows-1)'*ones(1,narrows) + ones(size(pts,2)/narrows,1)*(1:narrows);
ii = ii(:)';
x = zeros(size(pts,2)/narrows,narrows);
y = zeros(size(pts,2)/narrows,narrows);
z = zeros(size(pts,2)/narrows,narrows);
x(:) = pts(1,ii)';
y(:) = pts(2,ii)';
z(:) = pts(3,ii)';
% do the output
if (nargout<=1),
% % create or modify the patches
newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch'));
newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line'));
if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end;
% % make or modify the arrows
for k=1:narrows,
if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end;
xx=x(:,k); yy=y(:,k);
if (0), % this fix didn't work, so let's not use it -- 8/26/03
% try to work around a MATLAB 6.x OpenGL bug -- 7/28/02
mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2);
xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end;
end;
% plot the patch or line
if newpatch(k) || trueornan(ispatch(k)) %eaj 7/14/2014, 5/25/2016
% patch is closed so don't need endpoints %eaj 7/14/2014
if ~isempty(xx), xx(end)=[]; end; %eaj 7/14/2014
if ~isempty(yy), yy(end)=[]; end; %eaj 7/14/2014
if ~isempty(zz), zz(end)=[]; end; %eaj 7/14/2014
end %eaj 7/14/2014
xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag};
if newpatch(k)|newline(k),
if newpatch(k),
H(k) = patch(xyz{:});
else,
H(k) = line(xyz{:});
end;
if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end;
else,
if strcmp(get(H(k),'Type'),'patch') %eaj 5/25/16 if ispatch(k)
xyz = {xyz{:},'CData',[]};
end;
set(H(k),xyz{:});
end;
end;
if ~isempty(oldh), delete(oldh(oldh~=H)); end;
% % additional properties
set(H,'Clipping','off');
set(H,{'UserData'},num2cell(ud,2));
if length(extraprops)>0
ii = find(strcmpi(extraprops(1:2:end),'color')); %eaj 5/25/16
ispatch = strcmp(get(H,'Type'),'patch');
%eaj start 5/25/16
while ~isempty(ii) && any(ispatch)
if ii>1, set(H,extraprops{1:2*ii-2}); end;
c = extraprops{2*ii};
extraprops(1:2*ii) = [];
ii(1) = [];
if all(ispatch) || ischar(c)&&size(c,1)==1 || isnumeric(c)&&isequal(size(c),[1 3])
set(H,'EdgeColor',c,'FaceColor',c)
elseif iscell(c) && numel(c)~=numel(H)
set(H(ispatch),'EdgeColor',c(ispatch),'FaceColor',c(ispatch));
set(H(~ispatch),'Color',c(~ispatch));
elseif isnumeric(c) && isequal(size(c),[numel(H) 3])
set(H(ispatch),'EdgeColor',num2cell(c(ispatch,:),2),'FaceColor',num2cell(c(ispatch,:),2));
set(H(~ispatch),'Color',num2cell(c(~ispatch,:),2));
else
warning('ignoring unknown or invalid ''Color'' specification');
end
end
if ~isempty(extraprops)
%eaj end 5/25/16
set(H,extraprops{:});
end %eaj 5/25/16
end
% handle choosing arrow Start and/or Stop locations if unspecified
[H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims);
if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end;
% set the output
if (nargout>0), h=H; end;
% make sure the axis limits did not change
if isempty(oldaxlims),
ARROW_AXLIMITS = [];
ARROW_AX = [];
else,
lims = get(ax(:),{'XLim','YLim','ZLim'})';
lims = reshape(cat(2,lims{:}),6,size(lims,2));
mask = arrow_is2DXY(ax(:));
oldaxlims(5:6,mask) = lims(5:6,mask);
% store them for possible restoring
mask = any(oldaxlims~=lims,1); ARROW_AX=ax(mask); ARROW_AXLIMITS=oldaxlims(:,mask);
if any(mask),
warning(arrow_warnlimits(ARROW_AX,narrows));
end;
end;
else,
% don't create the patch, just return the data
h=x;
yy=y;
zz=z;
end;
function out = arrow_defcheck(in,def,prop)
% check if we got 'default' values
out = in;
if ~isstr(in), return; end;
if size(in,1)==1 & strncmp(lower(in),'def',3),
out = def;
elseif ~isempty(prop),
error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop ''' string.']);
end;
function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims)
% handle choosing arrow Start and/or Stop locations if necessary
errstr = '';
if isempty(H)|isempty(ud)|isempty(x), return; end;
% determine which (if any) need Start and/or Stop
needStart = all(isnan(ud(:,1:3)'))';
needStop = all(isnan(ud(:,4:6)'))';
mask = any(needStart|needStop);
if ~any(mask), return; end;
ud(~mask,:)=[]; ax(:,~mask)=[];
x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[];
% make them invisible for the time being
set(H,'Visible','off');
% save the current axes and limits modes; set to manual for the time being
oldAx = gca;
limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'});
set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'});
% loop over each arrow that requires attention
jj = find(mask);
for ii=1:length(jj),
h = H(jj(ii));
axes(ax(ii));
% figure out correct call
if needStart(ii), prop='Start'; else, prop='Stop'; end;
[wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii));
% handle errors and control-C
if wasInterrupted,
delete(H(jj(ii:end)));
H(jj(ii:end))=[];
oldaxlims(jj(ii:end),:)=[];
break;
end;
end;
% restore the axes and limit modes
axes(oldAx);
set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes);
function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax)
% handle the clicks for one arrow
fig = get(ax,'Parent');
% save some things
oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'};
oldFigValue = get(fig,oldFigProps);
oldArrowProps = {'EraseMode'};
if ~isnumeric(fig), oldArrowProps={}; end %eaj 5/24/16 % only use in HG2
oldArrowValue = get(H,oldArrowProps);
if isnumeric(fig), %eaj 5/24/16
set(H,'EraseMode','background'); %because 'xor' makes shaft invisible unless Width>1 -- only use in HG2
end %eaj 5/24/16
global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z
ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax;
ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax);
set(fig,'Pointer','crosshair');
% set up the WindowButtonMotion so we can see the arrow while moving around
set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ...
'WindowButtonMotionFcn','');
if ~lockStart,
set(H,'Visible','on');
set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']);
end;
% wait for the button to be pressed
[wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig);
% if we wanted to click-drag, set the Start point
if lockStart & ~wasInterrupted,
pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z);
feval(mfilename,H,'Start',pt,'Stop',pt);
set(H,'Visible','on');
ARROW_CLICK_PROP='Stop';
set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']);
% wait for the mouse button to be released
try
waitfor(fig,'WindowButtonUpFcn','');
catch
errstr = lasterr;
wasInterrupted = 1;
end;
end;
if ~wasInterrupted, feval(mfilename,'callback','motion'); end;
% restore some things
set(gcf,oldFigProps,oldFigValue);
set(H,oldArrowProps,oldArrowValue);
function arrow_callback(varargin)
% handle redrawing callbacks
if nargin==0, return; end;
str = varargin{1};
if ~isstr(str), error([upper(mfilename) ' got an invalid Callback command.']); end;
s = lower(str);
if strcmp(s,'motion'),
% motion callback
global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z
feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z));
drawnow;
else,
error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback option.']);
end;
function out = arrow_point(ax,use_z)
% return the point on the given axes
if nargin==0, ax=gca; end;
if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end;
out = get(ax,'CurrentPoint');
out = out(1,:);
if ~use_z, out=out(1:2); end;
function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig)
% wait for button down ignoring object ButtonDownFcn's
if nargin==0, fig=gcf; end;
errstr = '';
% save ButtonDownFcn values
objs = findobj(fig);
buttonDownFcns = get(objs,'ButtonDownFcn');
mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask);
set(objs,'ButtonDownFcn','');
% save other figure values
figProps = {'KeyPressFcn','WindowButtonDownFcn'};
figValue = get(fig,figProps);
% do the real work
set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ...
'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')');
lasterr('');
try
waitfor(fig,'WindowButtonDownFcn','');
wasInterrupted = 0;
catch
wasInterrupted = 1;
end
wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),'');
if wasInterrupted, errstr=lasterr; end;
% restore ButtonDownFcn and other figure values
set(objs,'ButtonDownFcn',buttonDownFcns);
set(fig,figProps,figValue);
function [out,is2D] = arrow_is2DXY(ax)
% check if axes are 2-D X-Y plots
% may not work for modified camera angles, etc.
out = false(size(ax)); % 2-D X-Y plots
is2D = out; % any 2-D plots
views = get(ax(:),{'View'});
views = cat(1,views{:});
out(:) = abs(views(:,2))==90;
is2D(:) = out(:) | all(rem(views',90)==0)';
function out = arrow_planarkids(ax)
% check if axes descendents all have empty ZData (lines,patches,surfaces)
out = true(size(ax));
allkids = get(ax(:),{'Children'});
for k=1:length(allkids),
kids = get([findobj(allkids{k},'flat','Type','line')
findobj(allkids{k},'flat','Type','patch')
findobj(allkids{k},'flat','Type','surface')],{'ZData'});
for j=1:length(kids),
if ~isempty(kids{j}), out(k)=logical(0); break; end;
end;
end;
function arrow_fixlimits(ax,lims)
% reset the axis limits as necessary
if isempty(ax) || isempty(lims), disp([upper(mfilename) ' does not remember any axis limits to reset.']); end;
for k=1:numel(ax),
if any(get(ax(k),'XLim')~=lims(1:2,k)'), set(ax(k),'XLim',lims(1:2,k)'); end;
if any(get(ax(k),'YLim')~=lims(3:4,k)'), set(ax(k),'YLim',lims(3:4,k)'); end;
if any(get(ax(k),'ZLim')~=lims(5:6,k)'), set(ax(k),'ZLim',lims(5:6,k)'); end;
end;
function out = arrow_WarpToFill(notstretched,manualcamera,curax)
% check if we are in "WarpToFill" mode.
out = strcmp(get(curax,'WarpToFill'),'on');
% 'WarpToFill' is undocumented, so may need to replace this by
% out = ~( any(notstretched) & any(manualcamera) );
function out = arrow_warnlimits(ax,narrows)
% create a warning message if we've changed the axis limits
msg = '';
switch (numel(ax))
case 1, msg='';
case 2, msg='on two axes ';
otherwise, msg='on several axes ';
end;
msg = [upper(mfilename) ' changed the axis limits ' msg ...
'when adding the arrow'];
if (narrows>1), msg=[msg 's']; end;
out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ...
' FIXLIMITS to reset them now.'];
function arrow_copyprops(fm,to)
% copy line properties to patches
props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',...
'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ...
'Clipping','DeleteFcn','BusyAction','HandleVisibility', ...
'Selected','SelectionHighlight','Visible'};
if ~isnumeric(findobj('Type','root')), props(strcmp(props,'EraseMode'))=[]; end; %eaj 5/24/16
lineprops = {'Color', props{:}};
patchprops = {'EdgeColor',props{:}};
patch2props = {'FaceColor',patchprops{:}};
fmpatch = strcmp(get(fm,'Type'),'patch');
topatch = strcmp(get(to,'Type'),'patch');
set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p
set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l
set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l
set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch& topatch),lineprops) ,'FaceColor','none'); %l->p
function arrow_props
% display further help info about ARROW properties
c = sprintf('\n');
disp([c ...
'ARROW Properties: Default values are given in [square brackets], and other' c ...
' acceptable equivalent property names are in (parenthesis).' c c ...
' Start The starting points. For N arrows, B' c ...
' this should be a Nx2 or Nx3 matrix. /|\ ^' c ...
' Stop The end points. For N arrows, this /|||\ |' c ...
' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ...
' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ...
' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ...
' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ...
' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ...
' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ...
' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ...
' [16] (Tip) / base ||| \ V' c ...
' Width Width of the base in pixels. Not E angle ||<-------->C' c ...
' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ...
' Page If provided, non-empty, and not NaN, |||' c ...
' this causes ARROW to use hardcopy |||' c ...
' rather than onscreen proportions. A' c ...
' This is important if screen aspect --> <-- width' c ...
' ratio and hardcopy aspect ratio are ----CrossDir---->' c ...
' vastly different. []' c...
' CrossDir A vector giving the direction towards which the fletches' c ...
' on the arrow should go. [computed such that it is perpen-' c ...
' dicular to both the arrow direction and the view direction' c ...
' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ...
' that CrossDir is a vector. Also note that if an axis is' c ...
' plotted on a log scale, then the corresponding component' c ...
' of CrossDir must also be set appropriately, i.e., to 1 for' c ...
' no change in that direction, >1 for a positive change, >0' c ...
' and <1 for negative change.)' c ...
' NormalDir A vector normal to the fletch direction (CrossDir is then' c ...
' computed by the vector cross product [Line]x[NormalDir]). []' c ...
' (Note that NormalDir is a vector. Unlike CrossDir,' c ...
' NormalDir is used as is regardless of log-scaled axes.)' c ...
' Ends Set which end has an arrowhead. Valid values are ''none'',' c ...
' ''stop'', ''start'', and ''both''. [''stop''] (End)' c...
' ShortenLength Shorten length of arrowhead(s) if line is too short' c ...
' ObjectHandles Vector of handles to previously-created arrows to be' c ...
' updated or line objects to be converted to arrows.' c ...
' [] (Object,Handle)' c ...
' Type ''patch'' creates the arrow with a PATCH object (the default)' c ...
' and ''line'' creates it with a LINE object [''patch''].' c ...
' Color For patch arrows (the default), set both ''FaceColor'' and' c ...
' ''EdgeColor'' to the given value. For line arrows, set' c ...
' the ''Color'' property to the given value.' c ...
]);
function out = arrow_demo
% demo
% create the data
[x,y,z] = peaks;
[ddd,out.iii]=max(z(:));
out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))];
% modify it by inserting some NaN's
[m,n] = size(z);
m = floor(m/2);
n = floor(n/2);
z(1:m,1:n) = NaN*ones(m,n);
% graph it
clf('reset');
out.hs=surf(x,y,z);
out.x=x; out.y=y; out.z=z;
xlabel('x'); ylabel('y');
function h = arrow_demo3(in)
% set the view
axlim = in.axlim;
axis(axlim);
zlabel('z');
%set(in.hs,'FaceColor','interp');
view(3); % view(viewmtx(-37.5,30,20));
title(['Demo of the capabilities of the ARROW function in 3-D']);
% Normal blue arrow
h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ...
'EdgeColor','b','FaceColor','b');
% Normal white arrow, clipped by the surface
h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]);
t=text(-2.4,2.7,7.7,'arrow clipped by surf');
% Baseangle<90
h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50);
t2=text(3.1,.125,3.5,'local maximum');
% Baseangle<90, fill and edge colors different
h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ...
'EdgeColor','b','FaceColor','c');
t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin');
set(t3,'HorizontalAlignment','center');
% Baseangle>90, black fill
h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ...
'EdgeColor','r','FaceColor','k','LineWidth',2);
% Baseangle>90, no fill
h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ...
'EdgeColor','r','FaceColor','none','LineWidth',2);
% Stick arrow
h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16);
t4=text(-1.5,-1.65,-7.25,'global mininum');
set(t4,'HorizontalAlignment','center');
% Normal, black fill
h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k');
t5=text(-1.5,0,-7.75,'local minimum');
set(t5,'HorizontalAlignment','center');
% Gray fill, crossdir specified, 'LineStyle' --
h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ...
'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--');
% a series of normal arrows, linearly spaced, crossdir specified
h10y=(0:4)'/3;
h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ...
[-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ...
12,[],[],[],[],[0 -1 0]);
% a series of normal arrows, linearly spaced
h11x=(1:.33:2.8)';
h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ...
[h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]);
% series of magenta arrows, radially oriented, crossdir specified
h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81;
h12t=(0:11)'/6*pi;
h12 = feval(mfilename, ...
[h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ...
h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ...
h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ...
10,[],[],[],[], ...
[-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],...
'FaceColor','none','EdgeColor','m');
% series of normal arrows, tangentially oriented, crossdir specified
or13=.91; h13t=(0:.5:12)'/6*pi;
locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13];
h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6);
% arrow with no line ==> oriented downwards
h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30);
t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center');
% arrow with arrowheads at both ends
h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ...
'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25);
h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15];
function h = arrow_demo2(in)
axlim = in.axlim;
dolog = 1;
if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end;
shading('interp');
view(2);
title(['Demo of the capabilities of the ARROW function in 2-D']);
hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off;
for k=H',
set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k');
if (dolog), set(k,'YData',10.^get(k,'YData')); end;
end;
if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log');
else, axis(axlim(1:4)); end;
% Normal blue arrow
start = [axlim(1) axlim(4) axlim(6)+2];
stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2];
if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end;
h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b');
% three arrows with varying fill, width, and baseangle
start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10];
stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10];
if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end;
h2 = feval(mfilename,start,stop,24,[90;60;120],[],[0;0;4],'Ends',str2mat('both','stop','stop'));
set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]);
set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]);
h=[h1;h2];
function out = trueornan(x)
if isempty(x),
out=x;
else,
out = isnan(x);
out(~out) = x(~out);
end;
|
github
|
jfrascon/SLAM_AND_PATH_PLANNING_ALGORITHMS-master
|
compute_derivative.m
|
.m
|
SLAM_AND_PATH_PLANNING_ALGORITHMS-master/10-EXTRA_RESOURCES/MATLAB_SCRIPTS/compute_derivative.m
| 315 |
utf_8
|
c9a63637037ba13f518a21e57aa78124
|
function [jumps] = compute_derivative(scan, min_dist)
jumps = zeros(1, length(scan));
for i =2:length(scan)-1
l = scan(i-1);
r = scan(i+1);
if(l > min_dist && r > min_dist)
der = (r - l)/2.0;
jumps(i) = der;
else
jumps(i) = 0;
jumps.append(0);
end
end
end
|
github
|
albanie/mcnDatasets-master
|
getAfewImdb.m
|
.m
|
mcnDatasets-master/afew3.0/getAfewImdb.m
| 7,968 |
utf_8
|
e0c2c8792224231b31c5422ab050db1d
|
function imdb = getAfewImdb(opts, varargin)
%GETAFEWIMDB AFEW 3.0 imdb construction
% IMDB = GETAFEWIMDB(OPTS) builds an image/video database for training and
% testing on the AFEW 3.0 dataset
%
% GETAFEWIMDB(..'name', value) accepts the following options:
%
% `includeTest` :: false
% whether to include face tracks from the test set.
%
% `subsampleStride` :: 0
% If set to be greater than zero, subsamples the faces at the given
% stride.
%
% `generateWavs` :: false
% whether to extract the audio track of each video into a separate wav file.
%
% `dropTracksWithNoDets` :: false
% If true, will drop tracks with no detections (on all subsets). This
% is useful for develepmont with the provided faces, but should not be used
% in an official evaluation (since it changes the number of examples in the
% validation and test sets), or if it is used, you must apply a small
% adjustment factor to account for it. Alternatively, you can re-run a
% better face detector to ensure that every track has some detections.
% More precisely, dropping tracks reduces the validation set from 383
% samples to 381 samples (a 0.52% change).
%
% Copyright (C) 2018 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.includeTest = false ;
opts.subsampleStride = 0 ;
opts.generateWavs = true ;
opts.dropTracksWithNoDets = false ;
opts = vl_argparse(opts, varargin) ;
imdb = afewSetup(opts) ;
imdb.images.ext = 'jpg' ;
end
% ------------------------------
function imdb = afewSetup(opts)
% ------------------------------
emotions = {'Angry', 'Disgust', 'Fear', 'Happy', ...
'Sad', 'Surprise', 'Neutral'} ;
faceDir = fullfile(opts.dataDir, 'Faces') ;
subsets = {'Train', 'Val'} ;
% determine track labels - note that the same video may be used (in different
% segments) for both training and validation, so we need to collect labels
% *per-subset*.
labelMaps = {containers.Map, containers.Map} ;
if opts.includeTest
subsets{end+1} = 'Test' ; labelMaps{end+1} = containers.Map ;
end
for ii = 1:numel(subsets)
fprintf('building label map for %s..\n', subsets{ii}) ;
for jj = 1:numel(emotions)
emo = emotions{jj} ;
folder = fullfile(opts.dataDir, subsets{ii}, emo) ;
paths = zs_getImgsInDir(folder, 'avi') ;
for kk = 1:numel(paths)
[~,vidName,~] = fileparts(paths{kk}) ;
msg = 'no track should be repeated in a single subset' ;
assert(~any(ismember(labelMaps{ii}.keys(), vidName)), msg) ;
labelMaps{ii}(vidName) = jj ; % use emotion index, rather than string
end
end
end
% sanity check number of faces
facePaths = zs_getImgsInSubdirs(faceDir, 'jpg') ;
fprintf('found %d face images (expected 100048) \n', numel(facePaths)) ;
% to avoid issues with shared video names across subsets, generate a unique
% index per track
numTracks = sum(cellfun(@(x) numel(x.keys()), labelMaps)) ;
% use FER2013 ordering
relPaths = cell(1, numTracks) ;
subsetIdx = zeros(1, numTracks) ;
labels = zeros(1, numTracks) ;
vidNames = cell(1, numTracks) ;
vidPaths = cell(1, numTracks) ;
if opts.generateWavs
wavPaths = cell(1, numTracks) ;
end
counter = 1 ;
sortedVidNames = cellfun(@(x) sort(x.keys()), labelMaps, 'uni', 0) ;
for ii = 1:numel(subsets)
subset = subsets{ii} ;
sortedVids = sortedVidNames{ii} ;
for jj = 1:numel(sortedVids)
fprintf('processing %d/%d (%s)\n', jj, numel(sortedVids), subset) ;
vidName = sortedVids{jj} ;
faceDir = fullfile(opts.dataDir, 'Faces', subset, vidName) ;
paths = sort(zs_getImgsInSubdirs(faceDir, 'jpg')) ;
if opts.subsampleStride && numel(paths) > 0
% assumes that the original frames were extracted at 25 fps
% and keeps all frames that are not contiguous
[~,fnames,~] = cellfun(@fileparts, paths, 'Uni', 0) ;
frameIdx = cellfun(@str2double, fnames) ;
contig = zeros(1, numel(frameIdx)-1) ;
prev = frameIdx(1) ;
for kk = 2:numel(frameIdx)
if frameIdx(kk) == prev + 1
contig(kk-1) = 1 ;
end
prev = frameIdx(kk) ;
end
splits = find(~contig) ;
ranges = arrayfun(@(x,y) {[x+1, y]}, [0 splits], [splits numel(frameIdx)]) ;
subsampled = cellfun(@(x) {[x(1):opts.subsampleStride:x(2)]}, ranges) ;
paths = paths([subsampled{:}]) ;
end
tails = cellfun(@(x) getTail(x, 4), paths, 'Uni', 0) ;
relPaths{counter} = tails ;
subsetIdx(counter) = ii ;
labels(counter) = labelMaps{ii}(vidName) ;
% store path to video and generate wav if requested
[base, vidId] = fileparts(strrep(faceDir, 'Faces/', '')) ;
vidBasePath = fullfile(base, emotions{labels(counter)}, vidId) ;
vidPath = [vidBasePath '.avi'] ;
assert(logical(exist(vidPath, 'file')), 'avi does not exist') ;
vidPaths{counter} = vidPath ;
if opts.generateWavs
wavPaths{counter} = extractAudio(vidBasePath) ;
end
vidNames{counter} = vidName ;
counter = counter + 1 ;
end
end
% sanity check expected track numbers
assert(counter - 1 == 383 + 773, 'unexpected number of tracks') ;
imdb.tracks.vids = vidNames ;
imdb.tracks.paths = relPaths ;
imdb.tracks.vidPaths = vidPaths ;
imdb.tracks.labels = labels ;
imdb.tracks.labelsFerPlus = convertFerToFerPlus(labels, emotions) ;
imdb.tracks.set = subsetIdx ;
imdb.meta.classes = emotions ;
imdb.meta.sets = subsets ;
if opts.generateWavs
imdb.tracks.wavPaths = wavPaths ;
end
% check statistics against expected numbers
msg = 'emotion statistics do not match expected numbers' ;
assert(sum(imdb.tracks.set == 1 & imdb.tracks.labels == 1) == 133, msg) ;
if opts.dropTracksWithNoDets % remove empty frames if requested
fprintf('removing empty face tracks....') ;
keep = ~cellfun(@isempty, imdb.tracks.paths) ;
numTracks = sum(keep) ;
fnames = {'vids', 'paths', 'vidPaths', 'wavPaths', ...
'labels', 'labelsFerPlus', 'set'} ;
for ii = 1:numel(fnames)
imdb.tracks.(fnames{ii}) = imdb.tracks.(fnames{ii})(keep) ;
end
fprintf('done\n') ;
end
imdb.tracks.id = 1:numTracks ;
end
% -------------------------------------------------------------------------
function labels = convertFerToFerPlus(labels, ferEmotions)
% -------------------------------------------------------------------------
% convert FER labels to FERplus emotion indices
ferPlusEmotions = {'neutral', 'happiness', 'surprise', 'sadness', ...
'anger', 'disgust', 'fear', 'contempt'} ;
% match strings
strMap = containers.Map() ;
strMap('Happy') = 'happiness' ;
strMap('Sad') = 'sadness' ;
strMap('Neutral') = 'neutral' ;
strMap('Surprise') = 'surprise' ;
strMap('Disgust') = 'disgust' ;
strMap('Fear') = 'fear' ;
strMap('Angry') = 'anger' ;
% generate label permutation array
permuteMap = cellfun(@(x) find(strcmp(strMap(x), ferPlusEmotions)), ...
ferEmotions) ;
msg = 'contempt should not exist in original labels' ;
assert(~ismember(8, permuteMap), msg) ;
labels = permuteMap(labels) ;
end
% ---------------------------------------
function tail = getTail(path, numTokens)
% ---------------------------------------
tokens = strsplit(path, '/') ;
tail = fullfile(tokens{end-numTokens+1:end}) ;
end
% -------------------------------------------------------------------------
function destPath = extractAudio(vidBasePath)
% -------------------------------------------------------------------------
srcPath = [vidBasePath '.avi'] ;
destPath = [vidBasePath '.wav'] ;
if ~exist(destPath, 'file')
ffmpegBin = '/users/albanie/local/bin/ffmpeg' ;
cmd = sprintf('%s -y -i %s -ac 1 -f wav -vn %s', ...
ffmpegBin, srcPath, destPath) ;
status = system(cmd) ;
if status ~= 0, keyboard ; end
end
end
|
github
|
albanie/mcnDatasets-master
|
printCocoResults.m
|
.m
|
mcnDatasets-master/coco/printCocoResults.m
| 2,339 |
utf_8
|
0050c5f890a3045bd3578931851f99cf
|
function res = printCocoResults(cacheDir, varargin)
%PRINTCOCORESULTS print summary of coco results
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.expTag = '' ;
opts.orientation = 'portrait' ;
opts = vl_argparse(opts, varargin) ;
% handle either a single, or cell array of inputs
if ischar(cacheDir), cacheDirs = {cacheDir} ; else, cacheDirs = cacheDir ; end
valList = selectExp(cacheDirs, opts) ;
res = cellfun(@(x) getResult(x), valList) ;
%---------------------------------------------
function valList = selectExp(cacheDirs, opts)
%--------------------------------------------
valList = cellfun(@getResultsList, cacheDirs, 'Uni', 0) ;
if isempty(opts.expTag), valList = [valList{:}] ; return ; end % no tag, return all
keep = [] ; % otherwise, return selected
for i = 1:numel(testList)
s = testList{i} ; fname = sprintf('%s.mat', opts.expTag) ;
if ~isempty(s) && exist(fullfile(fileparts(s{1}), fname), 'file')
keep(end+1) = i ;
end
end
valList = [valList{keep}] ;
% -------------------------------------
function val = getResultsList(cacheDir)
% -------------------------------------
files = ignoreSystemFiles(dir(fullfile(cacheDir, '*.mat'))) ;
names = {files.name} ;
[set, sfx] = cellfun(@(x) getSuffixes(x), names, 'Uni', false) ;
val = fullfile(cacheDir, names(strcmp(sfx, 'results') & strcmp(set, 'val'))) ;
% ---------------------------------------------------
function [penSuffix, suffix] = getSuffixes(filename)
% ---------------------------------------------------
[~,filename,~] = fileparts(filename) ;
tokens = strsplit(filename, '-') ;
if numel(tokens) == 1
penSuffix = '' ; suffix = '' ;
else
penSuffix = tokens{end -1} ; suffix = tokens{end} ;
end
% --------------------------------------
function result = getResult(resultFile)
% --------------------------------------
[~,fname,~] = fileparts(resultFile) ;
tokens = strsplit(fname,'-') ;
model = strjoin(tokens(1:end - 2), '-') ;
result.model = model;
result.subset = tokens{end - 1} ;
data = load(resultFile) ;
fprintf('---\n%s\n---\n', model) ;
ev = CocoEval() ; ev.eval = data.results ; ev.summarize() ;
a = 1 ; m = 3 ; s = data.results.precision(:,:,:,a,m) ;
result = mean(s(s>=0)) ;
|
github
|
albanie/mcnDatasets-master
|
getCocoImdb.m
|
.m
|
mcnDatasets-master/coco/getCocoImdb.m
| 7,468 |
utf_8
|
ffd12136cf3dab046980e1204fd96fe1
|
function imdb = getCocoImdb(opts)
%GETCOCOIMDB coco imdb construction
% IMDB = GETCOCOIMDB(OPTS) builds an image database for training and
% testing on the coco dataset
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
imdb = cocoSetup(opts) ;
classIds = 1:numel(imdb.meta.classes) ;
imdb.classMap = containers.Map(imdb.meta.classes, classIds) ;
imdb.images.ext = 'jpg' ;
imdb.meta.sets = {'train', 'val', 'test'} ;
% offset categories for background
imdb.meta.classes = [{'background'} imdb.meta.classes] ;
imdb.meta.supercategories = [{'background'} imdb.meta.supercategories] ;
% ------------------------------
function imdb = cocoSetup(opts)
% ------------------------------
opts.dataDir = fullfile(opts.dataOpts.dataRoot, 'mscoco') ;
switch opts.dataOpts.year
case 2014
imdb.sets.name = {'train', 'val', 'test'} ;
imdb.sets.id = uint8([1 2 3]) ;
trainImdb = buildSet(opts, 'train', 1) ;
valImdb = buildSet(opts, 'val', 2) ;
imdb = mergeImdbs(trainImdb, valImdb) ; % merge train and val
if opts.imdbOpts.includeTest
testImdb = buildTestSet(opts, 'test', 3) ;
imdb = mergeImdbs(imdb, testImdb) ;
end
imdb.meta = trainImdb.meta ; % only one meta copy is needed
case 2015
assert(opts.imdbOpts.includeTest == true, '2015 only has test images') ;
imdb.sets.name = {'test', 'test-dev'} ; imdb.sets.id = uint8([3 4]) ;
testImdb = buildTestSet(opts, 'test', 3) ;
testDevImdb = buildTestSet(opts, 'test-dev', 4) ;
imdb = mergeImdbs(testImdb, testDevImdb) ; imdb.meta = testImdb.meta ;
case 2017
imdb.sets.name = {'train', 'val', 'test', 'test-dev'} ;
imdb.sets.id = uint8([1 2 3 4]) ;
trainImdb = buildSet(opts, 'train', 1) ;
valImdb = buildSet(opts, 'val', 2) ;
testImdb = buildTestSet(opts, 'test', 3) ;
testDevImdb = buildTestSet(opts, 'test-dev', 4) ;
imdb = mergeImdbs(trainImdb, valImdb) ;
imdb = mergeImdbs(imdb, testImdb) ;
imdb = mergeImdbs(imdb, testDevImdb) ;
imdb.meta = trainImdb.meta ; % only one meta copy is needed
otherwise, error('year %d not supported', opts.dataOpts.year) ;
end
% -------------------------------------------------------------------------
function imdb = buildSet(opts, setName, setCode)
% -------------------------------------------------------------------------
annoFile = sprintf('instances_%s%d.json', setName, opts.dataOpts.year) ;
annoPath = fullfile(opts.dataDir, 'annotations', annoFile) ;
if opts.dataOpts.year == 2017 && ismember(setName, {'train', 'val'})
archive = 'annotations_trainval2017d.zip' ; %slightly different in 2017
else
archive = sprintf('annotations_%s%d.zip', setName, opts.dataOpts.year) ;
end
archivePath = fullfile(fileparts(annoPath), archive) ;
fetch(annoPath, archivePath) ;
fprintf('reading annotations from %s \n', annoPath) ;
tmp = importdata(annoPath) ; cocoData = jsondecode(tmp{1}) ;
imdb = getImageData(opts, cocoData, setName, setCode) ;
imdb.meta.classes = {cocoData.categories.name} ;
imdb.meta.supercategories = {cocoData.categories.supercategory} ;
ids = [cocoData.annotations.image_id] ;
annos_ = arrayfun(@(x) {cocoData.annotations(ids == x)}, imdb.images.id) ;
annos = cell(1, numel(annos_)) ;
for ii = 1:numel(annos_)
fprintf('processing annotation %d/%d\n', ii, numel(annos_)) ;
anno_ = annos_{ii} ; sz = imdb.images.imageSizes{ii} ;
if ~opts.imdbOpts.conserveSpace
newAnno.id = [anno_.id] ; newAnno.area = [anno_.area] ;
newAnno.iscrowd = [anno_.iscrowd] ; newAnno.image_id = [anno_.image_id] ;
newAnno.segmentation = {anno_.segmentation} ;
end
newAnno.classes = uint8([anno_.category_id]) ;
if numel(anno_) > 0
% store normalized boxes, rather than original pixel locations
b = [anno_.bbox]' ; b = [b(:,1:2) b(:,1:2) + b(:,3:4)] ;
newAnno.boxes = single(bsxfun(@rdivide, b, [sz([2 1]) sz([2 1])])) ;
else
newAnno.boxes = [] ;
end
annos{ii} = newAnno ;
end
imdb.annotations = annos ;
% -------------------------------------------------------------------------
function imdb = buildTestSet(opts, setName, setCode)
% -------------------------------------------------------------------------
annoFile = sprintf('image_info_%s%d.json', setName, opts.dataOpts.year) ;
annoPath = fullfile(opts.dataDir, 'annotations', annoFile) ;
fprintf('reading annotations from %s \n', annoPath) ;
if contains(setName, 'dev')
archive = sprintf('image_info_test-dev%d.zip', opts.dataOpts.year) ;
else
archive = sprintf('image_info_test%d.zip', opts.dataOpts.year) ;
end
archivePath = fullfile(fileparts(annoPath), archive) ;
fetch(annoPath, archivePath) ;
fprintf('reading annotations from %s \n', annoPath) ;
tmp = importdata(annoPath) ; cocoData = jsondecode(tmp{1}) ;
pos = regexp(setName, '-dev$') ; % trim -dev suffix if present
if ~isempty(pos), setName = setName(1:pos-1) ; end
imdb = getImageData(opts, cocoData, setName, setCode) ;
imdb.meta.classes = {cocoData.categories.name} ;
imdb.meta.supercategories = {cocoData.categories.supercategory} ;
% -------------------------------------------------------------------------
function imdb = getImageData(opts, cocoData, setName, setCode)
% -------------------------------------------------------------------------
imdb.images.name = {cocoData.images.file_name} ;
imdb.images.id = [cocoData.images.id] ;
imdb.images.set = ones(1, numel(imdb.images.name)) * setCode ;
height = [cocoData.images.height] ; width = [cocoData.images.width] ;
imdb.images.imageSizes = arrayfun(@(x,y) {[x, y]}, height, width) ;
imFolder = sprintf('%s%d', setName, opts.dataOpts.year) ;
imdb.paths.image = esc(fullfile(opts.dataDir, 'images', imFolder, '%s')) ;
paths = repmat(imdb.paths.image, numel(imdb.images.name), 1) ;
imdb.images.paths = arrayfun(@(x) {paths(x,:)}, 1:size(paths,1)) ;
% --------------------------------------
function imdb = mergeImdbs(imdb1, imdb2)
% --------------------------------------
imdb.images.id = [imdb1.images.id imdb2.images.id] ;
imdb.images.set = [imdb1.images.set imdb2.images.set] ;
imdb.images.name = [imdb1.images.name imdb2.images.name] ;
imdb.images.imageSizes = [imdb1.images.imageSizes imdb2.images.imageSizes] ;
imdb.images.paths = horzcat(imdb1.images.paths, imdb2.images.paths) ;
if isfield(imdb1, 'annotations') && isfield(imdb2, 'annotations')
imdb.annotations = horzcat(imdb1.annotations, imdb2.annotations) ;
elseif isfield(imdb1, 'annotations')
imdb.annotations = imdb1.annotations ;
elseif isfield(imdb2, 'annotations')
imdb.annotations = imdb2.annotations ;
else
% pass
end
% -----------------------------------
function fetch(annoPath, archivePath)
% -----------------------------------
% Fetch data from coco server if required
if ~exist(annoPath, 'file')
if ~exist(archivePath, 'file')
base = 'http://images.cocodataset.org/annotations' ;
url = fullfile(base, archive) ;
fprintf('downloading %s from %s\n', archive, url) ;
websave(archivePath, url) ;
end
unzip(archivePath,fileparts(fileparts(archivePath))) ;
end
% -------------------------------------------------------------------------
function str=esc(str)
% -------------------------------------------------------------------------
str = strrep(str, '\', '\\') ;
|
github
|
albanie/mcnDatasets-master
|
getEnterfaceImdb.m
|
.m
|
mcnDatasets-master/enterface/getEnterfaceImdb.m
| 6,163 |
utf_8
|
5ea10b5523c5a127fa92868c620706d4
|
function imdb = getEnterfaceImdb(opts, varargin)
%GETENTERFACE Enterface imdb construction
% IMDB = GETENTERFACE(OPTS) builds an image/video database for training and
% testing on the Enterface dataset
%
% Copyright (C) 2018 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.generateWavs = true ;
opts = vl_argparse(opts, varargin) ;
imdb = enterfaceSetup(opts) ;
imdb.images.ext = 'jpg' ;
end
% ------------------------------
function imdb = enterfaceSetup(opts)
% ------------------------------
emotions = {'Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise'} ;
% notation used in folders
emoKeys = {'anger', 'disgust', 'fear', 'happiness', 'sadness', 'surprise'} ;
faceDir = fullfile(opts.dataDir, 'faces') ;
subsets = {'train', 'val'} ;
trainIds = 1:30 ; valIds = 31:44 ;
trainSpeakers = arrayfun(@(x) {sprintf('subject-%d', x)}, trainIds) ;
valSpeakers = arrayfun(@(x) {sprintf('subject-%d', x)}, valIds) ;
speakers = {trainSpeakers, valSpeakers} ;
facePaths = zs_getImgsInSubdirs(faceDir, 'jpg') ;
allTracks = cellfun(@fileparts, facePaths, 'uni', 0) ;
numTracks = numel(unique(allTracks)) ;
fprintf('found %d tracks (expected 1293) \n', numTracks) ;
% use FER2013 ordering
labels = zeros(1, numTracks) ;
relPaths = cell(1, numTracks) ;
vidNames = cell(1, numTracks) ;
spIds = zeros(1, numTracks) ;
subsetIdx = zeros(1, numTracks) ;
vidPaths = cell(1, numTracks) ;
if opts.generateWavs
wavPaths = cell(1, numTracks) ;
end
% determine track labels
counter = 1 ;
for ii = 1:numel(subsets)
subset = subsets{ii} ;
subsetSpeakers = speakers{ii} ;
for jj = 1:numel(subsetSpeakers)
sp = subsetSpeakers{jj} ;
emotionDirs = zs_getSubdirs(fullfile(faceDir, sp)) ;
for kk = 1:numel(emotionDirs)
sentenceDirs = zs_getSubdirs(emotionDirs{kk}) ;
% The folder structure of the dataset is not consistent, so we
% flatten sentence dirs that contain extra subfolders to ensure
% an even depth
if any(~ismember(sentenceDirs, allTracks))
subdirs = cellfun(@zs_getSubdirs, sentenceDirs, 'uni', 0) ;
sentenceDirs = [subdirs{:}] ; depth = 6 ;
else
depth = 5 ;
end
msg = 'incorrect track selection' ;
assert(all(ismember(sentenceDirs, allTracks)), msg) ;
for ll = 1:numel(sentenceDirs)
fprintf('processing %d/%d (%s)\n', counter, numTracks, subset) ;
[~,vidName,~] = fileparts(sentenceDirs{ll}) ;
switch depth
case 5
[~,emoName] = fileparts(fileparts(sentenceDirs{ll})) ;
case 6
[~,emoName] = fileparts(fileparts(fileparts(sentenceDirs{ll}))) ;
otherwise, error('unexpected folder depth %d\n', depth) ;
end
label = find(strcmp(emoKeys, emoName)) ;
assert(numel(label) == 1, 'could not find appropriate label') ;
paths = zs_getImgsInSubdirs(sentenceDirs{ll}, 'jpg') ;
tails = cellfun(@(x) getTail(x, depth), paths, 'Uni', 0) ;
relPaths{counter} = tails ;
subsetIdx(counter) = ii ;
labels(counter) = label ;
vidNames{counter} = vidName ;
% store path to video and generate wav if requested
vidBasePath = strrep(sentenceDirs{ll}, 'faces', 'raw') ;
vidPath = [vidBasePath '.avi'] ;
assert(logical(exist(vidPath, 'file')), 'avi does not exist') ;
vidPaths{counter} = vidPath ;
if opts.generateWavs
wavPaths{counter} = extractAudio(vidBasePath) ;
end
spIds(counter) = find(strcmp(sp, [speakers{:}])) ;
counter = counter + 1 ;
end
end
end
end
% sanity check expected track numbers
assert(counter == 1294, 'unexpected number of tracks') ;
imdb.tracks.vids = vidNames ;
imdb.tracks.vidPaths = vidPaths ;
imdb.tracks.paths = relPaths ;
imdb.tracks.labels = labels ;
imdb.tracks.labelsFerPlus = convertFerToFerPlus(labels, emotions) ;
imdb.tracks.set = subsetIdx ;
imdb.meta.classes = emotions ;
imdb.meta.sets = subsets ;
if opts.generateWavs
imdb.tracks.wavPaths = wavPaths ;
end
% check statistics against expected numbers
msg = 'emotion statistics do not match expected numbers' ;
assert(sum(imdb.tracks.set == 1 & imdb.tracks.labels == 1) == 146, msg) ;
imdb.tracks.id = 1:numTracks ;
end
% -------------------------------------------------------------------------
function destPath = extractAudio(vidBasePath)
% -------------------------------------------------------------------------
srcPath = [vidBasePath '.avi'] ;
destPath = [vidBasePath '.wav'] ;
if ~exist(destPath, 'file')
ffmpegBin = '/users/albanie/local/bin/ffmpeg' ;
cmd = sprintf('%s -i %s -vn -acodec copy %s', ...
ffmpegBin, srcPath, destPath) ;
status = system(cmd) ;
if status ~= 0, keyboard ; end
end
end
% -------------------------------------------------------------------------
function labels = convertFerToFerPlus(labels, ferEmotions)
% -------------------------------------------------------------------------
% convert FER labels to FERplus emotion indices
ferPlusEmotions = {'neutral', 'happiness', 'surprise', 'sadness', ...
'anger', 'disgust', 'fear', 'contempt'} ;
% match strings
strMap = containers.Map() ;
strMap('Happy') = 'happiness' ;
strMap('Sad') = 'sadness' ;
strMap('Neutral') = 'neutral' ;
strMap('Surprise') = 'surprise' ;
strMap('Disgust') = 'disgust' ;
strMap('Fear') = 'fear' ;
strMap('Angry') = 'anger' ;
% generate label permutation array
permuteMap = cellfun(@(x) find(strcmp(strMap(x), ferPlusEmotions)), ...
ferEmotions) ;
msg = 'contempt should not exist in original labels' ;
assert(~ismember(8, permuteMap), msg) ;
labels = permuteMap(labels) ;
end
% ---------------------------------------
function tail = getTail(path, numTokens)
% ---------------------------------------
tokens = strsplit(path, '/') ;
tail = fullfile(tokens{end-numTokens+1:end}) ;
end
|
github
|
albanie/mcnDatasets-master
|
getSfewImdb.m
|
.m
|
mcnDatasets-master/sfew/getSfewImdb.m
| 2,881 |
utf_8
|
92f19b9656b9963c9bbbfb9d468dc823
|
function imdb = getSfewImdb(dataDir)
%GETSFEWIMDB Returns imdb (the image database)
% IMDB = GETSFEWIMDB(DATADIR) loads the SFEW image datbase. This
% functions assumes that DATADIR is directory containing a collection
% of images in png format arranged in three folders 'Train', 'Val'
% and 'Test'. 'Train' and 'Val' are assumed to contain further subfolders,
% each with the name of an emotion. 'Test' should contain an unlabelled
% collection of png files (the labels for the test set are not publicly
% available).
%
% Copyright (C) 2016 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
trainIms = zs_getImgsInSubdirs(fullfile(dataDir, 'Train'), 'png') ;
valIms = zs_getImgsInSubdirs(fullfile(dataDir, 'Val'), 'png') ;
testIms = zs_getImgsInSubdirs(fullfile(dataDir, 'Test'), 'png') ;
[trainData, trainLabels] = preprocessSFEW(trainIms, true) ;
[valData, valLabels] = preprocessSFEW(valIms, true) ;
testData = preprocessSFEW(testIms, false) ;
trainSet = ones(1, size(trainData, 4)) ;
valSet = 2 * ones(1, size(valData, 4)) ;
testSet = 3 * ones(1, size(testData, 4)) ;
imdb.images.data = cat(4, trainData, valData, testData) ;
imdb.images.labels = cat(2, trainLabels, valLabels) ;
imdb.images.set = [trainSet valSet testSet] ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = {'anger', 'disgust', 'fear', ...
'happiness', 'sadness', 'surprise', 'neutral'} ;
% --------------------------------------------------------------------
function [data, labels] = preprocessSFEW(imList, extractLabels)
% --------------------------------------------------------------------
%PREPROCESSSFEW - preprocess images stored in the SFEW layout
% [DATA, LABELS] = PREPROCESSSFEW(IMLIST, EXTRACTLABELS) loads the
% the data from a cell array of paths to image files. If EXTRACTLABELS
% is set to TRUE, these image paths should each have the form:
% SOME_DIR/EMOTION/IMG_NAME.PNG
% The EMOTION subfolder will be used to produce a label for each image.
% Alternatively, if EXTRACTLABELS is FALSE, the image paths should have the
% form:
% SOME_DIR/IMG_NAME.PNG
%
% The function returns 96 x 96 x 3 x N data array containing the images. If
% EXTRACTLABELS is TRUE, it will also return an Nx1 array of emotion labels.
rawData = cellfun(@(x) {single(imread(x))}, imList) ;
data = cat(4, rawData{:}) ;
if extractLabels, labels = cellfun(@extractEmotion, imList)' ; end
% -----------------------------------------
function emotionLabel = extractEmotion(path)
% -----------------------------------------
pathElems = strsplit(path, '/') ;
emotionKey = pathElems{end - 1} ;
keys = {'Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral'} ;
values = [1, 2, 3, 4, 5, 6. 7] ;
emotionMap = containers.Map(keys, values) ;
emotionLabel = emotionMap(emotionKey) ;
|
github
|
albanie/mcnDatasets-master
|
getFerPlusImdb.m
|
.m
|
mcnDatasets-master/FER2013+/getFerPlusImdb.m
| 6,404 |
utf_8
|
03a434a2ba9a28fb6cc3b6776e55d443
|
function imdb = getFerPlusImdb(dataDir, varargin)
%GETFERPLUSIMDB Returns imdb (the image database)
% IMDB = GETFERPLUSIMDB(DATADIR, VARARGIN) loads the FER+ image datbase.
%
% GETFERPLUSIMDB(..'name', value) accepts the following options:
%
% `dataType` :: 'CNTK'
% This option which labels and images are included.
% There are three options: "clean", which aggressively cleans the dataset,
% "CNTK", which aims to follow the cleaning procedure described in the
% Microsoft paper (link to the github page below), and "full", which does
% not apply any form of cleaning.
%
% Uses "plus" labels from: https://github.com/Microsoft/FERPlus
% See the paper for more details: https://arxiv.org/abs/1608.01041
%
% Copyright (C) 2018 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.dataType = 'CNTK' ;
opts = vl_argparse(opts, varargin) ;
imdb = getFerImdb(dataDir) ;
imdb = updateLabels(imdb, dataDir, opts.dataType) ;
% --------------------------------------------------------------------
function imdb = updateLabels(imdb, dataDir, dataType)
% --------------------------------------------------------------------
plusLabelPath = fullfile(dataDir, 'fer2013new.csv') ;
if ~exist(plusLabelPath, 'file')
fetchDataset('fer2013+', plusLabelPath) ;
end
csvData = importdata(plusLabelPath) ;
data = csvData.data ;
header = csvData.textdata(1,:) ; emotions = header(3:10) ;
subsets = csvData.textdata(2:end,1) ; % skip header
switch dataType
case 'clean'
% use stronger labels to remove non-faces from the dataset (where the majority
% of annotators agree that the image does not contain a face). We
% also drop images where the majority vote by the annotators label is
% "unknown".
[~,cls] = max(data, [], 2) ;
dropUnsure = sum(ismember(cls, 9)) ;
dropNF = sum(ismember(cls, 10)) ;
fprintf('dropped: %d non-face labels \n', dropNF) ;
fprintf('dropped: %d unsure labels \n', dropUnsure) ;
drop = find(ismember(cls, [9 10])) ;
data(drop,:) = [] ;
subsets(drop,:) = [] ;
imdb.images.data(:,:,:,drop) = [] ;
imdb.images.labels(drop) = [] ;
imdb.images.set(drop) = [] ;
case 'CNTK' % try to replicate the Microsoft cleaning process
origData = data ;
% remove emotions with a single vote (outlier removal)
outliers = (data <= 1) ;
data(outliers) = 0 ;
dropped = 1 - sum(data(:))/sum(origData(:)) ;
fprintf('dropped %.1f%% of votes as outliers\n', 100 * dropped) ;
numVotes = sum(data, 2) ; % per row
% following cntk processing - there are three reasons to drop examples:
% (1) If the majority votes for either "unknown-face" or "not-face"
% (2) If more than three votes share the maximum voting value
% (3) If the max votes do not account for more than half of the votes
toDrop = zeros(size(data,1), 1) ;
for ii = 1:size(data,1)
fprintf('processing %d/%d\n', ii, size(data,1)) ;
maxVote = max(data(ii,:)) ;
maxVoteEmos = find(data(ii,:) == maxVote) ;
drop = any(ismember(maxVoteEmos, [9 10])) ; % reason (1)
numMaxVotes = numel(maxVoteEmos) ;
drop = drop || logical(numMaxVotes >= 3) ; % reason (2)
drop = drop || logical((numMaxVotes * maxVote) <= 0.5 * numVotes(ii)) ; % reason (3)
toDrop(ii) = drop ;
end
toDrop = logical(toDrop) ;
data(toDrop,:) = [] ;
subsets(toDrop,:) = [] ;
imdb.images.data(:,:,:,toDrop) = [] ;
imdb.images.labels(toDrop) = [] ;
imdb.images.set(toDrop) = [] ;
case 'full' % do nothing
otherwise, error('unknown data type: %s\n', dataType) ;
end
imdb.images.oldLabels = imdb.images.labels ; % store FER original labels
imdb.images = rmfield(imdb.images, 'labels') ; % remove to avoid confusion
% use majority labels, and store votes
[~,cls] = max(data, [], 2) ;
imdb.images.votes = data ;
imdb.images.hardLabels = cls' ;
% sanity check the subset markers
trainCorrect = all(ismember(subsets(imdb.images.set == 1), {'Training'})) ;
valCorrect = all(ismember(subsets(imdb.images.set == 2), {'PublicTest'})) ;
testCorrect = all(ismember(subsets(imdb.images.set == 3), {'PrivateTest'})) ;
assert(trainCorrect, 'train subset does not match') ;
assert(valCorrect, 'val subset does not match') ;
assert(testCorrect, 'test subset does not match') ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = emotions ;
% -----------------------------------------
function fetchDataset(datasetName, dataPath)
% -----------------------------------------
waiting = true ;
prompt = sprintf(strcat('%s was not found at %s\nWould you like to ', ...
' download it from THE INTERNET (y/n)?\n'), datasetName, dataPath) ;
while waiting
str = input(prompt,'s') ;
switch str
case 'y'
dataDir = fileparts(dataPath) ;
if ~exist(dataDir, 'dir'), mkdir(dataDir) ; end
fprintf(sprintf('Downloading %s ... \n', datasetName)) ;
baseUrl = 'http://www.robots.ox.ac.uk/~albanie/data/mirrors' ;
url = sprintf('%s/%s.zip', baseUrl, datasetName) ;
% write the tar file to the same directory and unpack
archivePath = fullfile(dataDir, sprintf('%s.zip', datasetName)) ;
urlwrite(url, archivePath) ;
% matlab builtin untar keeps breaking, so use cmd line
cmd = sprintf('unzip %s -d %s', archivePath, dataDir) ;
status = system(cmd) ;
if status > 0
error(['automatic extraction failed, it will be necessary to '...
'set up the dataset manually\n']) ;
end
% move data up a directory
srcPath = fullfile(dataDir, 'fer2013+/fer2013new.csv') ;
destPath = fullfile(dataDir, 'fer2013new.csv') ;
status = movefile(srcPath, destPath) ;
if status ~= 1 % note that MATLAB uses 1 for a success :(
error(['directory layout failed, it will be necessary to '...
'set up the dataset manually\n']) ;
end
delete(archivePath) ; % clean up
fprintf('successfully extracted the dataset!\n') ;
return ;
case 'n', throw(exception) ;
otherwise, fprintf('input %s not recognised, please use `y/n`\n', str) ;
end
end
|
github
|
albanie/mcnDatasets-master
|
getFerImdb.m
|
.m
|
mcnDatasets-master/FER2013/getFerImdb.m
| 3,726 |
utf_8
|
c07a753c36c98f7af25539f20f2c75d4
|
function imdb = getFerImdb(dataDir)
%GETFERIMDB Returns imdb (the image database)
% IMDB = GETFERIMDB(DATADIR) loads the FER image datbase. This functions
% assumes that the raw data `fer2013.csv` has been downloaded and placed
% in DATADIR.
%
% Copyright (C) 2018 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
rawFaceDims = [48 48 1] ;
dataPath = fullfile(dataDir, 'fer2013.csv') ;
if ~exist(dataPath, 'file')
fetchDataset('fer2013', dataPath) ;
end
csvData = importdata(dataPath) ;
% parse data
csvData = csvData(2:end) ; % skip header
numRows = numel(csvData) ; % skip header
labels = zeros(1, numRows) ;
subset = zeros(1, numRows) ;
imData = zeros(48, 48, 1, numRows, 'single') ;
parfor ii = 1:numRows
fprintf('extracting example %d/%d\n', ii, numRows) ;
tokens = strsplit(csvData{ii}, ',') ;
labels(ii) = str2double(tokens{1}) + 1 ; % labels need to be one-indexed
% NOTE: we could use a switch/otherwise statement here, but the matlab
% code analyser sucks and throws a warning if it is used instead of
% if/else within a parfor, so we use the following hack:
setIdx = 0 ;
if strcmp(tokens{3}, 'Training')
setIdx = 1 ;
elseif strcmp(tokens{3}, 'PublicTest')
setIdx = 2 ;
elseif strcmp(tokens{3}, 'PrivateTest')
setIdx = 3 ;
end
if ~ismember(setIdx, [1 2 3]), error('setIdx is unset') ; end
subset(ii) = setIdx ;
pixels = single(cellfun(@str2double, strsplit(tokens{2}, ' '))) ;
face = reshape(pixels, rawFaceDims)' ;
imData(:,:,:,ii) = face ;
end
imdb.images.data = imData ;
imdb.images.labels = labels ;
imdb.images.set = subset ;
imdb.meta.sets = {'train', 'val', 'test'} ;
imdb.meta.classes = {'anger', 'disgust', 'fear', ...
'happiness', 'sadness', 'surprise', 'neutral'} ;
% -----------------------------------------
function fetchDataset(datasetName, dataPath)
% -----------------------------------------
waiting = true ;
prompt = sprintf(strcat('%s was not found at %s\nWould you like to ', ...
' download it from THE INTERNET (y/n)?\n'), datasetName, dataPath) ;
while waiting
str = input(prompt,'s') ;
switch str
case 'y'
dataDir = fileparts(dataPath) ;
if ~exist(dataDir, 'dir'), mkdir(dataDir) ; end
fprintf(sprintf('Downloading %s ... \n', datasetName)) ;
baseUrl = 'http://www.robots.ox.ac.uk/~albanie/data/mirrors' ;
url = sprintf('%s/%s.tar', baseUrl, datasetName) ;
% write the tar file to the same directory and unpack
archivePath = fullfile(dataDir, sprintf('%s.tar', datasetName)) ;
urlwrite(url, archivePath) ;
% matlab builtin untar keeps breaking, so use cmd line
cmd = sprintf('tar -xvf %s -C %s', archivePath, dataDir) ;
status = system(cmd) ;
if status > 0
error(['automatic extraction failed, it will be necessary to '...
'set up the dataset manually\n']) ;
end
% move data up a directory
srcPath = fullfile(dataDir, 'fer2013/fer2013.csv') ;
destPath = fullfile(dataDir, 'fer2013.csv') ;
status = movefile(srcPath, destPath) ;
if status ~= 1 % note that MATLAB uses 1 for a success :(
error(['directory layout failed, it will be necessary to '...
'set up the dataset manually\n']) ;
end
delete(archivePath) ; % clean up
fprintf('successfully extracted the dataset!\n') ;
return ;
case 'n', throw(exception) ;
otherwise, fprintf('input %s not recognised, please use `y/n`\n', str) ;
end
end
|
github
|
albanie/mcnDatasets-master
|
getCombinedPascalImdb.m
|
.m
|
mcnDatasets-master/pascal/getCombinedPascalImdb.m
| 6,155 |
utf_8
|
5438bfc85dc18199302018cc40fe2863
|
function imdb = getCombinedPascalImdb(opts, varargin)
% GETCOMBINEDPASCALIMDB - load Pascal IMDB file
% IMDB = GETCOMBINEDPASCALIMDB(OPTS) constructs an IMDB for the
% Pascal VOC data spanning the 2007 and 2012 dataset (commonly referred
% to as the "0712" dataset in object detection.
%
% GETCOMBINEDPASCALIMDBPASCALIMDB(..., 'option', value, ...) accepts
% the following options:
%
% `excludeDifficult`:: false
% Remove objects labelled as "difficult" from the VOC training annotations.
%
% `includeSegmentation`:: true
% Include segmentation labels for the subset of labeled images.
%
% `includeDevkit`:: true
% Include development kit code released with the challenge.
%
% `includeDetection`:: true
% Include detection labels for the subset of labeled images.
%
% Inspiration ancestry for code:
% A.Vedaldi -> R.Girshick -> S.Albanie
%
% Copyright (C) 2017 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.includeDevkit = true ;
opts.includeDetection = true ;
opts.excludeDifficult = false ;
opts.includeSegmentation = true ;
opts.vocAdditionalSegmentations = true ;
opts = vl_argparse(opts, varargin) ;
% Although the 2012 data can be used during training, only
% the 2007 test data is used for evaluation
opts.VOCRoot = fullfile(opts.dataOpts.dataRoot, 'VOCdevkit2007' ) ;
opts.devkitCode = fullfile(opts.VOCRoot, 'VOCcode') ;
imdb = loadImdb(opts) ;
opts.pascalOpts = loadPascalOpts(opts) ;
% add meta information (inlcuding background class)
imdb.meta.classes = [{'background'} opts.pascalOpts.classes'] ;
classIds = 1:numel(imdb.meta.classes) ;
imdb.classMap = containers.Map(imdb.meta.classes, classIds) ;
imdb.images.ext = 'jpg' ;
imdb.meta.sets = {'train', 'val', 'test'} ;
%-----------------------------------------
function pascalOpts = loadPascalOpts(opts)
%-----------------------------------------
% LOADPASCALOPTS Load the pascal VOC database options
%
% NOTE: The Pascal VOC dataset has a number of directories
% and attributes. The paths to these directories are
% set using the VOCdevkit code. The VOCdevkit initialization
% code assumes it is being run from the devkit root folder,
% so we make a note of our current directory, change to the
% devkit root, initialize the pascal options and then change
% back into our original directory
% check the existence of the required folders
assert(logical(exist(opts.VOCRoot, 'dir')), 'VOC root directory not found') ;
assert(logical(exist(opts.devkitCode, 'dir')), 'devkit code not found') ;
currentDir = pwd ; cd(opts.VOCRoot) ; addpath(opts.devkitCode) ;
VOCinit ; % VOCinit loads database options into a variable called VOCopts
pascalOpts = VOCopts ; cd(currentDir) ;
%-----------------------------
function imdb = loadImdb(opts)
%-----------------------------
dataDir07 = fullfile(opts.dataOpts.dataRoot, 'VOCdevkit2007', '2007') ;
imdb07 = getPascalYearImdb(dataDir07, 07, ...
'includeDevkit', opts.includeDevkit, ...
'includeTest', true, ...
'includeDetection', opts.includeDetection, ...
'includeSegmentation', opts.includeSegmentation) ;
dataDir12 = fullfile(opts.dataOpts.dataRoot, 'VOCdevkit2012', '2012') ;
imdb12 = getPascalYearImdb(dataDir12, 12 , ...
'includeTest', false, ... % download manually
'includeDevkit', opts.includeDevkit, ...
'includeDetection', opts.includeDetection, ...
'includeSegmentation', opts.includeSegmentation, ...
'vocAdditionalSegmentations', opts.vocAdditionalSegmentations) ;
imdb = combineImdbs(imdb07, imdb12, opts) ;
% ------------------------------------------------
function imdb = combineImdbs(imdb07, imdb12, opts)
% ------------------------------------------------
imdb.images.name = [imdb07.images.name, imdb12.images.name] ;
imdb.images.set = [imdb07.images.set imdb12.images.set] ;
imageSizes = [imdb07.images.size, imdb12.images.size] ;
imdb.images.year = [ones(1,numel(imdb07.images.name)) * 2007 ...
ones(1,numel(imdb12.images.name)) * 2012] ;
imdb.images.classification = [imdb07.images.classification ...
imdb12.images.classification] ;
imdb.images.segmentation = [imdb07.images.segmentation ...
imdb12.images.segmentation] ;
% add individual image paths for backward compatibility
paths = vertcat(repmat(imdb07.paths.image, numel(imdb07.images.name), 1), ...
repmat(imdb12.paths.image, numel(imdb12.images.name), 1)) ;
imdb.images.paths = arrayfun(@(x) {paths(x,:)}, 1:size(paths, 1)) ;
% also include the paths from both years to handle optional extra segmentations
imdb.paths2007 = imdb07.paths ;
imdb.paths2012 = imdb12.paths ;
% for consistency, store in Height-Width order
imdb.images.imageSizes = arrayfun(@(x) {imageSizes([2 1],x)'}, ...
1:size(imageSizes, 2)) ;
if opts.includeDetection
annot07 = loadAnnotations(imdb07, opts) ;
annot12 = loadAnnotations(imdb12, opts) ;
imdb.annotations = horzcat(annot07, annot12) ;
end
% ------------------------------------------------
function annotations = loadAnnotations(imdb, opts)
% ------------------------------------------------
annotations = cell(1, numel(imdb.images.name)) ;
for ii = 1:numel(imdb.images.name)
match = find(imdb.objects.image == ii) ;
if opts.excludeDifficult
keep = ~(imdb.objects.difficult(match)) ;
else
keep = 1:numel(match) ;
end
match = match(keep) ;
boxes = imdb.objects.box(:,match) ;
classes = imdb.objects.class(match) ;
% normalize annotation
imSize = repmat(imdb.images.size(:, ii)', [1 2]) ;
gt.boxes = bsxfun(@rdivide, boxes', single(imSize)) ;
gt.classes = classes + 1 ; % add offset for background
assert(all(2 <= gt.classes) && all(gt.classes <= 21), ...
'pascal class labels do not lie in the expected range') ;
annotations{ii} = gt ; fprintf('Loading annotaton %d \n', ii) ;
end
|
github
|
albanie/mcnDatasets-master
|
vocSetup.m
|
.m
|
mcnDatasets-master/pascal/vocSetup.m
| 11,730 |
utf_8
|
cf914b40f0b77ff3859f66c2e2563a3e
|
function imdb = vocSetup(varargin)
% VOCSETUP download and setup data from the Pascal VOC challenge
%
% This script was sourced from the Matconvnet-fcn project, written by
% Sebastien Erhardt and Andrea Vedaldi:
% https://github.com/vlfeat/matconvnet-fcn
opts.edition = '07' ;
opts.dataDir = fullfile('data','voc07') ;
opts.archiveDir = fullfile('data','archives') ;
opts.includeDetection = false ;
opts.includeSegmentation = false ;
opts.includeTest = false ;
opts.includeDevkit = false ;
opts = vl_argparse(opts, varargin) ;
% Download data
if ~exist(fullfile(opts.dataDir,'Annotations'), 'dir'), download(opts) ; end
% Source images and classes
imdb.paths.image = esc(fullfile(opts.dataDir, 'JPEGImages', '%s.jpg')) ;
imdb.sets.id = uint8([1 2 3]) ;
imdb.sets.name = {'train', 'val', 'test'} ;
imdb.classes.id = uint8(1:20) ;
imdb.classes.name = {...
'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', ...
'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', ...
'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'} ;
imdb.classes.images = cell(1,20) ;
imdb.images.id = [] ;
imdb.images.name = {} ;
imdb.images.set = [] ;
index = containers.Map() ;
[imdb, index] = addImageSet(opts, imdb, index, 'train', 1) ;
[imdb, index] = addImageSet(opts, imdb, index, 'val', 2) ;
if opts.includeTest, [imdb, index] = addImageSet(opts, imdb, index, 'test', 3) ; end
% Source segmentations
if opts.includeSegmentation
n = numel(imdb.images.id) ;
imdb.paths.objectSegmentation = esc(fullfile(opts.dataDir, ...
'SegmentationObject', '%s.png')) ;
imdb.paths.classSegmentation = esc(fullfile(opts.dataDir, ...
'SegmentationClass', '%s.png')) ;
imdb.images.segmentation = false(1, n) ;
[imdb, index] = addSegmentationSet(opts, imdb, index, 'train', 1) ;
[imdb, index] = addSegmentationSet(opts, imdb, index, 'val', 2) ;
if opts.includeTest
[imdb, ~] = addSegmentationSet(opts, imdb, index, 'test', 3) ;
end
end
% Compress data types
imdb.images.id = uint32(imdb.images.id) ;
imdb.images.set = uint8(imdb.images.set) ;
for i=1:20
imdb.classes.images{i} = uint32(imdb.classes.images{i}) ;
end
% Source detections
if opts.includeDetection
imdb.aspects.id = uint8(1:5) ;
imdb.aspects.name = {'front', 'rear', 'left', 'right', 'misc'} ;
imdb = addDetections(opts, imdb) ;
end
% Check images on disk and get their size
imdb = getImageSizes(imdb) ;
% -------------------------------------------------------------------------
function download(opts)
% -------------------------------------------------------------------------
baseUrl = 'http://host.robots.ox.ac.uk:8080' ;
switch opts.edition
case '07'
endpoint = sprintf('%s/pascal/VOC/voc2007', baseUrl) ;
url = sprintf('%s/VOCtrainval_06-Nov-2007.tar', endpoint) ;
testUrl = sprintf('%s/VOCtest_06-Nov-2007.tar', endpoint) ;
devkitUrl = sprintf('%s/VOCdevkit_08-Jun-2007.tar', endpoint) ;
case '08'
url='' ;
case '09'
url='' ;
case '10'
url=sprintf('%s/pascal_trainval/VOCtrainval_03-May-2010.tar', baseUrl) ;
case '11'
url=sprintf('%s/pascal_trainval/VOCtrainval_25-May-2011.tar', baseUrl) ;
case '12'
base12 = sprintf('%s/pascal/VOC', baseUrl) ; % different for 2012
url = sprintf('%s/voc2012/VOCtrainval_11-May-2012.tar', base12) ;
devkitUrl = sprintf('%s/voc2012/VOCdevkit_18-May-2011.tar', base12) ;
end
trainvalData = sprintf('VOC20%strainval.tar', opts.edition) ;
testData = sprintf('VOC20%stest.tar', opts.edition) ;
devkit = sprintf('VOC20%sdevkit.tar', opts.edition) ;
if ~exist(opts.archiveDir, 'dir'), mkdir(opts.archiveDir) ; end
archivePath=fullfile(opts.archiveDir, trainvalData) ;
if ~exist(archivePath, 'file')
fprintf('%s: downloading %s to %s\n', mfilename, url, archivePath) ;
urlwrite(url, archivePath) ;
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, opts.dataDir) ;
switch opts.edition
case '11' % Decompresses in TrainVal/VOCdevkit, Test/VOCdevkit (sigh!)
movefile(fullfile(opts.dataDir, 'TrainVal'), fullfile(opts.dataDir,'Test')) ;
otherwise % Decomporesses directly in VOCdevkit
end
if opts.includeDevkit
devkitDir = fileparts(opts.dataDir) ;
archivePath = fullfile(opts.archiveDir, devkit) ;
if ~exist(archivePath, 'file')
fprintf('%s: downloading %s to %s\n', mfilename, devkitUrl, archivePath) ;
urlwrite(devkitUrl, archivePath) ;
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, devkitDir) ;
movefile(fullfile(devkitDir, 'VOCdevkit', '*'), devkitDir) ;
rmdir(fullfile(devkitDir, 'VOCdevkit')) ;
end
if opts.includeTest
archivePath = fullfile(opts.archiveDir, testData) ;
if ~exist(archivePath, 'file')
try
fprintf('attempting download %s to %s\n', testUrl, archivePath) ;
urlwrite(testUrl, archivePath) ;
catch
error(['Cannot download the test data automatically. ', ...
'Please download the file %s manually from the PASCAL test ', ...
'server.'], archivePath) ;
end
end
fprintf('%s: decompressing and rearranging %s\n', mfilename, archivePath) ;
untar(archivePath, opts.dataDir) ;
end
switch opts.edition
case '11'
movefile(fullfile(opts.dataDir, 'Test', 'VOCdevkit', ...
sprintf('VOC20%s',opts.edition), '*'), opts.dataDir) ;
rmdir(fullfile(opts.dataDir, 'Test'),'s') ;
otherwise
movefile(fullfile(opts.dataDir, 'VOCdevkit', ...
sprintf('VOC20%s',opts.edition), '*'), opts.dataDir) ;
rmdir(fullfile(opts.dataDir, 'VOCdevkit'),'s') ;
end
% -------------------------------------------------------------------------
function [imdb, index] = addImageSet(opts, imdb, index, setName, setCode)
% -------------------------------------------------------------------------
j = length(imdb.images.id) ;
for ci = 1:length(imdb.classes.name)
className = imdb.classes.name{ci} ;
annoPath = fullfile(opts.dataDir, 'ImageSets', 'Main', ...
[className '_' setName '.txt']) ;
fprintf('%s: reading %s\n', mfilename, annoPath) ;
[names,labels] = textread(annoPath, '%s %f') ; %#ok
for i=1:length(names)
if ~index.isKey(names{i})
j = j + 1 ;
index(names{i}) = j ;
imdb.images.id(j) = j ;
imdb.images.set(j) = setCode ;
imdb.images.name{j} = names{i} ;
imdb.images.classification(j) = true ;
else
j = index(names{i}) ;
end
if labels(i) > 0, imdb.classes.images{ci}(end+1) = j ; end
end
end
% ------------------------------------------------------------------------------
function [imdb, index] = addSegmentationSet(opts, imdb, index, setName, setCode)
% ------------------------------------------------------------------------------
segAnnoPath = fullfile(opts.dataDir, 'ImageSets', ...
'Segmentation', [setName '.txt']) ;
fprintf('%s: reading %s\n', mfilename, segAnnoPath) ;
segNames = textread(segAnnoPath, '%s') ; %#ok
j = numel(imdb.images.id) ;
for i=1:length(segNames)
if index.isKey(segNames{i})
k = index(segNames{i}) ;
imdb.images.segmentation(k) = true ;
imdb.images.set(k) = setCode ;
else
j = j + 1 ;
index(segNames{i}) = j ;
imdb.images.id(j) = j ;
imdb.images.set(j) = setCode ;
imdb.images.name{j} = segNames{i} ;
imdb.images.classification(j) = false ;
imdb.images.segmentation(j) = true ;
end
end
% -------------------------------------------------------------------------
function imdb = getImageSizes(imdb)
% -------------------------------------------------------------------------
for j=1:numel(imdb.images.id)
info = imfinfo(sprintf(imdb.paths.image, imdb.images.name{j})) ;
imdb.images.size(:,j) = uint16([info.Width ; info.Height]) ;
msg = '%s: checked image %s [%d x %d]\n' ;
fprintf(msg, mfilename, imdb.images.name{j}, info.Height, info.Width) ;
end
% -------------------------------------------------------------------------
function imdb = addDetections(opts, imdb)
% -------------------------------------------------------------------------
rois = {} ; k = 0 ; msg = '%s: getting detections for %d images\n' ;
fprintf(msg, mfilename, numel(imdb.images.id)) ;
for j=1:numel(imdb.images.id)
fprintf('.') ; if mod(j,80)==0,fprintf('\n') ; end
name = imdb.images.name{j} ;
annoPath = fullfile(opts.dataDir, 'Annotations', [name '.xml']) ;
if ~exist(annoPath, 'file')
if imdb.images.classification(j) && imdb.images.set(j) ~= 3
msg = 'Could not find detection annotations for ''%s''. Skipping.' ;
warning(msg, name) ;
end
continue ;
end
doc = xmlread(annoPath) ;
x = parseXML(doc, doc.getDocumentElement()) ;
for q = 1:numel(x.object)
xmin = sscanf(x.object(q).bndbox.xmin,'%d') ;
ymin = sscanf(x.object(q).bndbox.ymin,'%d') ;
xmax = sscanf(x.object(q).bndbox.xmax,'%d') - 1 ;
ymax = sscanf(x.object(q).bndbox.ymax,'%d') - 1 ;
k = k + 1 ; roi.id = k ;
roi.image = imdb.images.id(j) ;
roi.class = find(strcmp(x.object(q).name, imdb.classes.name)) ;
roi.box = [xmin;ymin;xmax;ymax] ;
roi.difficult = logical(sscanf(x.object(q).difficult,'%d')) ;
roi.truncated = logical(sscanf(x.object(q).truncated,'%d')) ;
if isfield(x.object(q),'occluded')
roi.occluded = logical(sscanf(x.object(q).occluded,'%d')) ;
else
roi.occluded = false ;
end
switch x.object(q).pose
case 'frontal', roi.aspect = 1 ;
case 'rear', roi.aspect = 2 ;
case {'sidefaceleft', 'left'}, roi.aspect = 3 ;
case {'sidefaceright', 'right'}, roi.aspect = 4 ;
case {'','unspecified'}, roi.aspect = 5 ;
otherwise, error('Unknown view ''%s''', x.object(q).pose) ;
end
rois{k} = roi ; %#ok
end
end
fprintf('\n') ;
rois = horzcat(rois{:}) ;
imdb.objects = struct(...
'id', uint32([rois.id]), ...
'image', uint32([rois.image]), ...
'class', uint8([rois.class]), ...
'box', single([rois.box]), ...
'difficult', [rois.difficult], ...
'truncated', [rois.truncated], ...
'occluded', [rois.occluded], ...
'aspect', uint8([rois.aspect])) ;
% -------------------------------------------------------------------------
function value = parseXML(doc, x)
% -------------------------------------------------------------------------
text = {''} ;
opts = struct ;
if x.hasChildNodes
for c = 1:x.getChildNodes().getLength()
y = x.getChildNodes().item(c-1) ;
switch y.getNodeType()
case doc.TEXT_NODE
text{end+1} = lower(char(y.getData())) ; %#ok
case doc.ELEMENT_NODE
param = lower(char(y.getNodeName())) ;
if strcmp(param, 'part'), continue ; end
value = parseXML(doc, y) ;
if ~isfield(opts, param)
opts.(param) = value ;
else
opts.(param)(end+1) = value ;
end
end
end
if numel(fieldnames(opts)) > 0
value = opts ;
else
value = strtrim(horzcat(text{:})) ;
end
end
% -------------------------------------------------------------------------
function str=esc(str)
% -------------------------------------------------------------------------
str = strrep(str, '\', '\\') ;
|
github
|
albanie/mcnDatasets-master
|
eval_voc_cls.m
|
.m
|
mcnDatasets-master/pascal/helpers/eval_voc_cls.m
| 2,667 |
utf_8
|
2ecdf767a03c8f7c347660d9b63b00cf
|
function res = eval_voc_cls(cls, image_ids, scores, VOCopts, varargin)
% RES = EVAL_VOC(CLS, IMAGE_IDS, SCORES, VOCOPTS)
% Use the VOCdevkit to evaluate classifications specified in boxes
% for class cls against the ground-truth boxes in the image
% database IMDB. Results files are saved with an optional suffix.
%
% This is a modified version of Ross Girshick's Fast R-CNN code.
% Add a random string ("salt") to the end of the results file name
% to prevent concurrent evaluations from clobbering each other
opts.use_res_salt = true ;
opts.rm_res = true ; % Delete results files after computing APs
opts.comp_id = 'comp2' ; % comp2 because we use outside data (ILSVRC2012)
drawCurve = true ; % draw each class curve
opts.suffix = '' ;
opts.year = 2007 ;
[opts, ~] = vl_argparse(opts, varargin) ;
if ~strcmp(opts.suffix, ''), opts.suffix = ['_' opts.suffix] ; end
if opts.use_res_salt
prev_rng = rng ; rng shuffle ; salt = sprintf('%d', randi(100000)) ;
res_id = [opts.comp_id '-' salt] ; rng(prev_rng) ;
else
res_id = opts.comp_id ;
end
% write out detections in PASCAL format and score
res_fn = sprintf(VOCopts.clsrespath, res_id, cls);
fid = fopen(res_fn, 'w') ;
for i = 1:numel(image_ids)
template = '%s %f\n' ;
fprintf(fid, template, image_ids{i}, scores(i)) ;
end
fclose(fid) ;
[recall, prec, ap] = VOCevalcls(VOCopts, res_id, cls, drawCurve) ;
switch opts.year
case 2007, ap_auc = VOCap07(recall, prec) ;
case 2012, ap_auc = xVOCap(recall, prec) ;
otherwise, error('Year %d not recognised', opts.year) ;
end
ylim([0 1]) ; xlim([0 1]) ; % force plot limits
path = fullfile(VOCopts.cacheDir, sprintf('%s_pr_%s.jpg', cls, opts.suffix)) ;
print(gcf, '-djpeg', '-r0', path) ;
fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc) ;
path = fullfile(VOCopts.cacheDir, sprintf('%s_pr_%s',cls, opts.suffix)) ;
save(path, 'recall', 'prec', 'ap', 'ap_auc') ;
res.recall = recall ; res.prec = prec ; res.ap = NaN ; res.ap_auc = ap_auc ;
if opts.rm_res, delete(res_fn) ; end
% -----------------------------
function ap = VOCap07(rec,prec)
% -----------------------------
% From the PASCAL VOC 2007 devkit
ap = 0 ;
for t = 0:0.1:1
p = max(prec(rec>=t)) ;
if isempty(p), p=0 ; end
ap = ap + (p/11) ;
end
% -----------------------------
function ap = xVOCap(rec,prec)
% -----------------------------
% this function is part of the PASCAL VOC 2011 devkit
mrec=[0 ; rec ; 1];
mpre=[0 ; prec ; 0];
for i=numel(mpre)-1:-1:1
mpre(i)=max(mpre(i),mpre(i+1));
end
i=find(mrec(2:end)~=mrec(1:end-1))+1;
ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
|
github
|
albanie/mcnDatasets-master
|
eval_voc.m
|
.m
|
mcnDatasets-master/pascal/helpers/eval_voc.m
| 3,584 |
utf_8
|
1894c1f0ce5c9212bd5dc7325dfc9bbf
|
function res = eval_voc(cls, image_ids, bboxes, scores, VOCopts, varargin)
% RES = EVAL_VOC(CLS, IMAGE_IDS, BBOXES, SCORES, VOCOPTS)
% Use the VOCdevkit to evaluate detections specified in boxes
% for class cls against the ground-truth boxes in the image
% database IMDB. Results files are saved with an optional suffix.
%
% This is a modified version of Ross Girshick's code
%
% as part of R-CNN. released
% AUTORIGHTS
% ---------------------------------------------------------
% Copyright (c) 2014, Ross Girshick
%
% This file is part of the R-CNN code and is available
% under the terms of the Simplified BSD License provided in
% LICENSE. Please retain this notice and LICENSE if you use
% this file (or any portion of it) in your project.
% ---------------------------------------------------------
% Add a random string ("salt") to the end of the results file name
% to prevent concurrent evaluations from clobbering each other
opts.use_res_salt = true;
opts.rm_res = true ; % Delete results files after computing APs
opts.comp_id = 'comp4' ; % comp4 because we use outside data (ILSVRC2012)
drawCurve = true ; % draw each class curve
opts.suffix = '' ;
opts.year = 2007 ;
% the official eval is quite slow, so use x10 version for development
% and switch to official for paper experiments
opts.evalVersion = 'official' ;
[opts, ~] = vl_argparse(opts, varargin) ;
if ~strcmp(opts.suffix, ''), opts.suffix = ['_' opts.suffix] ; end
if opts.use_res_salt
prev_rng = rng ; rng shuffle ; salt = sprintf('%d', randi(100000)) ;
res_id = [opts.comp_id '-' salt] ; rng(prev_rng) ;
else
res_id = opts.comp_id ;
end
% write out detections in PASCAL format and score
res_fn = sprintf(VOCopts.detrespath, res_id, cls);
fid = fopen(res_fn, 'w') ;
for i = 1:numel(image_ids)
template = '%s %f %.3f %.3f %.3f %.3f\n' ;
fprintf(fid, template, image_ids{i}, scores(i), bboxes(i,:)) ;
end
fclose(fid) ;
tic ; % bug in VOCevaldet requires that tic has been called first
switch opts.evalVersion
case 'official'
[recall, prec, ap] = VOCevaldet(VOCopts, res_id, cls, drawCurve) ;
case 'fast'
[recall, prec, ap] = x10VOCevaldet(VOCopts, res_id, cls, drawCurve) ;
otherwise
error('Evaluation version %s not recognised', opts.evalVersion) ;
end
switch opts.year
case 2007, ap_auc = VOCap07(recall, prec) ;
case 2012, ap_auc = xVOCap(recall, prec) ;
otherwise, error('Year %d not recognised', opts.year) ;
end
ylim([0 1]) ; xlim([0 1]) ; % force plot limits
path = fullfile(VOCopts.cacheDir, sprintf('%s_pr_%s.jpg', cls, opts.suffix)) ;
print(gcf, '-djpeg', '-r0', path) ;
fprintf('!!! %s : %.4f %.4f\n', cls, ap, ap_auc) ;
path = fullfile(VOCopts.cacheDir, sprintf('%s_pr_%s',cls, opts.suffix)) ;
save(path, 'recall', 'prec', 'ap', 'ap_auc') ;
res.recall = recall ; res.prec = prec ; res.ap = NaN ; res.ap_auc = ap_auc ;
if opts.rm_res, delete(res_fn) ; end
% -----------------------------
function ap = VOCap07(rec,prec)
% -----------------------------
% From the PASCAL VOC 2007 devkit
ap = 0 ;
for t = 0:0.1:1
p = max(prec(rec>=t)) ;
if isempty(p), p=0 ; end
ap = ap + (p/11) ;
end
% -----------------------------
function ap = xVOCap(rec,prec)
% -----------------------------
% this function is part of the PASCAL VOC 2011 devkit
mrec=[0 ; rec ; 1];
mpre=[0 ; prec ; 0];
for i=numel(mpre)-1:-1:1
mpre(i)=max(mpre(i),mpre(i+1));
end
i=find(mrec(2:end)~=mrec(1:end-1))+1;
ap=sum((mrec(i)-mrec(i-1)).*mpre(i));
|
github
|
albanie/mcnDatasets-master
|
getRmlImdb.m
|
.m
|
mcnDatasets-master/rml/getRmlImdb.m
| 5,299 |
utf_8
|
891c2e84680f145e95cb207c55c406d4
|
function imdb = getRmlImdb(opts, varargin)
%GETRMLIMDB Rml imdb construction
% IMDB = GETRMLIMDB(OPTS) builds an image/video database for training and
% testing on the RML dataset
%
% Copyright (C) 2018 Samuel Albanie
% Licensed under The MIT License [see LICENSE.md for details]
opts.generateWavs = true ;
opts = vl_argparse(opts, varargin) ;
imdb = rmlSetup(opts) ;
imdb.images.ext = 'jpg' ;
end
% ------------------------------
function imdb = rmlSetup(opts)
% ------------------------------
emotions = {'Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise'} ;
emoKeys = {'an', 'di', 'fe', 'ha', 'sa', 'su'} ; % notation used in folders
faceDir = fullfile(opts.dataDir, 'faces') ;
subsets = {'rml-1', 'rml-2'} ;
speakers = {{'s1', 's2', 's3', 's4', 's5'}, {'s6', 's7', 's8'}} ;
facePaths = zs_getImgsInSubdirs(faceDir, 'jpg') ;
allTracks = cellfun(@fileparts, facePaths, 'uni', 0) ;
numTracks = numel(unique(allTracks)) ;
fprintf('found %d tracks (expected 720) \n', numTracks) ;
% use FER2013 ordering
labels = zeros(1, numTracks) ;
relPaths = cell(1, numTracks) ;
vidNames = cell(1, numTracks) ;
spIds = zeros(1, numTracks) ;
subsetIdx = zeros(1, numTracks) ;
vidPaths = cell(1, numTracks) ;
if opts.generateWavs
wavPaths = cell(1, numTracks) ;
end
% determine track labels
counter = 1 ;
for ii = 1:numel(subsets)
subset = subsets{ii} ;
subsetSpeakers = speakers{ii} ;
for jj = 1:numel(subsetSpeakers)
sp = subsetSpeakers{jj} ;
tracks = zs_getSubdirs(fullfile(faceDir, subset, sp)) ;
% flatten speakers with multiple languages
if any(~ismember(tracks, allTracks))
subTracks = cellfun(@zs_getSubdirs, tracks, 'uni', 0) ;
tracks = [subTracks{:}] ; depth = 6 ;
else
depth = 5 ;
end
assert(all(ismember(tracks, allTracks)), 'incorrect track selection') ;
for kk = 1:numel(tracks)
fprintf('processing %d/%d (%s)\n', counter, numTracks, subset) ;
[~,vidName,~] = fileparts(tracks{kk}) ;
label = find(strcmp(emoKeys, vidName(1:2))) ;
assert(numel(label) == 1, 'could not find appropriate label') ;
paths = zs_getImgsInSubdirs(tracks{kk}, 'jpg') ;
tails = cellfun(@(x) getTail(x, depth), paths, 'Uni', 0) ;
relPaths{counter} = tails ;
subsetIdx(counter) = ii ;
labels(counter) = label ;
vidNames{counter} = vidName ;
% store path to video and generate wav if requested
vidBasePath = strrep(tracks{kk}, '/faces', '') ; % chop from path
vidPath = [vidBasePath '.avi'] ;
assert(logical(exist(vidPath, 'file')), 'avi does not exist') ;
vidPaths{counter} = vidPath ;
if opts.generateWavs
wavPaths{counter} = extractAudio(vidBasePath) ;
end
spIds(counter) = find(strcmp(sp, [speakers{:}])) ;
counter = counter + 1 ;
end
end
end
% sanity check expected track numbers
assert(counter == 721, 'unexpected number of tracks') ;
imdb.tracks.vids = vidNames ;
imdb.tracks.vidPaths = vidPaths ;
imdb.tracks.paths = relPaths ;
imdb.tracks.labels = labels ;
imdb.tracks.labelsFerPlus = convertFerToFerPlus(labels, emotions) ;
imdb.tracks.set = subsetIdx ;
imdb.meta.classes = emotions ;
imdb.meta.sets = subsets ;
if opts.generateWavs
imdb.tracks.wavPaths = wavPaths ;
end
% check statistics against expected numbers
msg = 'emotion statistics do not match expected numbers' ;
assert(sum(imdb.tracks.set == 1 & imdb.tracks.labels == 1) == 66, msg) ;
imdb.tracks.id = 1:numTracks ;
end
% -------------------------------------------------------------------------
function destPath = extractAudio(vidBasePath)
% -------------------------------------------------------------------------
srcPath = [vidBasePath '.avi'] ;
destPath = [vidBasePath '.wav'] ;
if ~exist(destPath, 'file')
ffmpegBin = '/users/albanie/local/bin/ffmpeg' ;
cmd = sprintf('%s -i %s -vn -acodec copy %s', ...
ffmpegBin, srcPath, destPath) ;
status = system(cmd) ;
if status ~= 0, keyboard ; end
end
end
% -------------------------------------------------------------------------
function labels = convertFerToFerPlus(labels, ferEmotions)
% -------------------------------------------------------------------------
% convert FER labels to FERplus emotion indices
ferPlusEmotions = {'neutral', 'happiness', 'surprise', 'sadness', ...
'anger', 'disgust', 'fear', 'contempt'} ;
% match strings
strMap = containers.Map() ;
strMap('Happy') = 'happiness' ;
strMap('Sad') = 'sadness' ;
strMap('Neutral') = 'neutral' ;
strMap('Surprise') = 'surprise' ;
strMap('Disgust') = 'disgust' ;
strMap('Fear') = 'fear' ;
strMap('Angry') = 'anger' ;
% generate label permutation array
permuteMap = cellfun(@(x) find(strcmp(strMap(x), ferPlusEmotions)), ...
ferEmotions) ;
msg = 'contempt should not exist in original labels' ;
assert(~ismember(8, permuteMap), msg) ;
labels = permuteMap(labels) ;
end
% ---------------------------------------
function tail = getTail(path, numTokens)
% ---------------------------------------
tokens = strsplit(path, '/') ;
tail = fullfile(tokens{end-numTokens+1:end}) ;
end
|
github
|
q-omar/gravity_anomalies-master
|
grav_pot_point.m
|
.m
|
gravity_anomalies-master/matlab_implementation/grav_pot_point.m
| 307 |
utf_8
|
e8daed0e0a3699dea2338cd54278e2f5
|
%GOPH 547-Gravity and Magnetics
%Safian Omar Qureshi
%ID: 10086638
%TA: Ye Sun
%% Question 1a
function [U]=grav_pot_point(x,xm,m,G) %defining gravity potential function
r_norm=norm(x-xm); %simply using formula
U=(G*m)./r_norm;
end
%these will be used in other parts of the code
|
github
|
q-omar/gravity_anomalies-master
|
grav_eff_point.m
|
.m
|
gravity_anomalies-master/matlab_implementation/grav_eff_point.m
| 369 |
utf_8
|
d201104f25cc68482ed0caa23d8be8d7
|
%GOPH 547-Gravity and Magnetics (W2017)
%Safian Omar Qureshi
%ID: 10086638
%TA: Ye Sun
%% Question 1b
function [gz]=grav_eff_point(x,xm,m,G) %defining gravity effect function
r_norm=norm(x-xm); %simply using formula
r3=r_norm^3;
dz=(x(3)-xm(3));
gz=(G*m*dz)/r3;
end
%these will be used in other parts of the code
|
github
|
xiaosonghe/DynamicFunctionalConnectivity-master
|
S4ModularityMeasures.m
|
.m
|
DynamicFunctionalConnectivity-master/S4ModularityMeasures.m
| 1,059 |
utf_8
|
28d9089e18e0b75bb522eb263277638c
|
% Calculating MA, Flexibility, LI, P, Z, FCw and FCb
clear all;
sbj=importdata('E:\VerbGeneration_network\sbj.txt');
System=[1;1;1;2;2;2;2;2;3;3;3;4;4;4;4;4];% Define System for LI and I, R calculation
parfor t=1:length(sbj)
X=load(['E:\VerbGeneration_network\6CommunityMatrix\' sbj{t} '.mat']);
pathD=['E:\VerbGeneration_network\7ModularityMeasures\' sbj{t} '.mat'];
ModularityMeasures(System,X.S,X.A,pathD);
end
function ModularityMeasures(System,SO,A,pathD)
for ii=1:100
MA(:,:,ii)=allegiance(SO(:,:,ii));% Module Allegiance
F(ii,:)=flexibility(SO(:,:,ii));% Flexibility
Prom(ii,:)=promiscuity(SO(:,:,ii));% Promiscuity
I_s(ii,:)=integration(MA(:,:,ii),System);% Integration by System (L Broca, L Wernicke, R Broca, R Wernicke)
R_s(ii,:)=recruitment(MA(:,:,ii),System);% Recruitment by System (L Broca, L Wernicke, R Broca, R Wernicke)
RI(:,:,ii)=integration_sub(MA(:,:,ii),System);% RI by System (L Broca, L Wernicke, R Broca, R Wernicke)
end
save(pathD,'MA','F','Prom','I_s','R_s','RI');
end
|
github
|
xiaosonghe/DynamicFunctionalConnectivity-master
|
S6NullModelMeasures.m
|
.m
|
DynamicFunctionalConnectivity-master/S6NullModelMeasures.m
| 1,889 |
utf_8
|
fae0f8439cbcaffb12cfb602dd83c24a
|
% Calculating Flexibility and MA
clear all;
sbj=importdata('E:\VerbGeneration_network\sbj.txt');
System=[1;1;1;2;2;2;2;2;3;3;3;4;4;4;4;4];% Define System for LI and I, R calculation
parfor t=1:length(sbj)
x=load(['E:\VerbGeneration_network\8RandomCommunity\' sbj{t} '.mat']);
pathD=['E:\VerbGeneration_network\9NullModelMeasures\' sbj{t} '.mat'];
% Generating Modularity Measures
GenModalMeasure(C,System,x.Scr,x.Str,x.Snr,x.Ss,pathD);
end
% Generating Modularity Measures
function GenModalMeasure(C,System,Scr,Str,Snr,Ss,pathD)
for k=1:100
clear SO MAt Ft Promt Perst I_ht I_st R_ht R_st;
SO(:,:,:,1)=Scr(:,:,:,k);
SO(:,:,:,2)=Snr(:,:,:,k);
SO(:,:,:,3)=Ss(:,:,:,k);
for ii=1:100
for t=1:3
MAt(:,:,ii,t)=allegiance(SO(:,:,ii,t));% Module Allegiance
Ft(ii,:,t)=flexibility(SO(:,:,ii,t));% Flexibility
Promt(ii,:,t)=promiscuity(SO(:,:,ii,t));% Promiscuity
I_st(ii,:,t)=integration(MAt(:,:,ii),System);% Integration by System (L Broca, L Wernicke, R Broca, R Wernicke)
R_st(ii,:,t)=recruitment(MAt(:,:,ii),System);% Recruitment by System (L Broca, L Wernicke, R Broca, R Wernicke)
end
end
MAcr(:,:,:,k)=MAt(:,:,:,1);MAnr(:,:,:,k)=MAt(:,:,:,2);MAs(:,:,:,k)=MAt(:,:,:,3);
Fcr(:,:,k)=Ft(:,:,1);Fnr(:,:,k)=Ft(:,:,2);Fs(:,:,k)=Ft(:,:,3);
Promcr(:,:,k)=Promt(:,:,1);Promnr(:,:,k)=Promt(:,:,2);Proms(:,:,k)=Promt(:,:,3);
I_scr(:,:,k)=I_st(:,:,1);I_snr(:,:,k)=I_st(:,:,2);I_ss(:,:,k)=I_st(:,:,3);
R_scr(:,:,k)=R_st(:,:,1);R_snr(:,:,k)=R_st(:,:,2);R_ss(:,:,k)=R_st(:,:,3);
clear SO MAt Ft Promt I_st R_st;
end
if exist(pathD,'file')
delete(pathD);
end
save(pathD,'MAcr','MAnr','MAs','Fcr','Fnr','Fs','Promcr','Promnr','Proms','I_scr','I_snr','I_ss','R_hcr','R_hnr','R_hs','R_scr','R_snr','R_ss');
end
|
github
|
xiaosonghe/DynamicFunctionalConnectivity-master
|
S5RandomCommunity.m
|
.m
|
DynamicFunctionalConnectivity-master/S5RandomCommunity.m
| 4,936 |
utf_8
|
6d95f5a97f8291e0a715e8fe46fd2dbb
|
% Generating Null Models
clear all;
sbj=importdata('E:\VerbGeneration_network\sbj.txt');
gamma = 1; omega = 0.4; % Based on Chai et al 2016 CC
parfor t=1:length(sbj)
X=load(['E:\VerbGeneration_network\5tDecomposedSignals\' sbj{t} '.mat'],'D2');
pathD=['E:\VerbGeneration_network\8RandomCommunity\' sbj{t} '.mat'];
% Connectional Null Model
ConnectionalNullModel(pathD,X.D2,gamma,omega);
% Nodal Null Model
NodalNullModel(pathD,X.D2,gamma,omega);
% Static Null Model
StaticNullModel(pathD,X.D2,gamma,omega);
end
% Connectional Null Model
function ConnectionalNullModel(pathD,d,gamma,omega)
% Creating adjacency matrix over time: Window Size = 40 sec (14 windows, 8=half-window)/30 sec (19 windows, 6=half-window)/1 min (9 windows, 12=half-window;
% Overlapping = 50% with matlab new wavelet coherence
SampRate=1/2.5;
for i=1:14
clear At;
for k=1:16
for kk=1:16
clear wcoh f;
[wcoh,~,f] = wcoherence(d(((i-1)*8+1):(i+1)*8,k),d(((i-1)*8+1):(i+1)*8,kk),SampRate);
At(k,kk)=mean(mean(wcoh(find(f>0.05 & f<0.1),:)));
clear wcoh f;
end
end
At=round(At.*1000000)./1000000;
A{i,1}=At;
clear At;
end
for k=1:100
clear Acr;
for i=1:14
Acr{i}=randmio_und(A{i},20);
end
for ii=1:100 % 100 times of optimization
clear N T B mm PP St;
N=length(Acr{1});
T=length(Acr);
[B,mm] = multiord(Acr,gamma,omega);
PP = @(S) postprocess_ordinal_multilayer(S,T);
[St,Qcr(ii,k),~] = iterated_genlouvain(B,10000,0,1,'moverandw',[], PP); % tobe saved (Qtr)
Qcr(ii,k)=Qcr(ii,k)/mm;
St = reshape(St, N, T);
Scr(:,:,ii,k)=St';% tobe saved Str
clear N T B mm PP St;
end
clear Acr;
end
if exist(pathD,'file')
delete(pathD);
end
save(pathD,'Qcr','Scr');
end
% Nodal Null Model
function NodalNullModel(pathD,d,gamma,omega)
% Creating adjacency matrix over time: Window Size = 40 sec (14 windows, 8=half-window)/30 sec (19 windows, 6=half-window)/1 min (9 windows, 12=half-window;
% Overlapping = 50% with matlab new wavelet coherence
SampRate=1/2.5;
% Creating 100 null models
for k=1:100
% Creating adjacency matrix over time, with ROIs rotated at each window
clear Anr;
for i=1:14
clear At rd dt tt;
rd=randperm(16);
% [~,Inr(i,:,k)]=sort(rd);% tobe saved Inr
for tt=1:16
dt(:,tt)=d(:,rd(tt));
end
% Coherence
for kk=1:16
for kkk=1:16
clear wcoh f;
[wcoh,~,f] = wcoherence(dt(((i-1)*8+1):(i+1)*8,kk),dt(((i-1)*8+1):(i+1)*8,kkk),SampRate);
At(kk,kkk)=mean(mean(wcoh(find(f>0.05 & f<0.1),:)));
clear wcoh f;
end
end
At=round(At.*1000000)./1000000;
Anr{i,1}=At;
clear At rd dt tt;
end
for ii=1:100 % 100 times of optimization
clear N T B mm PP St;
N=length(Anr{1});
T=length(Anr);
[B,mm] = multiord(Anr,gamma,omega);
PP = @(S) postprocess_ordinal_multilayer(S,T);
[St,Qnr(ii,k),~] = iterated_genlouvain(B,10000,0,1,'moverandw',[], PP); % tobe saved (Qnr)
Qnr(ii,k)=Qnr(ii,k)/mm;
St = reshape(St, N, T);
Snr(:,:,ii,k)=St';% tobe saved Snr
clear N T B mm PP St;
end
clear Anr;
end
save(pathD,'Qnr','Snr','-append');% 'Inr'
end
% Static Null Model
function StaticNullModel(pathD,d,gamma,omega)
% Creating adjacency matrix over time: Window Size = 40 sec (14 windows, 8=half-window)/30 sec (19 windows, 6=half-window)/1 min (9 windows, 12=half-window;
% Overlapping = 50% with matlab new wavelet coherence
SampRate=1/2.5;
% Creating 100 null models
for k=1:100
% Creating adjacency matrix over time, by duplicating one of the windows
clear At As;
rd=randperm(14);
% coherence
for kk=1:16
for kkk=1:16
clear wcoh f;
[wcoh,~,f] = wcoherence(d(((rd(1)-1)*8+1):(rd(1)+1)*8,kk),d(((rd(1)-1)*8+1):(rd(1)+1)*8,kkk),SampRate);
At(kk,kkk)=mean(mean(wcoh(find(f>0.05 & f<0.1),:)));
clear wcoh f;
end
end
At=round(At.*1000000)./1000000;
for i=1:14
As{i,1}=At;
end
for ii=1:100 % 100 times of optimization
% Following based on Example on multilayer network quality function of Mucha et al. 2010
% (using multilayer cell A with A{s} the adjacency matrix of layer s)
clear N T B mm PP St;
N=length(As{1});
T=length(As);
[B,mm] = multiord(As,gamma,omega);
PP = @(S) postprocess_ordinal_multilayer(S,T);
[St,Qs(ii,k),~] = iterated_genlouvain(B,10000,0,1,'moverandw',[], PP); % tobe saved (Qs)
Qs(ii,k)=Qs(ii,k)/mm;
St = reshape(St, N, T);
Ss(:,:,ii,k)=St';% tobe saved Ss
clear N T B mm PP St;
end
clear At As;
end
save(pathD,'Qs','Ss','-append');
end
|
github
|
xiaosonghe/DynamicFunctionalConnectivity-master
|
S2ROISignalExtract.m
|
.m
|
DynamicFunctionalConnectivity-master/S2ROISignalExtract.m
| 816 |
utf_8
|
b4aa37c89259eabb7055f0f84f518721
|
% Extract ROI Signal
% Order: LIFGorb, LIFG, LMFG, LAT, LMAT, LMPT, LPT, LAG, RIFGorb, RIFG, RMFG, RAT, RMAT, RMPT, RPT, RAG
clear all;
sbj=importdata('E:\VerbGeneration_network\sbj.txt');
parfor i=1:length(sbj)
roi_filest = spm_get('files',['E:\VerbGeneration_network\4IndividualROIs\' sbj{i}],'*roi.mat');
roi_files=roi_filest([4 3 5 2 6:8 1 12 11 13 10 14:16 9],:);
ImgData=['E:\VerbGeneration_network\1Preprocessing\FunImgARCWS\' sbj{i} '\swCovRegressed_4DVolume.nii'];
pathD=['E:\VerbGeneration_network\5ROISignals\' sbj{i} '.txt'];
extractROIsignals(roi_files,ImgData,pathD);
end
function extractROIsignals(roi_files,ImgData,pathD)
rois = maroi('load_cell', roi_files);
mY=get_marsy(rois{:},ImgData,'mean');
y = summary_data(mY);
save(pathD,'y','-ascii','-double');
end
|
github
|
xiaosonghe/DynamicFunctionalConnectivity-master
|
S3CommunityMatrix.m
|
.m
|
DynamicFunctionalConnectivity-master/S3CommunityMatrix.m
| 2,321 |
utf_8
|
06bb3a5eb523023ff2e1fbfb87078632
|
% Generate the community assignments matrix
clear all;
sbj=importdata('E:\VerbGeneration_network\sbj.txt');
gamma = 1; omega = 0.4; % Based on Chai et al 2016 CC
parfor t=1:length(sbj)
X=load(['E:\VerbGeneration_network\5tDecomposedSignals\' sbj{t} '.mat'],'D2');
pathD=['E:\VerbGeneration_network\6CommunityMatrix\' sbj{t} '.mat'];
communitydetection(gamma,omega,pathD,X.D2);
end
function communitydetection(gamma,omega,pathD,d)
% Creating adjacency matrix over time: Window Size = 40 sec (14 windows, 8=half-window)/30 sec (19 windows, 6=half-window)/1 min (9 windows, 12=half-window;
% Overlapping = 50% with matlab new wavelet coherence
SampRate=1/2.5;
for i=1:14
clear At;
for k=1:16
for kk=1:16
clear wcoh f;
[wcoh,~,f] = wcoherence(d(((i-1)*8+1):(i+1)*8,k),d(((i-1)*8+1):(i+1)*8,kk),SampRate);
At(k,kk)=mean(mean(wcoh(find(f>0.05 & f<0.1),:)));
clear wcoh f;
end
end
At=round(At.*1000000)./1000000;
A{i,1}=At;
clear At;
end
% % Creating adjacency matrix over time: Window Size = 40 sec (27 windows, (4*i-3):(4*i+12))/30 sec (28 windows, (4*i-3):(4*i+8));
% % Step = 4 TR/10s; with matlab new wavelet coherence
% SampRate=1/2.5;
% for i=1:27
% clear At;
% for k=1:16
% for kk=1:16
% clear wcoh f;
% [wcoh,~,f] = wcoherence(d((4*i-3):(4*i+12),k),d((4*i-3):(4*i+12),kk),SampRate);
% At(k,kk)=mean(mean(wcoh(find(f>0.05 & f<0.1),:)));
% clear wcoh f;
% end
% end
% At=round(At.*1000000)./1000000;
% A{i,1}=At;
% clear At;
% end
for ii=1:100 % 100 times of optimization
% Following based on Example on multilayer network quality function of Mucha et al. 2010
% (using multilayer cell A with A{s} the adjacency matrix of layer s)
clear N T B mm PP St;
N=length(A{1});
T=length(A);
[B,mm] = multiord(A,gamma,omega);
PP = @(S) postprocess_ordinal_multilayer(S,T);
[St,Q(ii),~] = iterated_genlouvain(B,10000,0,1,'moverandw',[], PP); % tobe saved (Q)
St = reshape(St, N, T);
Q(ii)=Q(ii)/mm;
S(:,:,ii)=St';% tobe saved
clear N T B mm PP St;
end
if exist(pathD,'file')
delete(pathD);
end
save(pathD,'A','Q','S');
end
|
github
|
Erin-H/Activity-Recognition-master
|
LDA.m
|
.m
|
Activity-Recognition-master/LDA.m
| 8,682 |
utf_8
|
6fa50a0b489e557f036d16d4122c282d
|
function [eigvector, eigvalue] = LDA(gnd,options,data)
% LDA: Linear Discriminant Analysis
%
% [eigvector, eigvalue] = LDA(gnd, options, data)
%
% Input:
% data - Data matrix. Each row vector of fea is a data point.
% gnd - Colunm vector of the label information for each
% data point.
% options - Struct value in Matlab. The fields in options
% that can be set:
%
% Regu - 1: regularized solution,
% a* = argmax (a'X'WXa)/(a'X'Xa+ReguAlpha*I)
% 0: solve the sinularity problem by SVD
% Default: 0
%
% ReguAlpha - The regularization parameter. Valid
% when Regu==1. Default value is 0.1.
%
% ReguType - 'Ridge': Tikhonov regularization
% 'Custom': User provided
% regularization matrix
% Default: 'Ridge'
% regularizerR - (nFea x nFea) regularization
% matrix which should be provided
% if ReguType is 'Custom'. nFea is
% the feature number of data
% matrix
% Fisherface - 1: Fisherface approach
% PCARatio = nSmp - nClass
% Default: 0
%
% PCARatio - The percentage of principal
% component kept in the PCA
% step. The percentage is
% calculated based on the
% eigenvalue. Default is 1
% (100%, all the non-zero
% eigenvalues will be kept.
% If PCARatio > 1, the PCA step
% will keep exactly PCARatio principle
% components (does not exceed the
% exact number of non-zero components).
%
%
% Output:
% eigvector - Each column is an embedding function, for a new
% data point (row vector) x, y = x*eigvector
% will be the embedding result of x.
% eigvalue - The sorted eigvalue of LDA eigen-problem.
% elapse - Time spent on different steps
%
% Examples:
%
% fea = rand(50,70);
% gnd = [ones(10,1);ones(15,1)*2;ones(10,1)*3;ones(15,1)*4];
% options = [];
% options.Fisherface = 1;
% [eigvector, eigvalue] = LDA(gnd, options, fea);
% Y = fea*eigvector;
%
%
% See also LPP, constructW, LGE
%
%
%
%Reference:
%
% Deng Cai, Xiaofei He, Jiawei Han, "SRDA: An Efficient Algorithm for
% Large Scale Discriminant Analysis", IEEE Transactions on Knowledge and
% Data Engineering, 2007.
%
% Deng Cai, "Spectral Regression: A Regression Framework for
% Efficient Regularized Subspace Learning", PhD Thesis, Department of
% Computer Science, UIUC, 2009.
%
% version 3.0 --Dec/2011
% version 2.1 --June/2007
% version 2.0 --May/2007
% version 1.1 --Feb/2006
% version 1.0 --April/2004
%
% Written by Deng Cai (dengcai AT gmail.com)
%
MAX_MATRIX_SIZE = 1600; % You can change this number according your machine computational power
EIGVECTOR_RATIO = 0.1; % You can change this number according your machine computational power
if (~exist('options','var'))
options = [];
end
if ~isfield(options,'Regu') || ~options.Regu
bPCA = 1;
if ~isfield(options,'PCARatio')
options.PCARatio = 1;
end
else
bPCA = 0;
if ~isfield(options,'ReguType')
options.ReguType = 'Ridge';
end
if ~isfield(options,'ReguAlpha')
options.ReguAlpha = 0.1;
end
end
% ====== Initialization
[nSmp,nFea] = size(data);
if length(gnd) ~= nSmp
error('gnd and data mismatch!');
end
classLabel = unique(gnd);
nClass = length(classLabel);
Dim = nClass - 1;
if bPCA && isfield(options,'Fisherface') && options.Fisherface
options.PCARatio = nSmp - nClass;
end
if issparse(data)
data = full(data);
end
sampleMean = mean(data,1);
data = (data - repmat(sampleMean,nSmp,1));
bChol = 0;
if bPCA && (nSmp > nFea+1) && (options.PCARatio >= 1)
DPrime = data'*data;
DPrime = max(DPrime,DPrime');
[R,p] = chol(DPrime);
if p == 0
bPCA = 0;
bChol = 1;
end
end
%======================================
% SVD
%======================================
if bPCA
[U, S, V] = mySVD(data);
[U, S, V]=CutonRatio(U,S,V,options);
eigvalue_PCA = full(diag(S));
data = U;
eigvector_PCA = V*spdiags(eigvalue_PCA.^-1,0,length(eigvalue_PCA),length(eigvalue_PCA));
else
if ~bChol
DPrime = data'*data;
% options.ReguAlpha = nSmp*options.ReguAlpha;
switch lower(options.ReguType)
case {lower('Ridge')}
for i=1:size(DPrime,1)
DPrime(i,i) = DPrime(i,i) + options.ReguAlpha;
end
case {lower('Tensor')}
DPrime = DPrime + options.ReguAlpha*options.regularizerR;
case {lower('Custom')}
DPrime = DPrime + options.ReguAlpha*options.regularizerR;
otherwise
error('ReguType does not exist!');
end
DPrime = max(DPrime,DPrime');
end
end
[nSmp,nFea] = size(data);
Hb = zeros(nClass,nFea);
for i = 1:nClass,
index = find(gnd==classLabel(i));
classMean = mean(data(index,:),1);
Hb (i,:) = sqrt(length(index))*classMean;
end
if bPCA
[dumpVec,eigvalue,eigvector] = svd(Hb,'econ');
eigvalue = diag(eigvalue);
eigIdx = find(eigvalue < 1e-3);
eigvalue(eigIdx) = [];
eigvector(:,eigIdx) = [];
eigvalue = eigvalue.^2;
eigvector = eigvector_PCA*eigvector;
else
WPrime = Hb'*Hb;
WPrime = max(WPrime,WPrime');
dimMatrix = size(WPrime,2);
if Dim > dimMatrix
Dim = dimMatrix;
end
if isfield(options,'bEigs')
bEigs = options.bEigs;
else
if (dimMatrix > MAX_MATRIX_SIZE) && (ReducedDim < dimMatrix*EIGVECTOR_RATIO)
bEigs = 1;
else
bEigs = 0;
end
end
if bEigs
%disp('use eigs to speed up!');
option = struct('disp',0);
if bChol
option.cholB = 1;
[eigvector, eigvalue] = eigs(WPrime,R,Dim,'la',option);
else
[eigvector, eigvalue] = eigs(WPrime,DPrime,Dim,'la',option);
end
eigvalue = diag(eigvalue);
else
[eigvector, eigvalue] = eig(WPrime,DPrime);
eigvalue = diag(eigvalue);
[junk, index] = sort(-eigvalue);
eigvalue = eigvalue(index);
eigvector = eigvector(:,index);
if Dim < size(eigvector,2)
eigvector = eigvector(:, 1:Dim);
eigvalue = eigvalue(1:Dim);
end
end
end
for i = 1:size(eigvector,2)
eigvector(:,i) = eigvector(:,i)./norm(eigvector(:,i));
end
function [U, S, V]=CutonRatio(U,S,V,options)
if ~isfield(options, 'PCARatio')
options.PCARatio = 1;
end
eigvalue_PCA = full(diag(S));
if options.PCARatio > 1
idx = options.PCARatio;
if idx < length(eigvalue_PCA)
U = U(:,1:idx);
V = V(:,1:idx);
S = S(1:idx,1:idx);
end
elseif options.PCARatio < 1
sumEig = sum(eigvalue_PCA);
sumEig = sumEig*options.PCARatio;
sumNow = 0;
for idx = 1:length(eigvalue_PCA)
sumNow = sumNow + eigvalue_PCA(idx);
if sumNow >= sumEig
break;
end
end
U = U(:,1:idx);
V = V(:,1:idx);
S = S(1:idx,1:idx);
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
mc_raytracing.m
|
.m
|
ray-mapping-fresnel-lens-master/mc_raytracing.m
| 3,123 |
utf_8
|
767c6a36c4ffed235827ccde07dc7265
|
% This function computes the ray tracing given the position and the
% direction of the ray and the optical system
function [zout, thetaout,last_surface] = ...
mc_raytracing(surfaces, z , tau, variables)
graf = 0;
a = 2;
k = -1;
% (x,z) = coordinates of the initial position
ray.x = surfaces(1).x(1);
ray.z = z;
ray.n = 1;
% Initial angle with respect to the optical axis
% Ray direction
ray.sz = tau;
ray.sx = sqrt(1-tau^2);
% store initial conditions for debugging
% ray.n=1; % we start in air
ray_source = ray;
s = zeros(length(surfaces) ,1);
% s = parameter for the ray parameterization
xn = zeros(length(surfaces) ,1); % xn(i) = x-s(i)*sin(theta)
zn = zeros(length(surfaces) ,1); % zn(i) = z+s(i)*cos(theta)
surfaces_hit = 0;
while( k~=4 && k~=5 && k~=6 && k~=1 && k~=7 && surfaces_hit<100)
surfaces_hit = surfaces_hit+1;
x0 = ray.x;
z0 = ray.z;
for i=1:length(surfaces)
[xn(i),zn(i),s(i), valid(i)] = ...
surfaces(i).intersection(ray, surfaces(i), variables);
end
[k] = distances(xn,zn,ray,s,valid);
% disp([' closest intersection from surface ',num2str(k),' ',surfaces(k).name]);
% (x,z) = coordinates of the closer intersection
%if(k~=7)
ray.x = xn(k);
ray.z = zn(k);
% plot([x0, xn(k)], [z0, zn(k)], ' g', 'linewidth', 1.2);
a = a+1;
% plot the path of the rays
[ray1, ray2,ray,check, energy] = surfaces(k).action(ray,surfaces(k), ...
k, x0, z0, variables, 1);
%end
if ( graf)
figure(3)
hold on
if(check)
plot([x0, xn(k)], [z0, zn(k)], ' m', 'linewidth', 1.2);
% plot([ray1.x, xn(k)], [ray1.z, zn(k)], ' -- g', 'linewidth', 1.2);
else
plot([x0, xn(k)], [z0, zn(k)], ' g', 'linewidth', 1.2);
% plot([ray2.x, xn(k)], [ray2.z, zn(k)], '-- m', 'linewidth', 1.2);
end
% plot([x0, xn(k)], [z0, zn(k)], '* m', 'linewidth', 1.2);
end
% if(k==2 || k==3)
% for i=1:length(surfaces)
% [xn1(i),zn1(i),s1(i), valid1(i)] = ...
% surfaces(i).intersection(ray1, surfaces(i), variables);
% [xn2(i),zn2(i),s2(i), valid2(i)] = ...
% surfaces(i).intersection(ray2, surfaces(i), variables);
%
% end
% [k1] = distances(xn1,zn1,ray1,s1,valid1);
% [k2] = distances(xn2,zn2,ray2, s2,valid2);
% plot([ray1.x, xn1(k1)], [ray1.z, zn1(k1)], '-- c')
% plot([ray2.x, xn2(k2)], [ray2.z, zn2(k2)], '-- b')
% end
% if(R == 1)
% figure(1)
% hold on
% plot([x0, xn(k)], [z0, zn(k)], ' m', 'linewidth', 1.2);
% end
end % end while
% xout = xn(k);
%if(k~=7)
zout = zn(k);
thetaout = ray.sz;
last_surface = k;
% else
% xout= 0;
% zout = 0;
% thetaout = tau;
% last_surface = k;
% end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
bisection_method.m
|
.m
|
ray-mapping-fresnel-lens-master/bisection_method.m
| 2,217 |
utf_8
|
7b0f651017dede5a9b1f9528a7c54b28
|
% This function uses the bisection method top find the rays with
% the same number of reflections of A
function [C1, targetC1,pathC1, C2, targetC2, pathC2] = ...
bisection_method(A, B, targetA,targetB, pathA, surfaces, ...
action, variables)
%pathA = [pathA, A.surface];
toll = 1e-12;
pathB = 4;
while(abs(targetA.z-targetB.z)>toll)
% Consider the middle point between targetA.x and targetB.x
pathM = 4;
K = 0;
targetM.z = (targetA.z + targetB.z)/2;
targetM.x = targetA.x;
targetM.sx = targetA.sx;
targetM.sz = targetA.sz;
targetM.n = 1;
targetM.surface = -1;
targetM.I = 1;
M = targetM;
M.I = 1;
i = 2;
while (i <=length(pathA))
Mr = M;
Mt = M;
% Do ray tracing for target M
[Mr,Mt, RM, TM] = raytracing(M, surfaces, variables);
K = length(pathM);
if(action(K)==1)
M = Mt;
M.I = Mt.T;
if(Mr.n==1)
M.n = 1.5;
else
M.n = 1;
end
else
M = Mr;
M.I = Mr.R;
if(Mr.n==1)
M.n = 1;
else
M.n = 1.5;
end
end
if(isempty(M))
i = length(pathA);
else
if((M.surface==1) || (M.surface==4) ...
|| (M.surface==5)|| (M.surface==6) || (M.surface==7))
pathM = [pathM, M.surface];
i = length(pathA);
else
pathM = [pathM, M.surface];
end
i = i+1;
end
end
if(isequal(pathA,pathM))
A = M;
targetA = targetM;
pathA = pathM;
RA = RM;
TA = TM;
else
% if(A.surface~=M.surface)
B = M;
targetB = targetM;
RB = RM;
TB = TM;
pathB = pathM;
end
% figure(2)
% hold on
% plot(targetA.x, targetA.sx, '*', targetB.x, targetB.sx, '*')
% drawnow
end
C2 = B;
targetC2 = targetB;
pathC2 = pathB;
C1 = A;
targetC1 = targetA;
pathC1 = pathA;
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
reflect.m
|
.m
|
ray-mapping-fresnel-lens-master/reflect.m
| 1,118 |
utf_8
|
8c88c4d9eac2b5335667033ce177209b
|
% This function computes the direction of the reflected ray
function [ray] = reflect(ray, surface, k)
% Compute the normal to the surface "cup"
h = 5;
l = 10;
d = 0.5;
r = sqrt((l-d)^2+h^2);
if(k==2|| k==3)
n = 1.5;
L = r + n*d;
A = (1-n^2);
B = 2*n*(n*l-L);
C = ray.z^2-L^2+2*n*L*l-n^2*l^2;
rad = sqrt(B^2-4*A*C);
if( rad~=0)
if(surface.xmin<l)
der = (2*ray.z)/rad;
else
der = -(2*ray.z)/rad;
end
normal = [-der 1]./sqrt(der^2+1);
else
normal = [0 1];
end
else
normal = [0 1];
end
% rays: ray direction
rays = [ray.sz; ray.sx];
if (dot(normal,rays)<0)
normal = -normal;
end;
ray.normal = normal;
% Consider always a normal directed inside the optical system
% if (dot(normal,rays)<0)
% normal=-normal;
% end;
% Compute the reflection law to calculate the new direction
alpha = 1;
beta = -2*dot(normal,rays);
ray.sz = alpha*ray.sz+beta*normal(1);
ray.sx = alpha*ray.sx+beta*normal(2);
R = 1;
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
ellipse_intersection.m
|
.m
|
ray-mapping-fresnel-lens-master/ellipse_intersection.m
| 3,981 |
utf_8
|
8cc25ad3977848522ba6a5bc7cb55191
|
% This function computes the intersection between the ray and the ellips
% with axis a and b where a<b
function [xn,zn, s, valid] = ellipse_intersection(ray, surface, variables)
graph = 0;
s = 0;
% Plot the ray on the surface
if graph
% figure(7)
% hold on
% plot(ray.x, ray.z , ' * y')
end
valid = 0;
% Parameters of the lens
% h = 5;
% l = 10;
% d = 0.5;
% r = sqrt((l-d)^2+h^2);
% n = 1.5;
% L = r + n*d;
n = variables.n;
l = variables.l;
L = variables.L;
% Coefficients of the second order equation of the left reflector
A =(1-n^2)*ray.sx^2+ray.sz^2;
B = 2*(1-n^2)*ray.x*ray.sx+2*n*(n*l-L)*ray.sx+2*ray.z*ray.sz;
C = (1-n^2)*ray.x^2+2*n*(n*l-L)*ray.x+ray.z^2-L^2+2*n*l*L-n^2*l^2;
% Coefficients for the second order equation of the right reflector
A1 = (1-n^2)*ray.sx^2+ray.sz^2;
B1 = 2*(1-n^2)*ray.x*ray.sx-4*l*(1-n^2)*ray.sx-2*n*(n*l-L)*ray.sx+2*ray.sz*ray.z;
C1 = (1-n^2)*ray.x^2-4*l*(1-n^2)*ray.x+4*l^2*(1-n^2)-2*n*(n*l-L)*ray.x+...
4*n*l*(n*l-L)+ray.z^2-L^2+2*n*l*L-n^2*l^2;
if(surface.xmin<l)
% Arc length of the left reflector
s1 = (-B+sqrt(B^2-4*A*C))/(2*A);
s2 = (-B-sqrt(B^2-4*A*C))/(2*A);
xn1 = ray.x+s1*ray.sx;
zn1 = ray.z+s1*ray.sz;
xn2 = ray.x+s2*ray.sx;
zn2 = ray.z+s2*ray.sz;
else
% Arc length of the right reflector
% if(B1^2-4*A1*C1<0)
% disp('Error')
% end
s1 = (-B1+sqrt(B1^2-4*A1*C1))/(2*A1);
s2 = (-B1-sqrt(B1^2-4*A1*C1))/(2*A1);
xn1 = ray.x+s1*ray.sx;
zn1 = ray.z+s1*ray.sz;
xn2 = ray.x+s2*ray.sx;
zn2 = ray.z+s2*ray.sz;
end
eps = 10^-8;
%if((xn1-surface.xmin>=-eps)&& (xn1-surface.xmax<=eps)) && ...
if((zn1-surface.zmin>=-eps) && (zn1-surface.zmax<=eps))
% && ...
% sqrt((xn-ray.x)^2+(zn-ray.z)^2)>=0)
% if ((xn-cpc.xmin>=0) || (xn-cpc.xmin>=-eps && xn-cpc.xmin<=0)) && ...
% ((xn-cpc.xmax<=0)||(xn-cpc.xmax<=eps && xn-cpc.xmax>=0))
if(surface.xmin<l)
A1 = (1-n^2);
B1 = 2*n*(n*l-L);
C1 = zn1.^2-L^2+2*n*L*l-n^2*l^2;
x1 = (-B1-sqrt(B1^2-4*A1*C1))/(2*A1);
else
A1 = (1-n^2);
B1 = 2*n*(n*l-L);
C1 = zn1.^2-L^2+2*n*L*l-n^2*l^2;
x1 = -(-B1-sqrt(B1^2-4*A1*C1))/(2*A1)+2*l;
end
if (abs(x1-xn1)<=10^-6)
valid1 = 1;
xn1 = x1;
else
valid1 = 0;
end
else
valid1=0;
end;
if(valid1==1)
s = s1;
xn = xn1;
zn = zn1;
end
%if((xn2-surface.xmin>=-eps)&& (xn2-surface.xmax<=eps)) % && ...
if((zn2-surface.zmin>=-eps) && (zn2-surface.zmax<=eps)) % && ...
% sqrt((xn1-ray.x)^2+(zn1-ray.z)^2)>=0)
% if ((xn1-cpc.xmin>=0) || (xn1-cpc.xmin>=-eps && xn1-cpc.xmin<=0)) && ...
% ((xn1-cpc.xmax<=0)||(xn1-cpc.xmax<=eps && xn1-cpc.xmax>=0))
if(surface.xmin<l)
A1 = (1-n^2);
B1 = 2*n*(n*l-L);
C1 = zn2^2-L^2+2*n*L*l-n^2*l^2;
x2 = (-B1-sqrt(B1^2-4*A1*C1))/(2*A1);
else
A1 = (1-n^2);
B1 = 2*n*(n*l-L);
C1 = zn2^2-L^2+2*n*L*l-n^2*l^2;
x2 = -(-B1-sqrt(B1^2-4*A1*C1))/(2*A1)+2*l;
end
if (abs(x2-xn2)<=10^-6)
valid2 = 1;
xn2 = x2;
else
valid2 = 0;
end
else
valid2=0;
end;
if(valid1==1 && valid2 ==1)
if(xn1-ray.x==0 && zn1-ray.z==0)
% if ((xn-ray.x>=0) || (xn-ray.x>=-eps && xn-ray.x<=0)) && ...
% ((xn-ray.x<=0)||(xn-ray.x<=eps && xn-ray.x>=0))
xn = xn2;
zn = zn2;
s = s2;
valid = 1;
else
xn = xn1;
zn = zn1;
s = s1;
valid = 1;
end
elseif(valid1==1 && valid2==0)
xn = xn1;
zn = zn1;
s = s1;
valid = 1;
elseif(valid1==0 && valid2==1)
xn = xn2;
zn = zn2;
s = s2;
valid = 1;
elseif(valid1==0 && valid2==0)
xn = ray.x;
zn = ray.z;
s = -1;
valid = 0;
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
mc_fill_vector.m
|
.m
|
ray-mapping-fresnel-lens-master/mc_fill_vector.m
| 378 |
utf_8
|
2d8d00d168ede3e8206caf25b29befb5
|
% This function fills in a vector all the rays informations
function mc_fill_vector(z,t,zout,tout,path, energy)
global mc_vector
mc_vector.zin = [mc_vector.zin; z];
mc_vector.zout = [mc_vector.zout; zout];
mc_vector.tauin = [mc_vector.tauin; t];
mc_vector.tauout = [mc_vector.tauout; tout];
mc_vector.path = [mc_vector.path path];
mc_vector.energy = [mc_vector.energy energy];
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
Create_variables.m
|
.m
|
ray-mapping-fresnel-lens-master/Create_variables.m
| 336 |
utf_8
|
4910a5170d3f14ced4636ff1d69acc59
|
% This function defines the parameters that caracterize the equation of the Lens
function [variables] = Create_variables();
variables.h = 5;
variables.l = 10;
variables.d = 0.5;
variables.r = sqrt((variables.l-variables.d)^2+variables.h^2);
% index of refraction
variables.n = 1.5;
variables.L = variables.r + variables.n*variables.d;
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
ellipse_intersection1.m
|
.m
|
ray-mapping-fresnel-lens-master/ellipse_intersection1.m
| 3,651 |
utf_8
|
abd742c8b3c1d132b3ecaae306b33491
|
% This function computes the intersection between the ray and the ellips
% with axis a and b where a<b
function [xn,zn, s, valid] = ellipse_intersection1(ray, surface)
graph = 0;
s = 0;
% Plot the ray on the surface
if graph
% figure(7)
% hold on
% plot(ray.x, ray.z , ' * y')
end
valid = 0;
h = 5;
l = 10;
d = 0.5;
r = sqrt((l-d)^2+h^2);
n = 1.5;
L = r + n*d;
A0 = (1-n^2);
B0 = 2*n*(n*l-L);
%C0 = za.^2-L^2+2*n*L*l-n^2*l^2;
A =(1-n^2)*ray.sx^2+ray.sz^2;
B = (1-n^2)*ray.x*ray.sx+2*n*(n*l-L)*ray.sx+2*ray.z*ray.sz;
C = (1-n^2)*ray.x^2+2*n*(n*l-L)*ray.x+ray.z^2-L^2+2*n*l*L-n^2*l^2;
A1 =(4*A0^2)*ray.sx^2+4*A0*ray.sz^2;
B1 = (8*A0^2)*ray.x*ray.sx-4*A0*B0*ray.sx-16*A0^2*l*ray.sx+8*A0*ray.z*ray.sz;
C1 = 4*A0^2*ray.x^2-B0^2+16*A0^2*l^2+ 8*l*A0*B0-B0...
-4*A0*(2*n*l*L-n^2*l^2)-4*A0*ray.z^2;
s1 = (-B+sqrt(B^2-4*A*C))/(2*A);
s2 = (-B-sqrt(B^2-4*A*C))/(2*A);
s3 = (-B1+sqrt(B1^2-4*A1*C1))/(2*A1);
s4 = (-B1-sqrt(B1^2-4*A1*C1))/(2*A1);
if(surface.xmin<l)
xn1 = ray.x+s1*ray.sx;
zn1 = ray.z+s1*ray.sz;
xn2 = ray.x+s2*ray.sx;
zn2 = ray.z+s2*ray.sz;
else
xn1 = ray.x+s3*ray.sx;
zn1 = ray.z+s3*ray.sz;
xn2 = ray.x+s4*ray.sx;
zn2 = ray.z+s4*ray.sz;
end
eps = 10^-8;
%if((xn1-surface.xmin>=-eps)&& (xn1-surface.xmax<=eps)) && ...
if((zn1-surface.zmin>=-eps) && (zn1-surface.zmax<=eps))
% && ...
% sqrt((xn-ray.x)^2+(zn-ray.z)^2)>=0)
% if ((xn-cpc.xmin>=0) || (xn-cpc.xmin>=-eps && xn-cpc.xmin<=0)) && ...
% ((xn-cpc.xmax<=0)||(xn-cpc.xmax<=eps && xn-cpc.xmax>=0))
% if(surface.xmin<l)
% A1 = (1-n^2);
% B1 = 2*n*(n*l-L);
% C1 = zn1.^2-L^2+2*n*L*l-n^2*l^2;
% x1 = (-B1-sqrt(B1^2-4*A1*C1))/(2*A1);
% else
% A1 = (1-n^2);
% B1 = 2*n*(n*l-L);
% C1 = zn1.^2-L^2+2*n*L*l-n^2*l^2;
% x1 = -(-B1-sqrt(B1^2-4*A1*C1))/(2*A1)+2*l;
% end
if (abs(x1-xn1)<=10^-6)
valid1 = 1;
xn1 = x1;
else
valid1 = 0;
end
else
valid1=0;
end;
if(valid1==1)
s = s1;
xn = xn1;
zn = zn1;
end
%if((xn2-surface.xmin>=-eps)&& (xn2-surface.xmax<=eps)) % && ...
if((zn2-surface.zmin>=-eps) && (zn2-surface.zmax<=eps)) % && ...
% sqrt((xn1-ray.x)^2+(zn1-ray.z)^2)>=0)
% if ((xn1-cpc.xmin>=0) || (xn1-cpc.xmin>=-eps && xn1-cpc.xmin<=0)) && ...
% ((xn1-cpc.xmax<=0)||(xn1-cpc.xmax<=eps && xn1-cpc.xmax>=0))
if(surface.xmin<l)
A1 = (1-n^2);
B1 = 2*n*(n*l-L);
C1 = zn2^2-L^2+2*n*L*l-n^2*l^2;
x2 = (-B1-sqrt(B1^2-4*A1*C1))/(2*A1);
else
A1 = (1-n^2);
B1 = 2*n*(n*l-L);
C1 = zn2.^2-L^2+2*n*L*l-n^2*l^2;
x2 = -(-B1-sqrt(B1^2-4*A1*C1))/(2*A1)+2*l;
end
if (abs(x2-xn2)<=10^-6)
valid2 = 1;
xn2 = x2;
else
valid2 = 0;
end
else
valid2=0;
end;
if(valid1==1 && valid2 ==1)
if(xn1-ray.x==0 && zn1-ray.z==0)
% if ((xn-ray.x>=0) || (xn-ray.x>=-eps && xn-ray.x<=0)) && ...
% ((xn-ray.x<=0)||(xn-ray.x<=eps && xn-ray.x>=0))
xn = xn2;
zn = zn2;
s = s2;
valid = 1;
else
xn = xn1;
zn = zn1;
s = s1;
valid = 1;
end
elseif(valid1==1 && valid2==0)
xn = xn1;
zn = zn1;
s = s1;
valid = 1;
elseif(valid1==0 && valid2==1)
xn = xn2;
zn = zn2;
s = s2;
valid = 1;
elseif(valid1==0 && valid2==0)
xn = ray.x;
zn = ray.z;
s = -1;
valid = 0;
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
mc_fill_vector1.m
|
.m
|
ray-mapping-fresnel-lens-master/mc_fill_vector1.m
| 394 |
utf_8
|
c49df8c084ffa9eb34d2c981a9e0b8cc
|
% This function fills in a vector all the rays informations
function mc_fill_vector1(z,t,zout,tout,path, energy)
global mc_vector1
mc_vector1.zin = [mc_vector1.zin; z];
mc_vector1.zout = [mc_vector1.zout; zout];
mc_vector1.tauin = [mc_vector1.tauin; t];
mc_vector1.tauout = [mc_vector1.tauout; tout];
mc_vector1.path = [mc_vector1.path path];
%mc_vector1.energy = [mc_vector1.energy energy];
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
interpolation.m
|
.m
|
ray-mapping-fresnel-lens-master/interpolation.m
| 2,038 |
utf_8
|
272c270078518ec9c56ea1c9ab3f1a3a
|
% This function does an interpolation between targetA and targetB
function intensity = interpolation(intensity, targetA, targetB, ....
pathA, A, B,variables, surfaces, action)
for z = targetA.z+0.01:(targetB.z-targetA.z-0.02)/500:targetB.z-0.01
% trace the rays with z coordinates = i
% and tau coordinates = target.sz
i = 1;
targetC.z = z;
targetC.x = surfaces(4).xmax;
targetC.sx = targetA.sx;
targetC.sz = targetA.sz;
targetC.n = 1;
targetC.surface = -1;
targetC.I = 1;
C = targetC;
pathC = 4;
% Trace one ray
while (i <=length(pathA))
Cr = C;
Ct = C;
% Do ray tracing for target M
[Cr,Ct, RC, TC] = raytracing(C, surfaces, variables);
K = length(pathC);
if(action(K)==1)
C = Ct;
if(C.surface~=1)
C.I = Ct.T;
end
if(Cr.n==1)
C.n = 1.5;
else
C.n = 1;
end
else
C = Cr;
if(C.surface~=1)
C.I = Cr.R;
end
if(Cr.n==1)
C.n = 1;
else
C.n = 1.5;
end
end
if(isempty(C))
i = length(pathA);
else
if((C.surface==1) || (C.surface==4) ...
|| (C.surface==5)|| (C.surface==6) || (C.surface==7))
pathC = [pathC, C.surface];
i = length(pathC);
% if(C.surface~=1)
% intensity = [intensity, C.I];
% end
% figure(1)
% hold on
% plot(targetC.z, targetC.sz, '. r')
figure(2)
hold on
plot(targetC.z, C.I, '. b')
drawnow
else
pathC = [pathC, C.surface];
end
i = i+1;
end
end
intensity = [intensity, C.I];
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
raytracing.m
|
.m
|
ray-mapping-fresnel-lens-master/raytracing.m
| 1,732 |
utf_8
|
b6f87e6f0594e92f7ee3dc34feca39f9
|
% This function computes the ray tracing given the position and the
% direction of the ray and the optical system
function [reflected, transmitted, R, T] = ...
raytracing(ray, surfaces, variables)
k = -1;
x0 = ray.x;
z0 = ray.z;
% (x,z) = coordinates of the initial position
% ray.x = surfaces(4).x(1);
% ray.z = z;
% ray.n = 1;
% % Initial angle with respect to the optical axis
% % Ray direction
% ray.sz = tau;
% ray.sx = -sqrt(1-ray.sz^2);
% store initial conditions for debugging
% ray.n=1; % we start in air
% s = parameter for the ray parameterization
s = zeros(length(surfaces) ,1);
xn = zeros(length(surfaces) ,1); % xn(i) = x-s(i)*sin(theta)
zn = zeros(length(surfaces) ,1); % zn(i) = z+s(i)*cos(theta)
for i=1:length(surfaces)
[xn(i),zn(i),s(i), valid(i)] = ...
surfaces(i).intersection(ray, surfaces(i), variables);
end
%plot(xn(k), zn(k), '*')
[k] = distances(xn,zn,ray,s,valid);
if(k==-1)
% disp('Error')
end
% disp([' closest intersection from surface ',num2str(k),' ',surfaces(k).name]);
% (x,z) = coordinates of the closer intersection
if(k~=7)
ray.x = xn(k);
ray.z = zn(k);
ray.surface = k;
% figure(4)
% hold on
% plot([x0, xn(k)], [z0, zn(k)], ' g', 'linewidth', 1.2);
[reflected, transmitted, R, T] = surfaces(k).action(ray,surfaces(k),...
k,variables);
else
ray.surface = k;
R = 0;
T = 0;
reflected = ray;
transmitted = ray;
if(ray.n==1)
transmitted.n=1.5;
else
transmitted.n=1;
end
end
% if(R==0 || T==0)
% disp('R or T is 0')
% end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
intensity_computation.m
|
.m
|
ray-mapping-fresnel-lens-master/intensity_computation.m
| 6,646 |
utf_8
|
a76e39fb7277d62f8e82866962e15983
|
% This function computes the intensity at the target
% along a given direction it considers
function intensity = intensity_computation(A, B, targetA, targetB,...
pathA,pathB,surfaces, action, variables,...
intensity)
max_number_of_reflections = 4;
% If A and B are on the same line
% (this is always true at the first step as both start from the target
if(A.surface==B.surface)
if(A.surface==1)
if(A.n==1.5)
% Compute the intensity
% intensity = intensity + abs(targetA.x-targetB.x);
if(isequal(pathA, [4,3,2,1]))
% figure(1)
% plot([targetA.z, targetB.z],[targetA.sz, targetB.sz],'* r')
% hold on
% drawnow
% disp(['pathA ', num2str(pathA)]);
% disp(['pathB ', num2str(pathB)]);
intensity = [intensity, A.I];
intensity = interpolation(intensity, targetA, targetB, ....
pathA, A, B,variables, surfaces, action);
intensity = [intensity, B.I];
% if(A.R ~=0 && A.R ~=1)
% A.R;
% A.T;
% B.R;
% B.T;
% end
% disp(['RA ', num2str(RA)]); disp(['TA ', num2str(TA)]);
% disp(['RA+TA ', num2str(RA+TA)]);
end
else
% % A not physical path is found
% % Discard those rays
intensity = intensity;
end
else % (if the source is not reached yet)
% and if nether the target nor the reflectors are hit again
% if(length(pathA)==6)
% figure(1)
% plot([targetA.z, targetB.z],[targetA.sz, targetB.sz],'. b')
% end
if((A.surface~=4) && (A.surface~=5)...
&& (A.surface~=6) && (A.surface~=7))
% If the maximum number of reflection is not reached
if(length(pathA)<max_number_of_reflections)
% Trace back the rays A and B
% For both of them compute both the reflected and
% the transmitted ray.
% Calculate the reflectance and the transmittance
if(A.surface~=1)
[Ar, At, RA, TA] = raytracing(A, surfaces, variables);
[Br, Bt, RB, TB] = raytracing(B, surfaces, variables);
% At.I = A.I*TA;
pathA = [pathA, At.surface];
pathB = [pathB, Bt.surface];
K = length(pathA)-1;
end
if(K>length(action))
disp('Error')
% K
end
if(action(K)==1)
if(At.surface~=1)&&(Bt.surface~=1)
At.I = A.I*TA;
Bt.I = B.I*TB;
end
intensity = intensity_computation(At, Bt, targetA,...
targetB, pathA,pathB, surfaces, action, ...
variables, intensity);
else
if(At.surface~=1)&&(Bt.surface~=1)
Ar.I = A.I*RA;
Br.I = B.I*RB;
end
intensity = intensity_computation(Ar, Br, targetA,...
targetB, pathA,pathB,surfaces, action, ...
variables, intensity);
end
else
% If the maximum number of reflection is reached
% then the contribution to the intensity is negligible
intensity = intensity;
end
else % if the ray hits either the target again or
% one of the reflectors stop the procedure
intensity = intensity;
end
end
% If A and B hit two different surfaces
elseif(A.surface~=B.surface)
% If the maximum number of reflection is not reached yet
if(length(pathA)<=max_number_of_reflections)
% Do bisection to find the ray C1 with the same path of A
% The ray C2 has a different path
% targetC1 and targetC2 are the coordinates of the found
% rays at the target
% C1 and C2 are the coordinates of the rays at the last surface
% that they hit, for C1 this is equal to pathA(end) for C1
[C1, targetC1,pathC1, C2, targetC2, pathC2] = ...
bisection_method(A, B, targetA,...
targetB, pathA, surfaces, action, variables);
% If there is an interval at the left of ray A
% If the target and the reflectors are not reache yet
if((A.surface~=4) && (A.surface~=5)...
&& (A.surface~=6) && (A.surface~=7) )
if(~isequal(pathA, pathC1))
disp(['pathA ', num2str(pathA)]);
disp(['pathC1 ', num2str(pathC1)]);
end
% Recall the function for the rays with the same path
intensity = intensity_computation(A, C1, targetA,...
targetC1, pathA,pathC1,surfaces, ...
action, variables, intensity);
else
% If the rays hit either the target or the reflectors again
% discard those rays
intensity = intensity;
end
% Recall the function for the rays with a different path
intensity = intensity_computation(C2, B, targetC2,...
targetB, pathC2,pathB, surfaces, ...
action, variables, intensity);
else % (if the maximum number of reflection is reached)
% The contribution to the intensity given by those rays is
% negligible
intensity = intensity;
end
end
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
new_distances.m
|
.m
|
ray-mapping-fresnel-lens-master/new_distances.m
| 1,347 |
utf_8
|
4829f3d1201529d0a875fd2764111c1e
|
% This functions calculates the number of the
% next surface that the ray hit
function [k] = new_distances(xn,zn,ray,s,valid)
N=length(xn);
% d = vector with the distances between the ray
% and all the intersection points of the ray
% with the optical lines
d = sqrt((xn-ray.x).^2+(zn-ray.z).^2);
t = 1;
% valid distances is a vector with the following components:
% 1. the distance between the ray and the line that it leaves (around 0)
% 2. the distance between the ray and the next line it hits
% 3. -1 for the others intersections
for j = 1:N
if(valid(j)==1 && s(j)>=0)
valid_distances(t) = d(j);
else
valid_distances(t) = -1;
end
t = t+1;
end
% d
% valid_distances
[dmax,k] = max(valid_distances);
if(dmax~=-1)
k=k;
else
k=4;
end
% count = 0;
% distances = valid_distances;
% y = find(valid_distances==-1);
% distances(y) = [];
% for i = 1:length(valid_distances)
% if(valid_distances(i) ~= -1 && i~=ray.surface && ray.surface~=-1)
% count = count+1;
% end
% end
% if(count==1)
% [dmax,k] = max(valid_distances);
% else
% [dmax, k] = min(distances);
% k = find(valid_distances==dmax);
% end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
distances.m
|
.m
|
ray-mapping-fresnel-lens-master/distances.m
| 1,841 |
utf_8
|
ea49434cacd67c7297546090b45388d3
|
% This function computes the distances between the initial position of
% the ray and all crossing points of the ray with the 10 surfaces of the
% TIR-collimator.
% It also computes the minimal distance
% (without considering distances = 0 and negative directions)
% Meaning of the most important variables
% d(t) = distance from the initial surface to the surface t (10x1 vector)
% dmin = minim distance
% s = parameter of the ray parameterization (10x1 vector)
% k = index of the minimal distance
function [k] = distances(xn,zn,ray,s, valid)
N=length(xn);
d = sqrt((xn-ray.x).^2+(zn-ray.z).^2);
epsilon_d = 1.0e-11;
% epsilon = 1.0e-7;
t = 1;
k = -1;
dmin = 0;
epsilon_s = 10^-15;
% first find a surface for which there is at least a relevant stepsize..
while (dmin<epsilon_d && t<=N)
if (valid(t)==1 && s(t)>=epsilon_s)
dmin=d(t);
k=t;
end;
t=t+1;
end
if(k==7)
dip('Error');
end
% give an error message if we are above the maximum number of surfaces
if (t>N+1)
error(['not a distance larger than ',num2str(epsilon_d),' found']);
end;
for j=t:N
if (d(j)>epsilon_d && d(j)<dmin && valid(j)==1 && s(j)>=epsilon_s)
dmin = d(j);
k = j;
end
end
if (k<0 && t>N)
k = 7;
disp(['no crossing found! number of surfaces ',num2str(t)]);
% disp(['ray.x0 ',num2str(ray.x0),' ray.z0 ',num2str(ray.z0)]);
% disp(['ray.sx0 ',num2str(ray.sx0),' ray.sz0 ',num2str(ray.sz0)]);
% disp(['ray.n ',num2str(ray.n)]);
% error('no crossing found!');
% pause
% plot([ray.x ,ray.normal(1)+ray.x], [ray.z,ray.normal(2)+ray.z],'m')
% plot(x,z,'c')
% plot([ray.x ray.x+ray.sx],[ray.z ray.z+ray.sz],'c');
end;
% level=1;
end
|
github
|
melaniafilosa/ray-mapping-fresnel-lens-master
|
line_intersection.m
|
.m
|
ray-mapping-fresnel-lens-master/line_intersection.m
| 1,047 |
utf_8
|
7e92fa1a4d5db606d99367f88076f9a6
|
% This function compute the intersection point between the source and the
% rays
% s = parameter for the ray parameterization
% (x,z) = coordinates of the initial point
% theta = initial angle with respect to the normal of the surface
% xn = x- s*sin(theta) := x-coordinate of the intersection point
% zn = z+ s*cos(theta) := z-coordinate of the intersection point
% i = index of the surface hit
function [xn,zn,s, valid] = line_intersection(ray,surfaces, variables)
num = (ray.z-surfaces.z(1))*(surfaces.x(2)-surfaces.x(1))- ...
(ray.x-surfaces.x(1))*(surfaces.z(2)-surfaces.z(1));
den = ray.sx*(surfaces.z(2)-surfaces.z(1))- ...
ray.sz*(surfaces.x(2)-surfaces.x(1));
s = num/den;
xn = ray.x+s*ray.sx;
zn = ray.z+s*ray.sz;
% check if valid crossing (between -2 and 2 in x direction)
if (surfaces.xmin~=surfaces.xmax)
if (xn>surfaces.xmin && xn<surfaces.xmax)
valid=1;
else
valid=0;
end;
else
if (zn>surfaces.zmin && zn<surfaces.zmax)
valid=1;
else
valid=0;
end;
end;
|
github
|
hsun2022/CrowdComputing-master
|
crowd_model.m
|
.m
|
CrowdComputing-master/seek-plus/crowd_model.m
| 1,678 |
utf_8
|
bc956c57d0029eb0368c986c92744497
|
function model = crowd_model(L,varargin)
%%parameters....
Ntask =size(L,1);
Nwork=size(L,2);
%neiborhods
NeibTask = cell(1,Ntask);
for task_j = 1:Ntask
NeibTask{task_j} = find(L(task_j,:));
end
NeibWork = cell(Nwork,1);
for work_i = 1:Nwork
NeibWork{work_i} = find(L(:,work_i))';
end
model=init_model();
LabelTask=cell(1,Ntask);
for task_j = 1:Ntask,
LabelTask{task_j} = L(task_j, NeibTask{task_j}); % the labels of the same task should have the same dimension
end
LjDomain=cell(1,Ntask);
for task_j=1:Ntask
LjDomain{task_j} = unique(LabelTask{task_j});
end
LabelWork=cell(Nwork,1);
for work_i = 1:Nwork,
LabelWork{work_i} = L(NeibWork{work_i},work_i)'; % the labels of the same task should have the same dimension
end
LabelDomain = unique(L(L~=0));
model.LabelDomain = LabelDomain(:)';
model.Ndom = length(LabelDomain);
model.LabelTask=LabelTask;
model.LabelWork=LabelWork;
model.LjDomain=LjDomain;
model.Ntask = Ntask;
model.Nwork = Nwork;
model.NeibTask = NeibTask;
model.NeibWork = NeibWork;
model.L=L;
if ~isempty(varargin)
model.true_labels=varargin{1};
end
end
function model = init_model()
model.L= []; %: [5000x5000 double]
model.LabelTask= []; %: {1x5000 cell}
model.LjDomain= [];
model.LabelWork= []; %: {1x5000 cell}
model.LabelDomain= []; %: [1 2]
model.Ntask= []; %: 5000
model.Nwork= []; %: 5000
model.Ndom= []; %: [1 2]
model.NeibTask= []; %: {1x5000 cell}
model.NeibWork= []; %: {1x5000 cell}
model.true_labels= []; %: [1x5000 double]
return;
end
|
github
|
hsun2022/CrowdComputing-master
|
L_simulation_noNoise.m
|
.m
|
CrowdComputing-master/seek-plus/L_simulation_noNoise.m
| 994 |
utf_8
|
f24a6a31d78cb2b78138be45ee2fde8a
|
function [L,groundtruth] = L_simulation_noNoise(Ntask,Nworker,Ndom,Redun,ndom)
p0 = 0.05;
p1 = 0.75;
%prop = 0.5;
groundtruth = zeros(1,Ntask);
L = zeros(Ntask,Nworker);
for task_j = 1:Ntask
labelSet = randperm(Ndom,ndom);
groundtruth(task_j) = randsrc(1,1,labelSet);
prob = zeros(1,ndom);
for k = 1:ndom
dom_k = labelSet(k);
if isHypernym(dom_k,groundtruth(task_j))
prob(k) = p1/(1-p1);
elseif dom_k == groundtruth(task_j)
prob(k) = ndom-1;
else
prob(k) = p0/(1-p0);
end
end
workerSet = randperm(Nworker,Redun);
for i = 1:Redun
worker_i = workerSet(i);
prob = prob/sum(prob);
L(task_j,worker_i) = randsrc(1,1,[labelSet;prob]);
end
end
end
function flag = isHypernym(i,j)
% To confirm i is or not j's hypernym.
if i > floor(j/2)
flag = 0;
elseif i == floor(j/2)
flag = 1;
else
flag = isHypernym(i,floor(j/2));
end
end
|
github
|
hsun2022/CrowdComputing-master
|
SEEK_lnr_norm_semi.m
|
.m
|
CrowdComputing-master/seek-plus/SEEK_lnr_norm_semi.m
| 7,277 |
utf_8
|
800a43c9f98e78f632f301e31ef7c729
|
function result = SEEK_lnr_norm_semi(model, KnowledgeMatrix,groundTruthFlag)
maxIter = 20;
TOL = 1e-6;
global L NeibTask NeibWork LabelDomain Relation Ntask Nwork Ndom LabelTask LabelWork LjDomain groundTruth Flag bias
Ntask = model.Ntask;
Nwork = model.Nwork;
Ndom = model.Ndom;
NeibTask = model.NeibTask;
NeibWork = model.NeibWork;
LabelDomain = model.LabelDomain;
Relation = KnowledgeMatrix;
L = model.L;
LabelTask = model.LabelTask;
LabelWork = model.LabelWork;
LjDomain = model.LjDomain;
groundTruth = model.true_labels;
Flag = groundTruthFlag;
bias = 0.0001;
Nflag = sum(Flag);
majority = MajorityVote(model);
ansLabel = majority.ans_labels;
result.majorityAnsLabel = ansLabel;
if ~isempty(model.true_labels)
result.majorityAccuracy = sum(~(ansLabel-model.true_labels))/Ntask;
end
err = NaN;
Ability = zeros(1,Nwork);
Simplicity = zeros(1,Ntask);
for iter = 1:maxIter
if err < TOL
break;
elseif iter >=maxIter
% disp('iter in main function reached to maxIter');
break;
end
p_lt = Estep(Ability, Simplicity);
% obj = Aux(Ability,Simplicity,p_lt);
% disp(['object in Estep is: ',num2str(obj)]);
[Ability_tem,Simplicity_tem] = Mstep(Ability, Simplicity, p_lt);
err = (sum(abs(Ability_tem-Ability))+sum(abs(Ability_tem-Ability)))/(Ntask+Nwork);
Ability = Ability_tem;
Simplicity = Simplicity_tem;
% obj = Aux(Ability,Simplicity,p_lt);
% disp(['object in Mstep is: ',num2str(obj)]);
end
L_anslabel = ones(1,Ntask);
for task_j = 1:Ntask
[~, I] = max(p_lt{task_j});
L_anslabel(task_j) = LjDomain{task_j}(I);
end
if ~isempty(model.true_labels)
result.accuracy = sum(~(L_anslabel-model.true_labels))/Ntask;
result.FaultLabelIndex = find(L_anslabel-model.true_labels);
result.accuracy_unlabeled = (result.accuracy-Nflag/Ntask)/(1-Nflag/Ntask);
end
result.anslabel=L_anslabel;
end
function p_lt = Estep(Ability, Simplicity)
global NeibTask LabelTask LjDomain Ntask Nwork Relation groundTruth Flag bias
p_lij = cell(Ntask,Nwork);
p_lt = cell(1,Ntask);
for task_j = 1:Ntask
LjD = LjDomain{task_j};
NumLjD = length(LjD);
p_lt{task_j} = ones(1,NumLjD);
if Flag(task_j) == 1
for k = 1:NumLjD
if LjD(k) == groundTruth(task_j)
p_lt{task_j}(k) = 1;
else
p_lt{task_j}(k) = 0;
end
end
continue;
end
workerList = NeibTask{task_j};
labelList = LabelTask{task_j};
Nworker_j = length(workerList);
for i = 1:Nworker_j
worker_i = workerList(i);
lij = labelList(i);
lij_index = find(LjD==lij,1);
p_lij{task_j,worker_i} = zeros(NumLjD,NumLjD);
for k = 1:NumLjD
for k2 = 1:NumLjD
if k == k2
p_lij{task_j,worker_i}(k2,k) = (NumLjD-1+bias)*exp(Ability(worker_i)+Simplicity(task_j)+Relation(LjD(k2),LjD(k)));
else
p_lij{task_j,worker_i}(k2,k) = exp(Relation(LjD(k2),LjD(k)));
end
end
p_lij{task_j,worker_i}(:,k) = p_lij{task_j,worker_i}(:,k)/sum(p_lij{task_j,worker_i}(:,k));
p_lt{task_j}(k) = p_lt{task_j}(k)*p_lij{task_j,worker_i}(lij_index,k);
end
end
p_lt{task_j} = p_lt{task_j}/sum(p_lt{task_j});
end
end
function [Ability, Simplicity] = Mstep(oldAbility, oldSimplicity, p_lt)
global Ntask Nwork
err = NaN;
maxIter = 10;
TOL = 1e-6;
Ability = oldAbility;
Simplicity = oldSimplicity;
for iter = 1:maxIter
if err < TOL
return;
elseif iter >= maxIter
% disp('iter reachs to the maxIter in Mstep')
end
obj_old = Aux(oldAbility,oldSimplicity,p_lt);
[A_gradient,S_gradient] = gradient(oldAbility,oldSimplicity,p_lt);
alpha = 0.5;
for iter2 = 1:maxIter
if iter2 >= maxIter
A_gradient
S_gradient
error('error in gradient');
end
Ability = oldAbility +alpha*A_gradient;
Simplicity = oldSimplicity + alpha*S_gradient;
obj = Aux(Ability,Simplicity,p_lt);
if obj >= obj_old
break;
else
alpha = alpha/4;
end
end
err = (sum(abs(Ability-oldAbility))+sum(abs(Simplicity-oldSimplicity)))/(Ntask+Nwork);
oldAbility = Ability;
oldSimplicity = Simplicity;
end
end
function [A_gradient,S_gradient] = gradient(Ability,Simplicity,p_lt)
global Ntask Nwork LjDomain Relation NeibTask LabelTask bias
A_gradient = zeros(1,Nwork);
S_gradient = zeros(1,Ntask);
for task_j = 1:Ntask
LjD = LjDomain{task_j};
NumLjD = length(LjD);
workerList = NeibTask{task_j};
labelList = LabelTask{task_j};
NumWorker = length(workerList);
for i = 1:NumWorker
worker_i = workerList(i);
lij = labelList(i);
item = 0;
for k = 1:NumLjD
groundTruth = LjD(k);
tem = 0;
for k2 = 1:NumLjD
if LjD(k2) == groundTruth
main_tem = (NumLjD-1+bias)*exp(Ability(worker_i)+Simplicity(task_j)+Relation(groundTruth,groundTruth));
else
tem = tem + exp(Relation(LjD(k2),groundTruth));
end
end
pro_main = main_tem/(main_tem+tem);
if groundTruth == lij
item = item + p_lt{task_j}(k) - p_lt{task_j}(k)*pro_main;
else
item = item -p_lt{task_j}(k)*pro_main;
end
end
A_gradient(worker_i) = A_gradient(worker_i) + item;
S_gradient(task_j) = S_gradient(task_j) + item;
end
end
A_gradient = A_gradient - Ability;
S_gradient = S_gradient - Simplicity;
end
function obj = Aux(Ability,Simplicity,p_lt)
global NeibTask LabelTask Relation Nwork Ntask LjDomain Flag bias
part1 = 0;
part2 = 0;
part3 = 0;
B_reciprocal = cell(Ntask,Nwork);
for task_j = 1:Ntask
workerList = NeibTask{task_j};
labelList = LabelTask{task_j};
LjD = LjDomain{task_j};
NumLjD = length(LjD);
NumWorker = length(workerList);
for k = 1:NumLjD
if Flag(task_j) == 1
break;
end
part1 = part1 - p_lt{task_j}(k)*log(NumLjD*p_lt{task_j}(k));
end
for i = 1:NumWorker
worker_i = workerList(i);
lij = labelList(i);
B_reciprocal{task_j,worker_i} = zeros(1,NumLjD);
for k = 1:NumLjD
groundTruth = LjD(k);
for k2 = 1:NumLjD
if k2 == k
B_reciprocal{task_j,worker_i}(k) = B_reciprocal{task_j,worker_i}(k) + (NumLjD-1+bias)*exp(Ability(worker_i)+Simplicity(task_j)+Relation(groundTruth,groundTruth));
else
B_reciprocal{task_j,worker_i}(k) = B_reciprocal{task_j,worker_i}(k) + exp(Relation(LjD(k2),groundTruth));
end
end
part2 = part2 + p_lt{task_j}(k)*(Relation(lij,groundTruth)-log(B_reciprocal{task_j,worker_i}(k)));
if lij == groundTruth
part2 = part2 + p_lt{task_j}(k)*(Ability(worker_i)+Simplicity(task_j)+log(NumLjD-1+bias));
end
end
end
end
for task_j = 1:Ntask
part3 = part3 - Simplicity(task_j)^2/2;
end
for worker_i = 1:Nwork
part3 = part3 - Ability(worker_i)^2/2;
end
obj = part1 + part2 + part3;
end
|
github
|
shuangshuangguo/dense_flow-master
|
extractOpticalFlow_gpu.m
|
.m
|
dense_flow-master/matlab/extractOpticalFlow_gpu.m
| 1,645 |
utf_8
|
e184fc7aad7743036e394d6b08ba37f9
|
function [] = extractOpticalFlow_gpu(index, device_id, type)
% path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/';
% if type ==0
% path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_farn_gpu_step_2/';
% elseif type ==1
% path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_tvl1_gpu_step_2/';
% else
% path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_brox_gpu_step_2/';
% end
path1 = '/nfs/lmwang/lmwang/Data/HMDB51/hmdb51_org/';
if type ==0
path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_farn_gpu/';
elseif type ==1
path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_tvl1_gpu/';
else
path2 = '/media/sdb/lmwang/data/HMDB51/hmdb51_flow_img_brox_gpu/';
end
folderlist = dir(path1);
foldername = {folderlist(:).name};
foldername = setdiff(foldername,{'.','..'});
for i = index
if ~exist([path2,foldername{i}],'dir')
mkdir([path2,foldername{i}]);
end
filelist = dir([path1,foldername{i},'/*.avi']);
for j = 1:length(filelist)
if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir')
mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]);
end
file1 = [path1,foldername{i},'/',filelist(j).name];
file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x'];
file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y'];
file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i'];
cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20 -t %d -d %d -s %d',...
file1,file2,file3,file4,type,device_id,1);
system(cmd);
end
i
end
end
|
github
|
shuangshuangguo/dense_flow-master
|
extracOpticalFlow.m
|
.m
|
dense_flow-master/matlab/extracOpticalFlow.m
| 1,034 |
utf_8
|
87c098785c996cfa862cd7e84742994e
|
function [] = extracOpticalFlow(index)
path1 = '/home/lmwang/data/UCF/ucf101_org/';
path2 = '/home/lmwang/data/UCF/ucf101_warp_flow_img/';
folderlist = dir(path1);
foldername = {folderlist(:).name};
foldername = setdiff(foldername,{'.','..'});
for i = index
if ~exist([path2,foldername{i}],'dir')
mkdir([path2,foldername{i}]);
end
filelist = dir([path1,foldername{i},'/*.avi']);
for j = 1:length(filelist)
if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir')
mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]);
end
file1 = [path1,foldername{i},'/',filelist(j).name];
file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x'];
file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y'];
file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i'];
cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4);
system(cmd);
end
i
end
end
|
github
|
shuangshuangguo/dense_flow-master
|
extractOpticalFlow.m
|
.m
|
dense_flow-master/matlab/extractOpticalFlow.m
| 1,042 |
utf_8
|
e73edca68bee408e232e58e19e2aae1b
|
function [] = extractOpticalFlow(index)
path1 = '/nfs/lmwang/lmwang/Data/UCF101/ucf101_org/';
path2 = '/media/sdb/lmwang/data/UCF101/ucf101_flow_img_TV/';
folderlist = dir(path1);
foldername = {folderlist(:).name};
foldername = setdiff(foldername,{'.','..'});
for i = index
if ~exist([path2,foldername{i}],'dir')
mkdir([path2,foldername{i}]);
end
filelist = dir([path1,foldername{i},'/*.avi']);
for j = 1:length(filelist)
if ~exist([path2,foldername{i},'/',filelist(j).name(1:end-4)],'dir')
mkdir([path2,foldername{i},'/',filelist(j).name(1:end-4)]);
end
file1 = [path1,foldername{i},'/',filelist(j).name];
file2 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_x'];
file3 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_y'];
file4 = [path2,foldername{i},'/',filelist(j).name(1:end-4),'/','flow_i'];
cmd = sprintf('./extract_gpu -f %s -x %s -y %s -i %s -b 20',file1,file2,file3,file4);
system(cmd);
end
i
end
end
|
github
|
Reasat/cr-comp-master
|
gen_PU_PSK.m
|
.m
|
cr-comp-master/channel_allocation_scheduling/gen_PU_PSK.m
| 2,764 |
utf_8
|
b1bb1d3a1b9bc90924170e535d1df534
|
% initial sample of transmitted signal is assumed zero but pu tx state is
% assumed busy, fix it later
function [ch_tx,t_ch, pu_state]=gen_PU_PSK(T,lambda,Fs,M,hpsk)
%% Creating PU activity
Ts=1/Fs;
old = digits(3); % specify number of significant decimal digits
Ts=double(vpa(Ts));
digits(old);%Restore the default accuracy setting for further computations
state=randi(2,1,1)-1; % state= 1==>busy
% state= 0==>idle
seq=state; % list of transition between states busy/idle
emission=-1*log(1-rand)/lambda(2);% amount of time the channel will be busy
emission=floor(emission/Ts)*Ts;
while sum(emission)<T
if state==1% if busy toggle
state=0;% make idle
seq=[seq,state];
temp_busy=-1*log(1-rand)/lambda(1);
temp_busy=floor(temp_busy/Ts)*Ts;
emission=[emission temp_busy];
else if state==0% if idle toggle
state=1;% make busy
seq=[seq,state];
temp_idle=-1*log(1-rand)/lambda(2);
temp_idle=floor(temp_idle/Ts)*Ts;
emission=[emission temp_idle];
end
end
end
if sum(emission)>T
emission(end)=emission(end)-(sum(emission)-T);
end
%% creating PU signal
%% PU signal variables
ch_tx=[];% ch is signal in channel
t_ch=[];% time of channel samples
pu_state=[];
for i=1:length(seq)
state_ch=seq(i);
t = Ts:Ts:emission(i); % Sampling times
if isempty(t_ch)
temp=0;
else temp=t_ch(end);
end
t=t+temp;
t_ch=[t_ch t];
%% creating and modulating signal at PU transmitter
N_t=length(t);
if state_ch==1 % busy
infoSignal = randi(M,N_t,1)-1; % random binary signal (bits = log2(M))
signal_ch_tx = step(hpsk,infoSignal)'; % M-psk signal
% y is the transmitted signal
else if state_ch==0 %idle
signal_ch_tx = zeros(1,N_t); % no signal
end
end
ch_tx=[ch_tx signal_ch_tx];
pu_state=[pu_state seq(i)*ones(1,length(signal_ch_tx))];
end
t_ch=t_ch-Ts;
N=T*Fs;
if(length(t_ch)<N)
temp=t_ch(end)+Ts*(1:(N-length(t_ch)));
t_ch=[ t_ch temp ];
ch_tx=[ch_tx zeros(1,length(temp))];
pu_state=[pu_state zeros(1,length(temp))];
end
if(length(t_ch)>N)
t_ch= t_ch(1:N);
ch_tx=ch_tx(1:N);
pu_state=pu_state(1:N);
end
% if(length(t_ch)~=N)
% temp=t_ch(end)+Ts*(1:(N-length(t_ch)));
% t_ch=[ t_ch temp ];
% ch_tx=[ch_tx zeros(1,length(temp))];
% pu_state=[pu_state zeros(1,length(temp))];
% end
% if(length(t_ch)>N)
% t_ch= t_ch(1:N);
% ch_tx=ch_tx(1:N);
% pu_state=pu_state(1:N);
% end
|
github
|
PianoDan/TDP-master
|
TempoAvg.m
|
.m
|
TDP-master/TempoAvg.m
| 7,164 |
utf_8
|
089ba8ab4b3365c3c6a8896556e102e3
|
function varargout = TempoAvg(varargin)
% TEMPOAVG MATLAB code for TempoAvg.fig
% TEMPOAVG, by itself, creates a new TEMPOAVG or raises the existing
% singleton*.
%
% H = TEMPOAVG returns the handle to a new TEMPOAVG or the handle to
% the existing singleton*.
%
% TEMPOAVG('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in TEMPOAVG.M with the given input arguments.
%
% TEMPOAVG('Property','Value',...) creates a new TEMPOAVG or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before TempoAvg_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to TempoAvg_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help TempoAvg
% Last Modified by GUIDE v2.5 14-Feb-2018 20:15:39
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @TempoAvg_OpeningFcn, ...
'gui_OutputFcn', @TempoAvg_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before TempoAvg is made visible.
function TempoAvg_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to TempoAvg (see VARARGIN)
% Choose default command line output for TempoAvg
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes TempoAvg wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = TempoAvg_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in ActiveDirectoryButton.
function ActiveDirectoryButton_Callback(hObject, eventdata, handles)
% hObject handle to ActiveDirectoryButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.dir = uigetdir('','Set Active Directory');
if ~handles.dir
return;
end
handles.ActiveDirectoryBox.String = handles.dir;
subjectlist = dir([handles.dir,filesep,'*_analysis.mat']);
for i = length(subjectlist):-1:1
handles.subject(i) = load([handles.dir,filesep,subjectlist(i).name]);
melodies = cellfun(@str2num,handles.subject(i).subject.data(:,1));
[melodies, indices] = sort(melodies);
handles.subject(i).subject.data = handles.subject(i).subject.data(indices,:);
end
handles.MelodyBox.String = handles.subject(1).subject.data(:,1);
set(handles.SaveAveragesButton,'enable','on');
guidata(hObject,handles);
% --- Executes on selection change in MelodyBox.
function MelodyBox_Callback(hObject, eventdata, handles)
% hObject handle to MelodyBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns MelodyBox contents as cell array
% contents{get(hObject,'Value')} returns selected item from MelodyBox
selection = get(hObject,'Value');
subjectid = {};
for i = length(handles.subject):-1:1
interplength(i) = length(handles.subject(i).subject.data{selection,3}) -1;
subjectid(i) = {handles.subject(i).subject.id;};
end
[maxlength,maxindex] = max(interplength);
allinterpy = nan(maxlength,length(handles.subject));
for i = length(handles.subject):-1:1
x = cell2mat(handles.subject(i).subject.data{selection,4}(2:end,11));
y = cell2mat(handles.subject(i).subject.data{selection,4}(2:end,9));
interpy = cell2mat(handles.subject(i).subject.data{selection,3}(2:end,9));
allinterpy(:,i) = [interpy;nan(maxlength-length(interpy),1)];
plot(x,y,'Parent',handles.Ax);
hold on
end
interpx = cell2mat(handles.subject(maxindex).subject.data{selection,3}(2:end,11));
plot(interpx,nanmean(allinterpy,2),'k','Parent',handles.Ax);
subjectid = flip(subjectid);
subjectid(end+1) = {'Average'};
legend(subjectid);
xlabel('Total Beats');
ylabel('Beat Duration (ms)');
hold off
% --- Executes during object creation, after setting all properties.
function MelodyBox_CreateFcn(hObject, eventdata, handles)
% hObject handle to MelodyBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in SaveAveragesButton.
function SaveAveragesButton_Callback(hObject, eventdata, handles)
% hObject handle to SaveAveragesButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
nmelodies = length(handles.MelodyBox.String);
header = {'Melody'};
outputfile = [handles.dir,filesep,'MelodyAverages.xlsx'];
for j = 1:nmelodies
header = [header; {handles.MelodyBox.String{j}}];
header = [header; {' '}];
subjectid = {};
for i = length(handles.subject):-1:1
interplength(i) = length(handles.subject(i).subject.data{j,3}) -1;
subjectid(i) = {handles.subject(i).subject.id;};
end
[maxlength,maxindex] = max(interplength);
allinterpy = nan(maxlength,length(handles.subject));
for i = length(handles.subject):-1:1
interpy = cell2mat(handles.subject(i).subject.data{j,3}(2:end,9));
allinterpy(:,i) = [interpy;nan(maxlength-length(interpy),1)];
end
interpx = cell2mat(handles.subject(maxindex).subject.data{j,3}(2:end,11));
meany = nanmean(allinterpy,2);
xlswrite(outputfile,handles.MelodyBox.String{j},1,['A',num2str(j*2)]);
xlswrite(outputfile,interpx',1,['B' num2str(j*2)]);
xlswrite(outputfile,meany',1,['B' num2str(j*2 + 1)]);
disp(j);
end
xlswrite(outputfile,header,1,'A1');
|
github
|
PianoDan/TDP-master
|
TDPPlot.m
|
.m
|
TDP-master/TDPPlot.m
| 8,860 |
utf_8
|
4f515dcaccab2050037da3818dcd5f87
|
function varargout = TDPPlot(varargin)
% TDPPLOT MATLAB code for TDPPlot.fig
% TDPPLOT, by itself, creates a new TDPPLOT or raises the existing
% singleton*.
%
% H = TDPPLOT returns the handle to a new TDPPLOT or the handle to
% the existing singleton*.
%
% TDPPLOT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in TDPPLOT.M with the given input arguments.
%
% TDPPLOT('Property','Value',...) creates a new TDPPLOT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before TDPPlot_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to TDPPlot_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help TDPPlot
% Last Modified by GUIDE v2.5 18-Oct-2017 20:45:27
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @TDPPlot_OpeningFcn, ...
'gui_OutputFcn', @TDPPlot_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before TDPPlot is made visible.
function TDPPlot_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to TDPPlot (see VARARGIN)
subjectlist = dir('*_analysis.mat');
set(handles.SubjectBox,'String',{subjectlist.name});
% Choose default command line output for TDPPlot
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes TDPPlot wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = TDPPlot_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on selection change in SubjectBox.
function SubjectBox_Callback(hObject, ~, handles)
% hObject handle to SubjectBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns SubjectBox contents as cell array
% contents{get(hObject,'Value')} returns selected item from SubjectBox
contents = cellstr(get(hObject,'String'));
subjectfile = contents{get(hObject,'Value')};
load(subjectfile);
handles.subject = subject;
set(handles.startstopaction,'Enable','on');
[~, idx] = sort(str2double({subject.data{:,1}}));
subject.data = subject.data(idx,:);
set(handles.StimulusBox,'String',{subject.data{:,1}});
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function SubjectBox_CreateFcn(hObject, eventdata, handles)
% hObject handle to SubjectBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in StimulusBox.
function StimulusBox_Callback(hObject, eventdata, handles)
% hObject handle to StimulusBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns StimulusBox contents as cell array
% contents{get(hObject,'Value')} returns selected item from StimulusBox
contents = cellstr(get(hObject,'String'));
stimulus = contents{get(hObject,'Value')};
index = strcmp(handles.subject.data,stimulus);
data = handles.subject.data{index,2};
graphtype = get(handles.GraphTypeMenu,'Value');
timems = cell2mat(data(2:end,7));
answerms = cell2mat(data(2:end,9));
totalbeats = cell2mat(data(2:end,11));
if graphtype == 1
x = totalbeats;
y = answerms;
elseif graphtype == 2
x = timems;
y = answerms;
end
plot(handles.GraphAxes,x,y);
ylabel('Answer (ms)')
if graphtype == 1
xlabel('Total Beats');
elseif graphtype == 2
xlabel('Time (ms)');
end
set(handles.startbox,'String',strcat(num2str(y(1)),' ms'));
set(handles.endbox,'String',strcat(num2str(y(end)),' ms'));
% --- Executes during object creation, after setting all properties.
function StimulusBox_CreateFcn(hObject, eventdata, handles)
% hObject handle to StimulusBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in GraphTypeMenu.
function GraphTypeMenu_Callback(hObject, eventdata, handles)
% hObject handle to GraphTypeMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns GraphTypeMenu contents as cell array
% contents{get(hObject,'Value')} returns selected item from GraphTypeMenu
contents = cellstr(get(handles.StimulusBox,'String'));
if isempty(contents{1})
return
end
stimulus = contents{get(handles.StimulusBox,'Value')};
index = strcmp(handles.subject.data,stimulus);
data = handles.subject.data{index,2};
graphtype = get(handles.GraphTypeMenu,'Value');
timems = cell2mat(data(2:end,7));
answerms = cell2mat(data(2:end,9));
totalbeats = cell2mat(data(2:end,11));
if graphtype == 1
x = totalbeats;
y = answerms;
elseif graphtype == 2
x = timems;
y = answerms;
end
plot(handles.GraphAxes,x,y);
ylabel('Answer (ms)')
if graphtype == 1
xlabel('Total Beats');
elseif graphtype == 2
xlabel('Time (ms)');
end
% --- Executes during object creation, after setting all properties.
function GraphTypeMenu_CreateFcn(hObject, eventdata, handles)
% hObject handle to GraphTypeMenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function toolsmenu_Callback(hObject, eventdata, handles)
% hObject handle to toolsmenu (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function startstopaction_Callback(hObject, eventdata, handles)
% hObject handle to startstopaction (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
nsubjects = length(handles.subject.data);
stimuli = strings(1,nsubjects);
starts = zeros(1,nsubjects);
ends = zeros(1,nsubjects);
for idx = 1:nsubjects
stimuli(idx) = handles.subject.data{idx,1};
starts(idx) = handles.subject.data{idx,2}{2,9};
ends(idx) = handles.subject.data{idx,2}{end,9};
end
[~,i]=sort(str2double(stimuli));
f=figure;
set(f,'Name',['Intitial/Final Answers for Subject ' handles.subject.id]);
output = [stimuli(i);starts(i);ends(i)]';
t=uitable(f,'Data',cellstr(output));
t.ColumnName = {'Stimulus','Start(ms)','End(ms)'};
|
github
|
PianoDan/TDP-master
|
SubjectAvg.m
|
.m
|
TDP-master/SubjectAvg.m
| 7,407 |
utf_8
|
ac10cb4c905651c4816c4a0271313751
|
function varargout = SubjectAvg(varargin)
% SubjectAvg MATLAB code for SubjectAvg.fig
% SubjectAvg, by itself, creates a new SubjectAvg or raises the existing
% singleton*.
%
% H = SubjectAvg returns the handle to a new SubjectAvg or the handle to
% the existing singleton*.
%
% SubjectAvg('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SubjectAvg.M with the given input arguments.
%
% SubjectAvg('Property','Value',...) creates a new SubjectAvg or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before SubjectAvg_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to SubjectAvg_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help SubjectAvg
% Last Modified by GUIDE v2.5 21-May-2018 18:10:44
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @SubjectAvg_OpeningFcn, ...
'gui_OutputFcn', @SubjectAvg_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before SubjectAvg is made visible.
function SubjectAvg_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to SubjectAvg (see VARARGIN)
% Choose default command line output for SubjectAvg
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes SubjectAvg wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = SubjectAvg_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in ActiveDirectoryButton.
function ActiveDirectoryButton_Callback(hObject, eventdata, handles)
% hObject handle to ActiveDirectoryButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.dir = uigetdir('','Set Active Directory');
if ~handles.dir
return;
end
handles.ActiveDirectoryBox.String = handles.dir;
subjectlist = dir([handles.dir,filesep,'*_analysis.mat']);
ids = [];
for i = length(subjectlist):-1:1
handles.subject(i) = load([handles.dir,filesep,subjectlist(i).name]);
melodies = cellfun(@str2num,handles.subject(i).subject.data(:,1));
ids = [str2double(handles.subject(i).subject.id) ids];
[melodies, indices] = sort(melodies);
handles.subject(i).subject.data = handles.subject(i).subject.data(indices,:);
end
[ids, idindices] = sort(ids);
handles.subject = handles.subject(:,idindices);
handles.idindices = idindices;
handles.MelodyBox.String = ids;
set(handles.SaveAveragesButton,'enable','on');
guidata(hObject,handles);
% --- Executes on selection change in MelodyBox.
function MelodyBox_Callback(hObject, eventdata, handles)
% hObject handle to MelodyBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns MelodyBox contents as cell array
% contents{get(hObject,'Value')} returns selected item from MelodyBox
selection = get(hObject,'Value');
nstimuli = length(handles.subject(selection).subject.data);
for i = nstimuli:-1:1
interplength(i) = length(handles.subject(selection).subject.data{i,3}) -1;
stimulusid(i) = {handles.subject(selection).subject.data{i,1};};
end
[maxlength,maxindex] = max(interplength);
allinterpy = nan(maxlength,nstimuli);
for i = 1:nstimuli
x = cell2mat(handles.subject(selection).subject.data{i,4}(2:end,11));
y = cell2mat(handles.subject(selection).subject.data{i,4}(2:end,9));
interpy = cell2mat(handles.subject(selection).subject.data{i,3}(2:end,9));
allinterpy(:,i) = [interpy;nan(maxlength-length(interpy),1)];
plot(x,y,'Parent',handles.Ax);
hold on
end
interpx = cell2mat(handles.subject(selection).subject.data{maxindex,3}(2:end,11));
plot(interpx,nanmean(allinterpy,2),'k','Parent',handles.Ax);
%stimulusid = flip(stimulusid);
stimulusid(end+1) = {'Average'};
legend(stimulusid);
xlabel('Total Beats');
ylabel('Beat Duration (ms)');
hold off
% --- Executes during object creation, after setting all properties.
function MelodyBox_CreateFcn(hObject, eventdata, handles)
% hObject handle to MelodyBox (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in SaveAveragesButton.
function SaveAveragesButton_Callback(hObject, eventdata, handles)
% hObject handle to SaveAveragesButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
nsubjects = length(handles.MelodyBox.String(:,1));
header = {'Subject'};
outputfile = [handles.dir,filesep,'SubjectAverages.xlsx'];
for j = 1:nsubjects
header = [header; {handles.MelodyBox.String(j,:)}];
header = [header; {' '}];
subjectid = {};
nstimuli = length(handles.subject(j).subject.data);
for i = nstimuli:-1:1
interplength(i) = length(handles.subject(j).subject.data{i,3}) -1;
subjectid(i) = {handles.subject(j).subject.id;};
end
[maxlength,maxindex] = max(interplength);
allinterpy = nan(maxlength,length(handles.subject));
for i = nstimuli:-1:1
interpy = cell2mat(handles.subject(j).subject.data{i,3}(2:end,9));
allinterpy(:,i) = [interpy;nan(maxlength-length(interpy),1)];
end
interpx = cell2mat(handles.subject(j).subject.data{maxindex,3}(2:end,11));
meany = nanmean(allinterpy,2);
xlswrite(outputfile,cellstr(handles.MelodyBox.String(j,:)),1,['A',num2str(j*2)]);
xlswrite(outputfile,interpx',1,['B' num2str(j*2)]);
xlswrite(outputfile,meany',1,['B' num2str(j*2 + 1)]);
end
xlswrite(outputfile,header,1,'A1');
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
OccupancyGrid.m
|
.m
|
PlatoonBased-AIM-master/Matlab2/OccupancyGrid.m
| 54,073 |
utf_8
|
48a2d107b354fe119551901e2740db99
|
classdef (Sealed)OccupancyGrid <OccupancyGridBase
%OCCUPANCYGRID Create an occupancy grid
% OCCUPANCYGRID creates a 2D occupancy grid map. Each cell has
% a value representing the probability of occupancy of that cell.
% Probability values close to 1 represent certainty that the workspace
% represented by the cell is occupied by an obstacle. Values close to 0
% represent certainty that the workspace represented by the cell is not
% occupied and is obstacle-free.
%
% The probability values in the occupancy grid are stored with
% a precision of at least 1e-3 to reduce memory usage and allow creation of
% occupancy grid objects to represent large workspace. The minimum and
% maximum probability that can be represented are 0.001 and 0.999
% respectively.
%
% MAP = robotics.OccupancyGrid(W, H) creates a 2D occupancy grid
% object representing a world space of width(W) and height(H) in
% meters. The default grid resolution is 1 cell per meter.
%
% MAP = robotics.OccupancyGrid(W, H, RES) creates an OccupancyGrid
% object with resolution(RES) specified in cells per meter.
%
% MAP = robotics.OccupancyGrid(M, N, RES, 'grid') creates an
% OccupancyGrid object and specifies a grid size of M rows and N columns.
% RES specifies the cells per meter resolution.
%
% MAP = robotics.OccupancyGrid(P) creates an occupancy grid object
% from the values in the matrix, P. The size of the grid matches the
% matrix with each cell value interpreted from that matrix location.
% Matrix, P, may contain any numeric type with values between zero(0)
% and one(1).
%
% MAP = robotics.OccupancyGrid(P, RES) creates an OccupancyGrid
% object from matrix, P, with RES specified in cells per meter.
%
% OccupancyGrid properties:
% FreeThreshold - Threshold to consider cells as obstacle-free
% OccupiedThreshold - Threshold to consider cells as occupied
% ProbabilitySaturation - Saturation limits on probability values as [min, max]
% GridSize - Size of the grid in [rows, cols] (number of cells)
% Resolution - Grid resolution in cells per meter
% XWorldLimits - Minimum and maximum values of X
% YWorldLimits - Minimum and maximum values of Y
% GridLocationInWorld - Location of grid in world coordinates
%
%
% OccupancyGrid methods:
% checkOccupancy - Check locations for free, occupied or unknown
% copy - Create a copy of the object
% getOccupancy - Get occupancy of a location
% grid2world - Convert grid indices to world coordinates
% inflate - Inflate each occupied grid location
% insertRay - Insert rays from laser scan observation
% occupancyMatrix - Convert occupancy grid to double matrix
% raycast - Compute cell indices along a ray
% rayIntersection - Compute map intersection points of rays
% setOccupancy - Set occupancy of a location
% show - Show grid values in a figure
% updateOccupancy - Integrate probability observation at a location
% world2grid - Convert world coordinates to grid indices
%
%
% Example:
%
% % Create a 2m x 2m empty map
% map = robotics.OccupancyGrid(2,2);
%
% % Create a 10m x 10m empty map with resolution 20
% map = robotics.OccupancyGrid(10, 10, 20);
%
% % Insert a laser scan in the occupancy grid
% ranges = 5*ones(100, 1);
% angles = linspace(-pi/2, pi/2, 100);
% insertRay(map, [5,5,0], ranges, angles, 20);
%
% % Show occupancy grid in Graphics figure
% show(map);
%
% % Create a map from a matrix with resolution 20
% p = eye(100)*0.5;
% map = robotics.OccupancyGrid(p, 20);
%
% % Check occupancy of the world location (0.3, 0.2)
% value = getOccupancy(map, [0.3 0.2]);
%
% % Set world position (1.5, 2.1) as occupied
% setOccupancy(map, [1.5 2.1], 0.8);
%
% % Get the grid cell indices for world position (2.5, 2.1)
% ij = world2grid(map, [2.5 2.1]);
%
% % Set the grid cell indices to unoccupied
% setOccupancy(map, [1 1], 0.2, 'grid');
%
% % Integrate occupancy observation at a location
% updateOccupancy(map, [1 1], 0.7);
%
% % Show occupancy grid in Graphics figure
% show(map);
%
% See also robotics.MonteCarloLocalization, robotics.BinaryOccupancyGrid.
% Copyright 2016 The MathWorks, Inc.
%#codegen
%%
properties (Dependent)
%OccupiedThreshold Probability threshold to consider cells as occupied
% A scalar representing the probability threshold above which
% cells are considered to be occupied. The OccupiedThreshold will be
% saturated based on ProbabilitySaturation property.
%
% Default: 0.65
OccupiedThreshold
%FreeThreshold Probability threshold to consider cells as obstacle-free
% A scalar representing the probability threshold below which
% cells are considered to be obstacle-free. The FreeThreshold will be
% saturated based on ProbabilitySaturation property.
%
% Default: 0.20
FreeThreshold
%ProbabilitySaturation Saturation values for probability
% A vector [MIN MAX] representing the probability saturation
% values. The probability values below MIN value will be saturated to
% MIN and above MAX values will be saturated to MAX. The MIN
% value cannot be below 0.001 and MAX value cannot be above 0.999.
%
% Default: [0.001 0.999]
ProbabilitySaturation
end
properties (Access = public)
%Logodds Internal log-odds representation for probability
Logodds
end
properties (Access = protected, Constant)
%DefaultType Default datatype used for log-odds
DefaultType = 'int16';
%ProbMaxSaturation Maximum probability saturation possible
ProbMaxSaturation = [0.001 0.999]
%LookupTable Lookup table to convert between log-odds and probability
LookupTable = createLookupTable();
%LinSpaceInt16 The line space for all integer log-odds values
LinSpaceInt16 = getIntLineSpace();
end
properties (Access = private)
%FreeThresholdIntLogodds Integer log-odds values for FreeThreshold
% The log-odds value correspond to the default threshold of 0.2
FreeThresholdIntLogodds
%OccupiedThresholdIntLogodds Integer log-odds values for OccupiedThreshold
% The log-odds value correspond to the default threshold of 0.65
OccupiedThresholdIntLogodds
end
properties (Access = public)
%LogoddsHit Integer log-odds value for update on sensor hit
% This is the default log-odds value used to update grid cells
% where a hit is detected. This value represents probability
% value of 0.7
LogoddsHit
%LogoddsMiss Integer log-odds value for update on sensor miss
% This is the default log-odds value used to update grid cells
% where a miss is detected (i.e. laser ray passes through grid
% cells). This value represents probability value of 0.4
LogoddsMiss
%ProbSatIntLogodds Int log-odds for saturation
% These values correspond to default ProbabilitySaturation
% values of [0.001 0.999]
ProbSatIntLogodds
end
methods
function set.OccupiedThreshold(obj,threshold)
freeThreshold = obj.intLogoddsToProb(obj.FreeThresholdIntLogodds);
validateattributes(threshold, {'numeric'}, ...
{'scalar', 'real', 'nonnan', 'finite', 'nonnegative'}, ...
'OccupiedThreshold');
logOddsThreshold = obj.probToIntLogodds(double(threshold));
check = obj.FreeThresholdIntLogodds > logOddsThreshold;
if check
if coder.target('MATLAB')
error(message('robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'OccupiedThreshold', ...
'>=', num2str(freeThreshold,'%.3f')));
else
coder.internal.errorIf(check, 'robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'OccupiedThreshold', ...
'>=', coder.internal.num2str(freeThreshold));
end
end
obj.OccupiedThresholdIntLogodds = logOddsThreshold;
end
function threshold = get.OccupiedThreshold(obj)
threshold = double(obj.intLogoddsToProb(obj.OccupiedThresholdIntLogodds));
end
function set.FreeThreshold(obj,threshold)
occupiedThreshold = obj.intLogoddsToProb(obj.OccupiedThresholdIntLogodds);
validateattributes(threshold, {'numeric'}, ...
{'scalar', 'real', 'nonnan', 'finite', 'nonnegative'}, ...
'FreeThreshold');
logOddsThreshold = obj.probToIntLogodds(double(threshold));
check = obj.OccupiedThresholdIntLogodds < logOddsThreshold;
if check
if coder.target('MATLAB')
error(message('robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'FreeThreshold', ...
'<=', num2str(occupiedThreshold,'%.3f')));
else
coder.internal.errorIf(check, 'robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'FreeThreshold', ...
'<=', coder.internal.num2str(occupiedThreshold));
end
end
obj.FreeThresholdIntLogodds = logOddsThreshold;
end
function threshold = get.FreeThreshold(obj)
threshold = double(obj.intLogoddsToProb(obj.FreeThresholdIntLogodds));
end
function set.ProbabilitySaturation(obj, sat)
% Run basic checks
validateattributes(sat, {'numeric'}, ...
{'vector', 'real', 'nonnan', 'numel', 2}, 'ProbabilitySaturation');
% Check the limits
sortedSat = sort(sat);
validateattributes(sortedSat(1), {'numeric'}, {'>=',obj.ProbMaxSaturation(1), ...
'<=',0.5}, ...
'ProbabilitySaturation', 'lower saturation');
validateattributes(sortedSat(2), {'numeric'}, {'>=',0.5, ...
'<=',obj.ProbMaxSaturation(2)}, ...
'ProbabilitySaturation', 'upper saturation');
obj.ProbSatIntLogodds = obj.probToIntLogoddsMaxSat(double([sortedSat(1), sortedSat(2)]));
obj.Logodds(obj.Logodds < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(obj.Logodds > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
end
function sat = get.ProbabilitySaturation(obj)
sat = double(obj.intLogoddsToProb(obj.ProbSatIntLogodds));
end
function obj = OccupancyGrid(varargin)
%OccupancyGrid Constructor
% Parse input arguments
narginchk(1,4);
[resolution, isGrid, mat, width, height, isMat]...
= obj.parseConstructorInputs(varargin{:});
% Assign properties with default values
obj.FreeThresholdIntLogodds = obj.probToIntLogoddsMaxSat(0.2);
obj.OccupiedThresholdIntLogodds = obj.probToIntLogoddsMaxSat(0.65);
obj.LogoddsHit = obj.probToIntLogoddsMaxSat(0.7);
obj.LogoddsMiss = obj.probToIntLogoddsMaxSat(0.4);
obj.ProbSatIntLogodds = [intmin(obj.DefaultType), intmax(obj.DefaultType)];
% Apply probability saturation to matrix
mat(mat < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
mat(mat > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
obj.Resolution = resolution;
% Construct grid from a matrix input
if isMat
obj.Logodds = mat;
obj.GridSize = size(obj.Logodds);
return;
end
% Construct empty grid from width and height
if isGrid
obj.Logodds = mat;
else
gridsize = size(mat);
% Throw a warning if we round off the grid size
if any(gridsize ~= ([height, width]*obj.Resolution))
coder.internal.warning(...
'robotics:robotalgs:occgridcommon:RoundoffWarning');
end
obj.Logodds = mat;
end
obj.GridSize = size(obj.Logodds);
end
function cpObj = copy(obj)
%COPY Creates a copy of the object
% cpObj = COPY(obj) creates a deep copy of the
% Occupancy Grid object with the same properties.
%
% Example:
% % Create an occupancy grid of 10m x 10m world representation
% map = robotics.OccupancyGrid(10, 10);
%
% % Create a copy of the object
% cpObj = copy(map);
%
% % Access the class methods from the new object
% setOccupancy(cpObj,[2 4],true);
%
% % Delete the handle object
% delete(cpObj)
%
% See also robotics.OccupancyGrid
if isempty(obj)
% This will not be encountered in code generation
cpObj = OccupancyGrid.empty(0,1);
else
% Create a new object with the same properties
cpObj = OccupancyGrid(obj.GridSize(1),...
obj.GridSize(2),obj.Resolution,'grid');
% Assign the grid data to the new object handle
cpObj.Logodds = obj.Logodds;
cpObj.GridLocationInWorld = obj.GridLocationInWorld;
cpObj.OccupiedThresholdIntLogodds = obj.OccupiedThresholdIntLogodds;
cpObj.FreeThresholdIntLogodds = obj.FreeThresholdIntLogodds;
cpObj.ProbSatIntLogodds = obj.ProbSatIntLogodds;
end
end
function value = getOccupancy(obj, pos, frame)
%getOccupancy Get occupancy value for one or more positions
% VAL = getOccupancy(MAP, XY) returns an N-by-1 array of
% occupancy values for N-by-2 array, XY. Each row of the
% array XY corresponds to a point with [X Y] world coordinates.
%
% VAL = getOccupancy(MAP, IJ, 'grid') returns an N-by-1
% array of occupancy values for N-by-2 array IJ. Each row of
% the array IJ refers to a grid cell index [X,Y].
%
% Example:
% % Create an occupancy grid and get occupancy
% % values for a position
% map = robotics.OccupancyGrid(10, 10);
%
% % Get occupancy of the world coordinate (0, 0)
% value = getOccupancy(map, [0 0]);
%
% % Get occupancy of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = getOccupancy(map, [X(:) Y(:)]);
%
% % Get occupancy of the grid cell (1, 1)
% value = getOccupancy(map, [1 1], 'grid');
%
% % Get occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = getOccupancy(map, [I(:) J(:)], 'grid');
%
% See also robotics.OccupancyGrid, setOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 2
isGrid = obj.parseOptionalFrameInput(frame, 'getOccupancy');
end
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'getOccupancy');
value = double(obj.intLogoddsToProb(obj.Logodds(indices)));
end
function setOccupancy(obj, pos, value, frame)
%setOccupancy Set occupancy value for one or more positions
% setOccupancy(MAP, XY, VAL) assigns the scalar occupancy
% value, VAL to each coordinate specified in the N-by-2 array,
% XY. Each row of the array XY corresponds to a point with
% [X Y] world coordinates.
%
% setOccupancy(MAP, XY, VAL) assigns each element of the
% N-by-1 vector, VAL to the coordinate position of the
% corresponding row of the N-by-2 array, XY.
%
% setOccupancy(MAP, IJ, VAL, 'grid') assigns occupancy values
% to the grid positions specified by each row of the N-by-2
% array, IJ, which refers to the [row, col] index from each row
% in the array.
%
% Example:
% % Create an occupancy grid and set occupancy
% % values for a position
% map = robotics.OccupancyGrid(10, 10);
%
% % Set occupancy of the world coordinate (0, 0)
% setOccupancy(map, [0 0], 0.2);
%
% % Set occupancy of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = ones(numel(X),1)*0.65;
% setOccupancy(map, [X(:) Y(:)], values);
%
% % Set occupancy of the grid cell (1, 1)
% setOccupancy(map, [1 1], 0.4, 'grid');
%
% % Set occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% setOccupancy(map, [I(:) J(:)], 0.4, 'grid');
%
% % Set occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = ones(numel(I),1)*0.8;
% setOccupancy(map, [I(:) J(:)], values, 'grid');
%
% See also robotics.OccupancyGrid, getOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 3
isGrid = obj.parseOptionalFrameInput(frame, 'setOccupancy');
end
% Validate values
obj.validateOccupancyValues(value, size(pos, 1), 'setOccupancy', 'val');
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'setOccupancy');
obj.Logodds(indices) = probToIntLogodds(obj,double(value(:)));
end
function inflate(obj, varargin)
%INFLATE Inflate the occupied positions by a given amount
% INFLATE(MAP, R) inflates each occupied position of the
% occupancy grid by at least R meters. Each cell of the
% occupancy grid is inflated by number of cells which is the
% closest integer higher than the value MAP.Resolution*R.
%
% INFLATE(MAP, R, 'grid') inflates each cell of the
% occupancy grid by R cells.
%
% Note that the inflate function does not inflate the
% positions past the limits of the grid.
%
% Example:
% % Create an occupancy grid and inflate map
% mat = eye(100)*0.6;
% map = robotics.OccupancyGrid(mat);
%
% % Create a copy of the map for inflation
% cpMap = copy(map);
%
% % Inflate occupied cells using inflation radius in
% % meters
% inflate(cpMap, 0.1);
%
% % Inflate occupied cells using inflation radius in
% % number of cells
% inflate(cpMap, 2, 'grid');
%
% See also robotics.OccupancyGrid, copy
narginchk(2,3);
obj.Logodds = obj.inflateGrid(obj.Logodds, varargin{:});
end
function imageHandle = show(obj, varargin)
%SHOW Display the occupancy grid in a figure
% SHOW(MAP) displays the MAP occupancy grid in the
% current axes with the axes labels representing the world
% coordinates.
%
% SHOW(MAP, 'grid') displays the MAP occupancy grid in
% the current axes with the axes of the figure representing
% the grid indices.
%
% HIMAGE = SHOW(MAP, ___) returns the handle to the image
% object created by show.
%
% SHOW(MAP,___,Name,Value) provides additional options specified
% by one or more Name,Value pair arguments. Name must appear
% inside single quotes (''). You can specify several name-value
% pair arguments in any order as Name1,Value1,...,NameN,ValueN:
%
% 'Parent' - Handle of an axes that specifies
% the parent of the image object
% created by show.
%
% Example:
% % Create an occupancy grid and display
% map = robotics.OccupancyGrid(eye(5)*0.5);
%
% % Display the occupancy with axes showing the world
% % coordinates
% imgHandle = show(map);
%
% % Display the occupancy with axes showing the grid
% % indices
% imgHandle = show(map, 'grid');
%
% % Display the occupancy with axes showing the world
% % coordinates and specify a parent axes
% fHandle = figure;
% aHandle = axes('Parent', fh);
% imgHandle = show(map, 'world', 'Parent', ah);
%
% See also robotics.OccupancyGrid
[axHandle, isGrid] = obj.showInputParser(varargin{:});
[axHandle, imghandle] = showGrid(obj, obj.intLogoddsToProb(obj.Logodds), axHandle, isGrid);
title(axHandle, ...
'Platoon Based Autonomous Intersection Management');
% Only return handle if user requested it.
if nargout > 0
imageHandle = imghandle;
end
end
function occupied = checkOccupancy(obj, pos, frame)
%checkOccupancy Check ternary occupancy status for one or more positions
% VAL = checkOccupancy(MAP, XY) returns an N-by-1 array of
% occupancy status using OccupiedThreshold and FreeThreshold,
% for N-by-2 array, XY. Each row of the array XY corresponds
% to a point with [X Y] world coordinates. Occupancy status
% of 0 refers to obstacle-free cells, 1 refers to occupied
% cells and -1 refers to unknown cells.
%
% VAL = checkOccupancy(MAP, IJ, 'grid') returns an N-by-1
% array of occupancy status for N-by-2 array IJ. Each row of
% the array IJ refers to a grid cell index [X,Y].
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(10, 10);
%
% % Check occupancy status of the world coordinate (0, 0)
% value = checkOccupancy(map, [0 0]);
%
% % Check occupancy status of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = checkOccupancy(map, [X(:) Y(:)]);
%
% % Check occupancy status of the grid cell (1, 1)
% value = checkOccupancy(map, [1 1], 'grid');
%
% % Check occupancy status of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = checkOccupancy(map, [I(:) J(:)], 'grid');
%
% See also robotics.OccupancyGrid, getOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 2
isGrid = obj.parseOptionalFrameInput(frame, 'checkOccupancy');
end
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'checkOccupancy');
value = obj.Logodds(indices);
freeIdx = (value < obj.FreeThresholdIntLogodds);
occIdx = (value > obj.OccupiedThresholdIntLogodds);
occupied = ones(size(value))*(-1);
occupied(freeIdx) = 0;
occupied(occIdx) = 1;
end
function idx = world2grid(obj, pos)
%WORLD2GRID Convert world coordinates to grid indices
% IJ = WORLD2GRID(MAP, XY) converts an N-by-2 array of world
% coordinates, XY, to an N-by-2 array of grid indices, IJ. The
% input, XY, is in [X Y] format. The output grid indices, IJ,
% are in [ROW COL] format.
%
% Example:
% % Create an occupancy grid and convert world
% % coordinates to grid indices
% % Create a 10m x 10m world representation
% map = robotics.OccupancyGrid(10, 10);
%
% % Get grid indices from world coordinates
% ij = world2grid(map, [0 0])
%
% % Get grid indices from world coordinates
% [x y] = meshgrid(0:0.5:2);
% ij = world2grid(map, [x(:) y(:)])
pos = obj.validatePosition(pos, obj.XWorldLimits, ...
obj.YWorldLimits, 'world2grid', 'xy');
% Convert world coordinate to grid indices
idx = worldToGridPrivate(obj, pos);
end
function pos = grid2world(obj, idx)
%GRID2WORLD Convert grid indices to world coordinates
% XY = GRID2WORLD(MAP, IJ) converts an N-by-2 array of grid
% indices, IJ, to an N-by-2 array of world coordinates, XY. The
% input grid indices, IJ, are in [ROW COL] format. The output,
% XY, is in [X Y] format.
%
% Example:
% % Create an occupancy grid and convert grid
% % indices to world coordinates
% % Create a 10m x 10m world representation
% map = robotics.OccupancyGrid(10, 10);
%
% % Get world coordinates from grid indices
% xy = grid2world(map, [1 1])
%
% % Get world coordinates from grid indices
% [i j] = meshgrid(1:5);
% xy = world2grid(map, [i(:) j(:)])
idx = obj.validateGridIndices(idx, obj.GridSize, ...
'grid2world', 'IJ');
% Convert grid index to world coordinate
pos = gridToWorldPrivate(obj, idx);
end
function updateOccupancy(obj, pos, value, frame)
%updateOccupancy Integrate occupancy value for one or more positions
% updateOccupancy(MAP, XY, OBS) probabilistically integrates
% the scalar observation OBS for each coordinate specified in the
% N-by-2 array, XY. Each row of the array XY corresponds to a
% point with [X Y] world coordinates. Default update values
% are used if OBS is logical. Update values are 0.7 and 0.4
% for true and false respectively. Alternatively, OBS can be
% of any numeric type with value between 0 and 1.
%
% updateOccupancy(MAP, XY, OBS) probabilistically integrates
% each element of the N-by-1 vector, OBS with the coordinate
% position of the corresponding row of the N-by-2 array, XY.
%
% updateOccupancy(MAP, IJ, OBS, 'grid') probabilistically
% integrates observation values to the grid positions
% specified by each row of the N-by-2 array, IJ, which refers
% to the [row, col] index from each row in the array.
%
% Example:
% % Create an occupancy grid and update occupancy
% % values for a position
% map = robotics.OccupancyGrid(10, 10);
%
% % Update occupancy of the world coordinate (0, 0)
% updateOccupancy(map, [0 0], true);
%
% % Update occupancy of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = ones(numel(X),1)*0.65;
% updateOccupancy(map, [X(:) Y(:)], values);
%
% % Update occupancy of the grid cell (1, 1)
% updateOccupancy(map, [1 1], false, 'grid');
%
% % Update occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% updateOccupancy(map, [I(:) J(:)], 0.4, 'grid');
%
% % Update occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = true(numel(I),1);
% updateOccupancy(map, [I(:) J(:)], values, 'grid');
%
% See also robotics.OccupancyGrid, setOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 3
isGrid = obj.parseOptionalFrameInput(frame, 'updateOccupancy');
end
% Validate values
obj.validateOccupancyValues(value, size(pos, 1), 'updateOccupancy', 'val');
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'updateOccupancy');
if isscalar(value)
value = cast(ones(size(pos, 1), 1)*value, 'like', value);
end
if islogical(value)
updateValuesHit = obj.Logodds(indices(logical(value(:)))) + obj.LogoddsHit;
updateValuesHit(updateValuesHit > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
obj.Logodds(indices(logical(value(:)))) = updateValuesHit;
updateValuesMiss = obj.Logodds(indices(~logical(value(:)))) + obj.LogoddsMiss;
updateValuesMiss(updateValuesMiss < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(indices(~logical(value(:)))) = updateValuesMiss;
else
updateValues = obj.Logodds(indices) + obj.probToIntLogoddsMaxSat(double(value(:)));
updateValues(updateValues > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
updateValues(updateValues < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(indices) = updateValues;
end
end
function collisionPt = rayIntersection(obj, pose, angles, maxRange, threshold)
%rayIntersection Compute map intersection points of rays
% PTS = rayIntersection(MAP, POSE, ANGLES, MAXRANGE) returns
% collision points PTS in the world coordinate frame for
% rays emanating from POSE. PTS is an N-by-2 array of points.
% POSE is a 1-by-3 array of sensor pose [X Y THETA] in the world
% coordinate frame. ANGLES is an N-element vector of angles
% at which to get ray intersection points. MAXRANGE is a
% scalar representing the maximum range of the range sensor. If
% there is no collision up-to the maximum range then [NaN NaN]
% output is returned. By default, the OccupiedThreshold
% property in MAP is used to determine occupied cells.
%
% PTS = rayIntersection(MAP, POSE, ANGLES, MAXRANGE, THRESHOLD)
% returns collision points PTS, where the THRESHOLD is used
% to determine the occupied cells. Any cell with a probability
% value greater or equal to THRESHOLD is considered occupied.
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(eye(10));
%
% % Set occupancy of the world coordinate (5, 5)
% setOccupancy(map, [5 5], 0.5);
%
% % Get collision points
% collisionPts = rayIntersection(map, [0,0,0], [pi/4, pi/6], 10);
%
% % Visualize the collision points
% show(map);
% hold('on');
% plot(collisionPts(:,1),collisionPts(:,2) , '*')
%
% % Get collision points with threshold value 0.4
% collisionPts = rayIntersection(map, [0,0,0], [pi/4, pi/6], 10, 0.4);
%
% % Visualize the collision points
% plot(collisionPts(:,1),collisionPts(:,2) , '*')
%
% See also robotics.OccupancyGrid, raycast
narginchk(4,5);
vPose = obj.validatePose(pose, obj.XWorldLimits, obj.YWorldLimits, 'rayIntersection', 'pose');
vAngles = obj.validateAngles(angles, 'rayIntersection', 'angles');
validateattributes(maxRange, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', 'positive'}, 'rayIntersection', 'maxrange');
if nargin < 5
grid = (obj.occupancyMatrix('ternary') == 1);
else
validateattributes(threshold, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', '<=', 1, '>=', 0}, 'rayIntersection', 'threshold');
grid = obj.occupancyMatrix > threshold;
end
[ranges, endPt] = robotics.algs.internal.calculateRanges(vPose, vAngles, double(maxRange), ...
grid, obj.GridSize, obj.Resolution, obj.GridLocationInWorld);
collisionPt = endPt;
collisionPt(isnan(ranges), :) = nan;
end
function [endPts, middlePts] = raycast(obj, varargin)
%RAYCAST Get cells along a ray
% [ENDPTS, MIDPTS] = RAYCAST(MAP, POSE, RANGE, ANGLE) returns
% cell indices of all cells traversed by a ray emanating from
% POSE at an angle ANGLE with length equal to RANGE. POSE is
% a 3-element vector representing robot pose [X, Y, THETA] in
% the world coordinate frame. ANGLE and RANGE are scalars.
% The ENDPTS are indices of cells touched by the
% end point of the ray. MIDPTS are all the cells touched by
% the ray excluding the ENDPTS.
%
% [ENDPTS, MIDPTS] = RAYCAST(MAP, P1, P2) returns
% the cell indices of all cells between the line segment
% P1=[X1,Y1] to P2=[X2,Y2] in the world coordinate frame.
%
% For faster insertion of range sensor data, use the insertRay
% method with an array of ranges or an array of end points.
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(10, 10, 20);
%
% % compute cells along a ray
% [endPts, midPts] = raycast(map, [5,3,0], 4, pi/3);
%
% % Change occupancy cells to visualize
% updateOccupancy(map, endPts, true, 'grid');
% updateOccupancy(map, midPts, false, 'grid');
% % Compute cells along a line segment
% [endPts, midPts] = raycast(map, [2,5], [6,8]);
%
% % Change occupancy cells to visualize
% updateOccupancy(map, endPts, true, 'grid');
% updateOccupancy(map, midPts, false, 'grid');
%
% % Visualize the raycast output
% show(map);
%
% See also robotics.OccupancyGrid, insertRay
narginchk(3,4);
if nargin == 4
pose = obj.validatePose(varargin{1}, obj.XWorldLimits, ...
obj.YWorldLimits, 'raycast', 'pose');
validateattributes(varargin{2}, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', 'nonnegative'}, 'raycast', 'range');
validateattributes(varargin{3}, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar'}, 'raycast', 'angle');
range = double(varargin{2});
angle = double(varargin{3}) + pose(3);
startPoint = pose(1:2);
endPoint = [pose(1) + range*cos(angle), ...
pose(2) + range*sin(angle)];
else
startPoint = obj.validatePosition(varargin{1}, obj.XWorldLimits, ...
obj.YWorldLimits, 'raycast', 'StartPoint');
validateattributes(varargin{1}, {'numeric'}, {'numel', 2}, ...
'raycast', 'p1');
endPoint = obj.validatePosition(varargin{2}, obj.XWorldLimits, ...
obj.YWorldLimits, 'raycast', 'EndPoint');
validateattributes(varargin{2}, {'numeric'}, {'numel', 2}, ...
'raycast', 'p2');
end
[endPts, middlePts] = robotics.algs.internal.raycastCells(startPoint, endPoint, ...
obj.GridSize(1), obj.GridSize(2), obj.Resolution, obj.GridLocationInWorld);
end
function insertRay(obj, varargin)
%insertRay Insert rays from laser scan observation
% insertRay(MAP, POSE, RANGES, ANGLES, MAXRANGE) inserts one
% or more range sensor observations in the occupancy grid.
% POSE is a 3-element vector representing sensor pose
% [X, Y, THETA] in world coordinate frame, RANGES and ANGLES
% are corresponding N-element vectors for range sensor
% readings, MAXRANGE is the maximum range of the sensor.
% The cells along the ray except the end points are observed
% as obstacle-free and updated with probability of 0.4.
% The cells touching the end point are observed as occupied
% and updated with probability of 0.7. NaN values in RANGES are
% ignored. RANGES above MAXRANGE are truncated and the end
% points are not updated for MAXRANGE readings.
%
% insertRay(MAP, POSE, RANGES, ANGLES, MAXRANGE, INVMODEL)
% inserts the ray with update probabilities according to a
% 2-element vector INVMODEL. The first element of
% INVMODEL is used to update obstacle-free observations and
% the second element is used to update occupied observations.
% Values in INVMODEL should be between 0 and 1.
%
% insertRay(MAP, STARTPT, ENDPTS) inserts cells between the
% line segments STARTPT and ENDPTS. STARTPT is 2-element vector
% representing the start point [X,Y] in the world coordinate frame.
% ENDPTS is N-by-2 array of end points in the world coordinate
% frame. The cells along the line segment except the end points
% are updated with miss probability of 0.4 and the cells
% touching the end point are updated with hit probability of 0.7.
%
% insertRay(MAP, STARTPT, ENDPTS, INVMODEL) inserts the
% line segment with update probabilities according to a
% 1-by-2 or 2-by-1 array INVMODEL.
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(10,10,20);
%
% % Insert two rays
% insertRay(map, [5,5,0], [5, 6], [pi/4, pi/6], 20);
%
% % Insert rays with non default inverse model
% insertRay(map, [5,5,0], [5, 6], [pi/3, pi/2], 20, [0.3 0.8]);
%
% % Visualize inserted rays
% show(map);
%
% % Insert a line segment
% insertRay(map, [0,0], [3,3]);
%
% % Visualize inserted ray
% show(map);
%
% See also robotics.OccupancyGrid, raycast
% Supported syntax
%insertRay(ogmap, robotpose, ranges, angles, maxRange)
%insertRay(ogmap, robotpose, ranges, angles, maxRange, inverseModel)
%insertRay(ogmap, startPoint, endPoints)
%insertRay(ogmap, startPoint, endPoints, inverseModel)
gridSize = obj.GridSize;
res = obj.Resolution;
loc = obj.GridLocationInWorld;
narginchk(3, 6);
if nargin < 5
% Cartesian input
validateattributes(varargin{1}, {'numeric'}, ...
{'nonempty', 'numel', 2}, 'insertRay', 'startpt');
startPt = [varargin{1}(1) varargin{1}(2)];
startPt = obj.validatePosition(startPt, obj.XWorldLimits, ...
obj.YWorldLimits, 'insertRay', 'StartPoint');
endPt = obj.validatePosition(varargin{2}, obj.XWorldLimits, ...
obj.YWorldLimits, 'insertRay', 'endpts');
else
% Polar input
pose = obj.validatePose(varargin{1}, obj.XWorldLimits, ...
obj.YWorldLimits, 'insertRay', 'pose');
maxRange = varargin{4};
validateattributes(maxRange, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', 'positive'}, 'insertRay', 'maxrange');
ranges = obj.validateRanges(varargin{2}, 'insertRay', 'ranges');
angles = obj.validateAngles(varargin{3}, 'insertRay', 'angles');
isInvalidSize = (numel(ranges) ~= numel(angles));
coder.internal.errorIf(isInvalidSize, ...
'robotics:robotalgs:occgridcommon:RangeAngleMismatch', 'ranges', 'angles');
vRanges = ranges(~isnan(ranges(:)));
vAngles = angles(~isnan(ranges(:)));
vRanges = min(maxRange, vRanges);
startPt = [pose(1) pose(2)];
endPt = [pose(1) + vRanges.*cos(pose(3)+vAngles), ...
pose(2) + vRanges.*sin(pose(3)+vAngles)];
end
if nargin == 6 || nargin == 4
% Validate inverse model
validateattributes(varargin{end}, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'nonempty', 'numel', 2}, 'insertRay', 'invmodel');
invModel = varargin{end}(:)';
if coder.target('MATLAB')
firstElementMsg = message('robotics:robotalgs:occgrid:FirstElement').getString;
secondElementMsg = message('robotics:robotalgs:occgrid:SecondElement').getString;
else
% Hard code error string for code generation as coder
% does not support getting string from catalog.
firstElementMsg = 'first element of';
secondElementMsg = 'second element of';
end
validateattributes(invModel(1,1), {'numeric'}, ...
{'>=', 0, '<=', 0.5, 'scalar'}, 'insertRay', [firstElementMsg 'invModel']);
validateattributes(invModel(1,2), {'numeric'}, ...
{'>=', 0.5, '<=', 1, 'scalar'}, 'insertRay', [secondElementMsg 'invModel']);
inverseModelLogodds = obj.probToIntLogoddsMaxSat(double(invModel));
else
inverseModelLogodds = [obj.LogoddsMiss obj.LogoddsHit];
end
for i = 1:size(endPt, 1)
[endPts, middlePts] = robotics.algs.internal.raycastCells(startPt, endPt(i,:), ...
gridSize(1), gridSize(2), res, loc);
if ~isempty(middlePts)
mIndex = sub2ind(gridSize, middlePts(:,1), middlePts(:,2));
updateValuesMiss = obj.Logodds(mIndex) + inverseModelLogodds(1);
updateValuesMiss(updateValuesMiss < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(mIndex) = updateValuesMiss;
end
% For max range reading do not add end point
if nargin >= 5 && vRanges(i) >= maxRange
continue;
end
if ~isempty(endPts)
eIndex = sub2ind(gridSize, endPts(:,1), endPts(:,2));
updateValuesHit = obj.Logodds(eIndex) + inverseModelLogodds(2);
updateValuesHit(updateValuesHit > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
obj.Logodds(eIndex) = updateValuesHit;
end
end
end
function mat = occupancyMatrix(obj, option)
%OCCUPANCYMATRIX Export occupancy grid as a matrix
% MAT = OCCUPANCYMATRIX(MAP) returns probability values stored in the
% occupancy grid object as a matrix.
%
% MAT = OCCUPANCYMATRIX(MAP, 'ternary') returns occupancy status of
% the each occupancy grid cell as a matrix. The
% OccupiedThreshold and FreeThreshold are used to determine
% obstacle-free and occupied cells. Value 0 refers to
% obstacle-free cell, 1 refers to occupied cell and -1 refers
% to unknown cell.
%
% Example:
% % Create an occupancy grid
% inputMat = repmat(0.2:0.1:0.9, 8, 1);
% map = robotics.OccupancyGrid(inputMat);
%
% % Export occupancy grid as a matrix
% mat = occupancyMatrix(map);
%
% % Export occupancy grid as a ternary matrix
% mat = occupancyMatrix(map, 'ternary');
%
% See also robotics.OccupancyGrid, getOccupancy
narginchk(1,2);
if nargin < 2
mat = double(obj.intLogoddsToProb(obj.Logodds));
return;
end
validStrings = {'Ternary'};
validatestring(option, validStrings, 'occupancyMatrix');
mat = -1*ones(size(obj.Logodds));
occupied = (obj.Logodds > obj.OccupiedThresholdIntLogodds);
free = (obj.Logodds < obj.FreeThresholdIntLogodds);
mat(occupied) = 1;
mat(free) = 0;
end
end
%================================================================
methods (Static, Access = {?matlab.unittest.TestCase, ...
?robotics.algs.internal.OccupancyGridBase})
function logodds = probToLogodds(prob)
%probToLogodds Get log-odds value from probabilities
logodds = log(prob./(1-prob));
end
function probability = logoddsToProb(logodds)
%logoddsToProb Get probabilities from log-odds values
probability = 1 - 1./(1 + exp(logodds));
end
function maxSat = getMaxSaturation()
%getMaxSaturation Get max saturation for testing purposes
maxSat = robotics.OccupancyGrid.ProbMaxSaturation;
end
end
methods (Access = {?matlab.unittest.TestCase, ...
?robotics.algs.internal.OccupancyGridBase})
function logodds = probToIntLogodds(obj, prob)
%probToIntLogodds Convert probability to int16 log-odds
prob(prob < obj.ProbabilitySaturation(1)) = obj.ProbabilitySaturation(1);
prob(prob > obj.ProbabilitySaturation(2)) = obj.ProbabilitySaturation(2);
logodds = int16(interp1(obj.LookupTable, ...
single(obj.LinSpaceInt16),prob,'nearest', 'extrap'));
end
function probability = intLogoddsToProb(obj, logodds)
%intLogoddsToProb Convert int16 log-odds to probability
probability = interp1(single(obj.LinSpaceInt16), ...
obj.LookupTable, single(logodds),'nearest', 'extrap');
end
function logodds = probToIntLogoddsMaxSat(obj, prob)
%probToIntLogoddsMaxSat Convert probability to int16 log-odds
% This method uses maximum possible saturation. Required for
% update occupancy.
prob(prob < obj.ProbMaxSaturation(1)) = obj.ProbMaxSaturation(1);
prob(prob > obj.ProbMaxSaturation(2)) = obj.ProbMaxSaturation(2);
logodds = int16(interp1(obj.LookupTable, ...
single(obj.LinSpaceInt16),prob,'nearest', 'extrap'));
end
end
methods (Access = protected)
function mat = processMatrix(obj, varargin)
%processMatrix Process construction input and create log-odds
% Supports two input patterns:
% processMatrix(obj, rows,columns);
% processMatrix(obj, mat);
if nargin == 3
rows = varargin{1};
columns = varargin{2};
mat = zeros(rows, columns, obj.DefaultType);
elseif nargin == 2
% As probability saturation is not assigned, use max
% saturation.
mat = obj.probToIntLogoddsMaxSat(single(varargin{1}));
end
end
end
methods (Static, Access =public)
function P = validateMatrixInput(P)
%validateMatrixInput Validates the matrix input
if islogical(P)
validateattributes(P, {'logical'}, ...
{'2d', 'real', 'nonempty'}, ...
'OccupancyGrid', 'P', 1);
else
validateattributes(P, {'numeric','logical'}, ...
{'2d', 'real', 'nonempty','nonnan','<=',1,'>=',0}, ...
'OccupancyGrid', 'P', 1);
end
end
function className = getClassName()
className = 'OccupancyGrid';
end
function validateOccupancyValues(values, len, fcnName, argname)
%validateOccupancyValues Validate occupancy value vector
% check that the values are numbers in [0,1]
if islogical(values)
validateattributes(values, {'logical'}, ...
{'real','vector', 'nonempty'}, fcnName, argname);
else
validateattributes(values, {'numeric'}, ...
{'real','vector', 'nonnan', '<=',1,'>=',0, 'nonempty'}, fcnName, argname);
end
isSizeMismatch = length(values) ~= 1 && length(values) ~= len;
coder.internal.errorIf(isSizeMismatch,...
'robotics:robotalgs:occgridcommon:InputSizeMismatch');
end
end
end
function linSpace = getIntLineSpace()
%getIntLineSpace Generate line space for integer log-odds
defaultType = OccupancyGrid.DefaultType;
linSpace = intmin(defaultType):intmax(defaultType);
end
function lookup = createLookupTable()
%createLookupTable Create lookup table for integer log-odds to probability
numOfPoints = abs(double(intmin(OccupancyGrid.DefaultType)))+...
double(intmax(OccupancyGrid.DefaultType))+1;
logOddsLimits = OccupancyGrid.probToLogodds(OccupancyGrid.ProbMaxSaturation);
lookup = single(OccupancyGrid.logoddsToProb(...
linspace(logOddsLimits(1), logOddsLimits(2), numOfPoints)));
end
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
AIM_Optimal.m
|
.m
|
PlatoonBased-AIM-master/Matlab2/AIM_Optimal.m
| 13,139 |
utf_8
|
bd8a3a8dbf63c5717afdaf44da5e5b26
|
function [F,callCounter,packets,var,AverageDelayPerVehicle,AverageDelayPerPlatoon,totalVehicles,totalVehiclesCrossed] = AIM_Optimal(policyName,ver,seed,granularity,platoonMaxSize,spawnRate,duration,simSpeed,handles)
tic;
rng(seed);
packetsFromPlatoons = 0;
packetsToPlatoons = 0;
%Get Map, Show Map
intersectionData = intersection();
map = intersectionData.getMap(granularity);
show(map)
%title('Platoon-Based Intersection Management');
xlim([0 granularity]);
ylim([0 granularity]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Initialization and Constants
laneTraffic = zeros(1,4);
laneIsFull= zeros(1,4);
global simulationTime;
numVehiclesPassed = 0;
numPlatoonsPassed = 0;
currentAvgDelay = 0;
totalVehicles = [0 0 0 0];
totalVehiclesCrossed = [0 0 0 0];
%LaneTail is initialized to the stop points, this will dynamically change..
%as platoon stop for their turn.other platoons will use this data to stop
%right behind the last platoon in queue.
laneStop = [180 195;%for Lane 1
205 180;%for Lane 2
220 205;%for Lane 3
195 215;%for Lane 4
];
turns ={'straight' 'left' 'right'};
numOfPlatoons = 0;
numOfLanes = 4;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
frameCounter = 1;
F(frameCounter) = getframe(gcf);
%legend('Vehicle');
%stoppedByUser=0;
tic;
elapsedTime = toc;
%Spawn First Platoon
laneNumber = randi([1 numOfLanes]);
platoonLeader = vehicleModel(intersectionData.spawnPoints(laneNumber,:));
%Spawn The followers
platoonSize = randi([1 platoonMaxSize]);
turnDecision = turns{randi([1 3])};
platoons(numOfPlatoons+1) = vehiclePlatoon(platoonSize,platoonLeader,turnDecision,frameCounter);
numOfPlatoons = numOfPlatoons+1;
platoons(numOfPlatoons).addVehicle(platoonSize-1);
simulationTime = 5*simSpeed;
spawnPerSec = spawnRate/3600;
lastFrame = 0;
clearTime = 0;
times = 0;
laneCapacity = 16;
%legend('Stopped Platoon','Stopped Platoon','Stopped Platoon','Stopped Platoon');
newBatch = 1;
fps=2;
index=0;
gone = [];
numOfPlatoonsInSchedule=0;
callCounter = 0;
candidates = [0 0 0 0];
while(frameCounter<duration*fps)
set(handles.timeLabel,'String',sprintf('%.2fs',frameCounter/fps));
set(handles.crossedVehicles,'String',sprintf('%d',sum(totalVehiclesCrossed)));
if(mod(frameCounter,1)==0)%Spawn 4 platoons every 100 frames
for k=1:4
%Spawn New Platoons
%decide lane
%laneNumber = randi([1 numOfLanes]);
%decide turn
turnDecision = turns{randi([1 3])};
%decide platoon size
platoonSize = randi([1 platoonMaxSize]);
%Spawn Leader
prob = rand();
threshold = spawnPerSec*0.5/platoonSize;
if(prob<threshold && ((laneTraffic(k)+platoonSize)<laneCapacity))
totalVehicles(k) = totalVehicles(k) + platoonSize;
platoonLeader = vehicleModel(intersectionData.spawnPoints(k,:));
%Spawn The followers
platoons(numOfPlatoons+1) = vehiclePlatoon(platoonSize,platoonLeader,turnDecision,frameCounter);
numOfPlatoons = numOfPlatoons+1;
platoons(numOfPlatoons).addVehicle(platoonSize-1);
laneTraffic(k) = laneTraffic(k) +platoonSize;
if(laneTraffic(k)>laneCapacity)
laneIsFull(k)=1;
else
laneIsFull(k)=0;
end
end
end
end
%Get Solution%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
arrivals = [];
lengths = [];
waitings = [];
packetsFromPlatoons = packetsFromPlatoons + length(platoons);
indices = 1:length(platoons);
indices(gone) = [];
if(isempty(indices))
drawnow;
frameCounter = frameCounter+1;
%F(frameCounter) = getframe(gcf);
continue;
else
for j=indices
if (j==1)
waitings = [1 platoons(j).waitingTime platoons(j).arrivalTime];
%arrivals = [1 platoons(j).arrivalTime];
else
waitings = [waitings; j platoons(j).waitingTime platoons(j).arrivalTime];
%lengths = [lengths; j platoons(j).platoonSize];
end
end
schedule2 = sortrows(waitings,[3]);
sortedList = [schedule2(:,1)'];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
counter = 0;
timePassed = frameCounter-lastFrame;
lastCandidates = candidates;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if(newBatch==1 || ver==2)%index>numOfPlatoonsInSchedule || index==0)
candidates = [0 0 0 0];
candidateCounter = 0;
for pt=sortedList
if(candidateCounter==4)
break
else
lane = platoons(pt).arrivalLane;
if(candidates(lane)==0 && ~strcmp(platoons(pt).state,'crossing') ...
&& ~strcmp(platoons(pt).state,'done')...
&& platoons(pt).arrivalTime<=clearTime)
candidates(lane)=pt;
candidateCounter = candidateCounter+1;
end
end
end
candidates = candidates(candidates~=0);
if(~isempty(candidates))
if(length(candidates)~=length(lastCandidates))
newSchedule = greedySort(candidates);
callCounter = callCounter+1;
newBatch = 0;
numOfPlatoonsInSchedule = length(newSchedule);
index = 1;
elseif(candidates~=lastCandidates)
newSchedule = greedySort(candidates);
callCounter = callCounter+1;
newBatch = 0;
numOfPlatoonsInSchedule = length(newSchedule);
index = 1;
else
newSchedule = greedySort(candidates);
newBatch = 0;
numOfPlatoonsInSchedule = length(newSchedule);
index = 1;
end
else
newSchedule = 0;
index = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=sortedList
if(index>0 && index <=numOfPlatoonsInSchedule)
whosTurn = newSchedule(index);
else
whosTurn=0;
end
if(isvalid(platoons(j)))
if(strcmp(platoons(j).state,'done'))
gone = [gone j];
end
timePassed = frameCounter-lastFrame;
if(timePassed>=clearTime && j==whosTurn ...
&& (strcmp(platoons(j).state,'stopandwait')...
|| strcmp(platoons(j).state,'moveandwait')))
index = index + 1;
if(index>numOfPlatoonsInSchedule)
newBatch=1;
end
packetsToPlatoons = packetsToPlatoons + 1;
packetsFromPlatoons = packetsFromPlatoons + 1;
platoons(j).setPath(intersectionData.getTrajectory(platoons(j).arrivalLane,platoons(j).turn),frameCounter);
arrival = platoons(j).arrivalTime;
totalVehiclesCrossed(platoons(j).arrivalLane) = totalVehiclesCrossed(platoons(j).arrivalLane) + platoons(j).platoonSize; %counter = counter + 1;
clearTime = arrival + (25+(platoons(j).platoonSize*8))/(platoons(j).linearVelocity*simulationTime);
lastFrame = frameCounter;
laneTraffic(platoons(j).arrivalLane) = laneTraffic(platoons(j).arrivalLane) -platoons(j).platoonSize;
if(laneTraffic(platoons(j).arrivalLane)>laneCapacity)
laneIsFull(platoons(j).arrivalLane)=1;
else
laneIsFull(platoons(j).arrivalLane)=0;
end
%counter = counter + 1;
for ii= sortedList(find(sortedList==j,1)+1:end)
platoons(ii).updateStopPoint(platoons(j).stopPoints(platoons(j).arrivalLane,:),platoons(j).arrivalLane);
end
end
drive(platoons(j),simulationTime,frameCounter,true);
if(strcmp(platoons(j).state,'stopandwait')...
|| strcmp(platoons(j).state,'moveandwait'))
for ii= sortedList(find(sortedList==j,1)+1:end)
platoons(ii).updateStopPoint(platoons(j).tail(),platoons(j).arrivalLane);
end
end
end
end
drawnow;
frameCounter = frameCounter+1;
%platoonSizeSetting = platoonMaxSize
%SimulationTime = frameCounter/2
F(frameCounter) = getframe(gcf);
%tic;
%pause(time/1000);
%times = [times toc-elapsedTime];
%elapsedTime = toc;
%platoons = sort(platoons);
end
end
aveTime = mean(times);
delays = [];
platoonDelays = [];
for j=1:length(platoons)
if(isvalid(platoons(j)))
if(strcmp(platoons(j).state,'done') || strcmp(platoons(j).state,'crossing'))
%totalVehiclesCrossed(platoons(j).arrivalLane) = totalVehiclesCrossed(platoons(j).arrivalLane) + platoons(j).platoonSize;
delay =platoons(j).totalWaiting/fps;
if(delay>=0)
platoonDelays = [platoonDelays delay];
for(i=1:platoons(j).platoonSize)
delays = [delays delay];
end
end
elseif(platoons(j).waitingTime>=0)
delay = platoons(j).waitingTime/fps;
platoonDelays = [platoonDelays delay];
for(i=1:platoons(j).platoonSize)
delays = [delays delay];
end
end
delete(platoons(j));
end
end
delays = delays;
platoonDelays = platoonDelays;
AverageDelayPerVehicle = mean(delays);
AverageDelayPerPlatoon = mean(platoonDelays);
packets = packetsFromPlatoons+packetsToPlatoons;
var = sum(delays.^2)/(length(delays)-1) - (length(delays))*mean(delays)^2/(length(delays)-1);
function sol = getSchedule(lengths,waitingTimes)
[sorted sol] = sort(waitingTimes,'descend');
end
function sol = getSchedule2(lengths,arrivalTimes)
[sorted sol] = sort(arrivalTimes);
end
function [newSchedule] = greedySort(candidates)
minimumDelay = inf;
newSchedule = candidates;
clearTimes = getClearTimes(candidates);
permutations = perms(candidates);
for i=1:size(permutations,1)
maxDelay = 0;
extraWaitTime = max(clearTime - platoons(permutations(i,1)).arrivalTime ,0);
extraWait = extraWaitTime>0;
delayPerVehicle = (platoons(permutations(i,1)).waitingTime*extraWait +...
extraWaitTime)*...
platoons(permutations(i,1)).platoonSize;
totalDelay = clearTimes(find(candidates ==permutations(i,1),1))+clearTime+...
+max(platoons(permutations(i,1)).arrivalTime-clearTime,0);
%delayPerVehicle = delayPerVehicle+...
% platoons(permutations(i,1)).waitingTime*...
% platoons(permutations(i,1)).platoonSize;
%delayPerVehicle=0;
%delayPerVehicle = delayPerVehicle +...
% platoons(permutations(i,1)).waitingTime*...
% platoons(permutations(i,1)).platoonSize;
if(delayPerVehicle>maxDelay)
maxDelay = delayPerVehicle;
end
for j=2:size(permutations,2)
extraWaitTime = max(totalDelay - platoons(permutations(i,j)).arrivalTime ,0);
extraWait = extraWaitTime>0;
if(strcmp(policyName,'pdm'))
delayPerVehicle =delayPerVehicle+(extraWait*platoons(permutations(i,j)).waitingTime+...
extraWaitTime)*...
platoons(permutations(i,j)).platoonSize;
else
delayPerVehicle =delayPerVehicle+ j*(extraWait*platoons(permutations(i,j)).waitingTime+...
extraWaitTime)*...
platoons(permutations(i,j)).platoonSize;
end
%platoons(permutations(i,j)).waitingTime+
%laneTraffic(platoons(permutations(i,j)).arrivalLane);
%platoons(permutations(i,j)).platoonSize;
% + ...
totalDelay = totalDelay+max(platoons(permutations(i,j)).arrivalTime - totalDelay,0) + ...
clearTimes(find(candidates ==permutations(i,j),1));
if(delayPerVehicle>maxDelay)
maxDelay = delayPerVehicle;
end
end
if(delayPerVehicle<minimumDelay)
minimumDelay = delayPerVehicle;
newSchedule = permutations(i,:);
end
end
end
function clearTimes = getClearTimes(candidates)
for i=1:length(candidates)
if(candidates(i)==0)
pSize(i) = 0;
else
pSize(i) = platoons(candidates(i)).platoonSize;
end
end
constants = zeros(1,length(candidates)).*25;
clearTimes = (constants+(pSize.*8))./(simulationTime);
end
end
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
intersection.m
|
.m
|
PlatoonBased-AIM-master/Matlab2/intersection.m
| 6,087 |
utf_8
|
c8d83f6e75ff575d165c9f3adf6d0cb6
|
classdef intersection < handle
properties(SetAccess = private)
granularity;
lineWidth;
lanePerRoad;
end
properties(SetAccess = public)
spawnPoints = [20 195 0;%for Lane 1
205 20 pi/2;%for Lane 2
380 205 pi;%for Lane 3
195 380 -pi/2;%for Lane 4
];
stopPoints = [180 195;%for Lane 1
205 180;%for Lane 2
220 205;%for Lane 3
195 215;%for Lane 4
];
endPoints = [20 205;
195 20;
380 195;
205 380;];
lane1To4 = [180 195;%Lane 1 Turn left
190 195;
195 200;
200 205;
202 210;
205 220;
205 380];
lane1To3 = [180 195;%Lane 1 Go Straight
190 195;
195 195;
200 195;
205 195;
240 195;
380 195];
lane1To2 = [180 195;%Lane 1 Turn right
185 195;
190 195;
192 195;
194 185;
195 145;
195 20];
lane2To3 = [205 180;%Lane 2 turn right
205 185;
205 190;
205 192;
215 195;
275 195;
380 195];
lane2To4 = [205 180;%Lane 2 go straight
205 190;
205 195;
205 200;
205 205;
205 245;
205 380];
lane2To1 = [205 180;
205 190;
205 195;
200 200;
190 205;
130 205;
20 205];%Lane 2 turn left
lane3To4 = [220 205;
210 205;
207 205;
205 210;
205 220;
205 280;
205 380];%Lane 3 turn right
lane3To1 = [220 205;
210 205;
200 205;
160 205;
100 205;
50 205;
20 205];%Lane 3 go straight
lane3To2 = [220 205;
205 205;
200 200;
195 195;
195 190;
195 130;
195 20];%Lane 3 turn left
lane4To1 = [195 220;
195 210;
190 208;
180 205;
130 205;
80 205;
20 205];%Lane 4 turn right
lane4To2 = [195 220;
195 210;
195 205;
195 200;
195 195;
195 155;
195 20;]%Lane 4 go straight
lane4To3 = [195 220;
195 205;
200 200;
205 195;
220 195;
280 195;
380 195;]%Lane 4 turn left
trajectories;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods(Access=public)
function path = getTrajectory(obj,arrivalLane,turn)
switch turn
case 'right'
offset=1;
case 'straight'
offset=2;
case 'left'
offset=3;
end
index = (arrivalLane-1)*3+offset;
path = obj.trajectories(:,:,index);
end
end
methods(Static)
function obj = intersection()
obj.granularity = 400;
obj.lineWidth = 1;
obj.lanePerRoad = 1;
obj.trajectories = obj.lane1To2;%Lane 1 turn right
obj.trajectories(:,:,2) = obj.lane1To3;%Lane 1 go straight
obj.trajectories(:,:,3) = obj.lane1To4;%Lane 1 turn left
obj.trajectories(:,:,4) = obj.lane2To3;%Lane 2 turn right
obj.trajectories(:,:,5) = obj.lane2To4;%Lane 2 go straight
obj.trajectories(:,:,6) = obj.lane2To1;%Lane 2 turn left
obj.trajectories(:,:,7) = obj.lane3To4;%Lane 3 turn right
obj.trajectories(:,:,8) = obj.lane3To1;%Lane 3 go straight
obj.trajectories(:,:,9) = obj.lane3To2;%Lane 3 turn left
obj.trajectories(:,:,10) = obj.lane4To1;%Lane 4 turn right
obj.trajectories(:,:,11) = obj.lane4To2;%Lane 4 go straight
obj.trajectories(:,:,12) = obj.lane4To3;%Lane 4 turn left
end
function map = getMap(varargin)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
numvarargs = length(varargin);
if numvarargs > 3
error('gridMapGenerator: TooManyInputs', ...
'This function takes 1-3 input arguments');
end
optargs = {200 1 1};
optargs(1:numvarargs) = varargin;
[granularity lineWidth lanePerRoad] = optargs{:};
obj.granularity = granularity;
obj.lineWidth = lineWidth;
obj.lanePerRoad = lanePerRoad;
%granularity = 200;
%lineWidth = 1;
intersectionGridMap = zeros(granularity, granularity);
bottomOfLane = 0.5*granularity-10;
topOfLane = 0.5* granularity+10;
intersectionGridMap(bottomOfLane:bottomOfLane+lineWidth,1:bottomOfLane)=1;
intersectionGridMap(bottomOfLane:bottomOfLane+lineWidth,topOfLane:end)=1;
intersectionGridMap(topOfLane:topOfLane+lineWidth,1:bottomOfLane)=1;
intersectionGridMap(topOfLane:topOfLane+lineWidth,topOfLane:end)=1;
intersectionGridMap(1:bottomOfLane+lineWidth,bottomOfLane:bottomOfLane+lineWidth)=1;
intersectionGridMap(topOfLane:end,bottomOfLane:bottomOfLane+lineWidth)=1;
intersectionGridMap(1:bottomOfLane,topOfLane:topOfLane+lineWidth)=1;
intersectionGridMap(topOfLane:end,topOfLane:topOfLane+lineWidth)=1;
intersectionGridMap(0.5*granularity,1:bottomOfLane)=0.5;
intersectionGridMap(0.5*granularity,topOfLane+lineWidth:end)=0.5;
intersectionGridMap(1:bottomOfLane,0.5*granularity)=0.5;
intersectionGridMap(topOfLane+lineWidth:end,0.5*granularity)=0.5;
intersectionGridMap(1:bottomOfLane,1:bottomOfLane)=0.7;
intersectionGridMap(1:bottomOfLane,topOfLane+lineWidth:end)=0.7;
intersectionGridMap(topOfLane+lineWidth:end,1:bottomOfLane)=0.7;
intersectionGridMap(topOfLane+lineWidth:end,topOfLane+lineWidth:end)=0.7;
intersectionGridMap = intersectionGridMap';
map = OccupancyGrid(intersectionGridMap);
end
end
end
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
simulator.m
|
.m
|
PlatoonBased-AIM-master/Matlab2/simulator.m
| 27,407 |
utf_8
|
cf0a2074baee1fc10130713ee54d1d6e
|
function varargout = simulator(varargin)
% SIMULATOR MATLAB code for simulator.fig
%%
%%
% SIMULATOR, by itself, creates a new SIMULATOR or raises the existing
% singleton*.
%
% H = SIMULATOR returns the handle to a new SIMULATOR or the handle to
% the existing singleton*.
%
% SIMULATOR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SIMULATOR.M with the given input arguments.
%
% SIMULATOR('Property','Value',...) creates a new SIMULATOR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before simulator_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to simulator_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help simulator
% Last Modified by GUIDE v2.5 02-Jan-2017 18:06:33
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @simulator_OpeningFcn, ...
'gui_OutputFcn', @simulator_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before simulator is made visible.
function simulator_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to simulator (see VARARGIN)
% Choose default command line output for simulator
handles.output = hObject;
% Update handles structure
handles.simTime = 500;
handles.readyColor = [1 1 1];
handles.runningColor = [104/255 151/255 187/255];
handles.finishedColor = [102/255 205/255 170/255];
handles.savingColor = [211/255 71/255 31/255];
grid on;
grid minor;
guidata(hObject, handles);
axes(handles.axes1);
%title('Platoon-Based Autonomous Intersection Management');
xlim([0 400]);
ylim([0 400]);
%grid on
%grid minor
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','off');
%axes(handles.axes1);
% UIWAIT makes simulator wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = simulator_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject handle to start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%clf;
handles.simTime = round(get(handles.duration,'Value'));
handles.simSpeed = round(get(handles.simulationSpeed,'Value'));
handles.spawnRate = round(get(handles.spawn,'Value'));
axes(handles.axes1);
g = 400;
contents = str2double(get(handles.platoonSize,'String'));
maxSize= contents(get(handles.platoonSize,'Value'));
set(handles.resetbutton,'Enable','on');
set(handles.savevideo,'Enable','off');
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.runningColor);
set(handles.status, 'String','Simulation is Running');
policyNumber = get(handles.policy,'Value');
seed = 12345;
if(policyNumber==1)
[handles.F,p,var,vDelay,pDelay,tv,tvc] = AIM(seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
elseif(policyNumber==2)
% [handles.Fcc,p,var,vDelay,pDelay,tv,tvc] = AIM_Optimal(1,seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
% vDelay
% var
% cc
[handles.F,cc,p,var,vDelay,pDelay,tv,tvc] = AIM_Optimal('pdm',2,seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
vDelay
var
cc
elseif(policyNumber==3)
% [handles.Fcc,p,var,vDelay,pDelay,tv,tvc] = AIM_Optimal(1,seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
% vDelay
% var
% cc
[handles.F,cc,p,var,vDelay,pDelay,tv,tvc] = AIM_Optimal('pvm',2,seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
vDelay
var
cc
end
fprintf('The Average Delay per Vehicle is %f\n', vDelay)
guidata(hObject,handles);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Finished');
set(handles.start,'Enable','on');
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','on');
% --- Executes on selection change in granularity.
function granularity_Callback(hObject, eventdata, handles)
% hObject handle to granularity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns granularity contents as cell array
% contents{get(hObject,'Value')} returns selected item from granularity
% --- Executes during object creation, after setting all properties.
function granularity_CreateFcn(hObject, eventdata, handles)
% hObject handle to granularity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in resetbutton.
function resetbutton_Callback(hObject, eventdata, handles)
% hObject handle to resetbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%axes(handles.axes1);
%error('stop requested by user');
%handles.stop=1;
%guidata(hObject,handles);
%clc;
cla;
grid on;
grid minor;
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Ready!');
set(handles.start,'Enable','on');
set(handles.savevideo,'Enable','off');
% --- Executes on slider movement.
function duration_Callback(hObject, eventdata, handles)
% hObject handle to duration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.simTime = round(get(hObject,'Value'));
labelText = strcat(num2str(handles.simTime),' Sec.');
set(handles.durationlabel,'String',labelText);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function duration_CreateFcn(hObject, eventdata, handles)
% hObject handle to duration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on slider movement.
function slider2_Callback(hObject, eventdata, handles)
% hObject handle to slider2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% --- Executes during object creation, after setting all properties.
function slider2_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on button press in exit.
function exit_Callback(hObject, eventdata, handles)
% hObject handle to exit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(gcf);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over start.
function start_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in savevideo.
function savevideo_Callback(hObject, eventdata, handles)
% hObject handle to savevideo (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.savingColor);
set(handles.status, 'String','Saving Video');
pause(0.5);
policyNumber = get(handles.policy,'Value');
uniqueNumber = num2str(randi([0 100])*100+policyNumber);
video = VideoWriter(strcat('AIM-Demo-',uniqueNumber),'MPEG-4');
video.FrameRate = 20;
open(video);
writeVideo(video,handles.F);
close(video);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Video was saved to File!');
set(handles.start,'Enable','on');
% --- Executes on slider movement.
function slider5_Callback(hObject, eventdata, handles)
% hObject handle to slider5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% --- Executes during object creation, after setting all properties.
function slider5_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on selection change in platoonSize.
function platoonSize_Callback(hObject, eventdata, handles)
% hObject handle to platoonSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns platoonSize contents as cell array
% contents{get(hObject,'Value')} returns selected item from platoonSize
% --- Executes during object creation, after setting all properties.
function platoonSize_CreateFcn(hObject, eventdata, handles)
% hObject handle to platoonSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on slider movement.
function simulationSpeed_Callback(hObject, eventdata, handles)
% hObject handle to simulationSpeed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.simSpeed = round(get(hObject,'Value'));
labelText = strcat(num2str(handles.simSpeed),'X');
set(handles.speedlabel,'String',labelText);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function simulationSpeed_CreateFcn(hObject, eventdata, handles)
% hObject handle to simulationSpeed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on slider movement.
function spawn_Callback(hObject, eventdata, handles)
% hObject handle to spawn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.spawnRate = round(get(hObject,'Value'));
labelText = strcat(num2str(handles.spawnRate),' Veh/H/L');
set(handles.spawnLabel,'String',labelText);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function spawn_CreateFcn(hObject, eventdata, handles)
% hObject handle to spawn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on selection change in policy.
function policy_Callback(hObject, eventdata, handles)
% hObject handle to policy (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns policy contents as cell array
% contents{get(hObject,'Value')} returns selected item from policy
% --- Executes during object creation, after setting all properties.
function policy_CreateFcn(hObject, eventdata, handles)
% hObject handle to policy (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in experiment.
function experiment_Callback(hObject, eventdata, handles)
% hObject handle to experiment (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.simTime = round(get(handles.duration,'Value'));
handles.simSpeed = round(get(handles.simulationSpeed,'Value'));
handles.spawnRate = round(get(handles.spawn,'Value'));
axes(handles.axes1);
g = 400;
contents = str2double(get(handles.platoonSize,'String'));
maxSize= contents(get(handles.platoonSize,'Value'));
set(handles.resetbutton,'Enable','on');
set(handles.savevideo,'Enable','off');
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.runningColor);
set(handles.status, 'String','Simulation is Running');
policyNumber = get(handles.policy,'Value');
totalVehicles = 0;
totalVehiclesCrossed = 0;
trafficFlows = [];
counter=0;
seed = 1234;
for j = 500:100:2000
trafficFlows = [trafficFlows j];
counter = counter+1;
n_exp = 1;
for i=1:8
seed = 1234;
if(policyNumber==1)
p = zeros(1,n_exp);
v = zeros(1,n_exp);
vDelay = zeros(1,n_exp);
pDelay = zeros(1,n_exp);
fprintf('Max_Platoon = %d, Traffic Level = %d\n',i,j);
for n=1:n_exp
seed = seed+n;
[p(n),v(n),vDelay(n),pDelay(n),tv,tvc] = AIM(seed,g,i,j,handles.simTime,handles.simSpeed,handles);
fprintf('Experiment #%d\n',n);
Average_Delay_Per_Vehicle = vDelay(n)
cla
end
fprintf('Max_Platoon = %d, Traffic Level = %d\n',i,j);
v;
vDelay;
packets(i,counter) = mean(p);
var(i,counter) = mean(v);
AverageDelayPerVehicle(i,counter) = mean(vDelay)
AverageDelayPerPlatoon(i,counter) = mean(pDelay);
elseif(policyNumber==2)
[p,var(i,counter),vDelay,pDelay,tv,tvc] = AIM_Optimal(g,i,j,handles.simTime,handles.simSpeed,handles);
packets(i,counter)=p;
AverageDelayPerVehicle(i,counter) = vDelay;
AverageDelayPerPlatoon(i,counter) = pDelay;
end
%totalVehicles(i,counter) = sum(tv);
%totalVehiclesCrossed(i,counter) = sum(tvc);
%AverageDelayPerVehicle
%packets
end
end
figure
plot(trafficFlows,AverageDelayPerVehicle(1,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(2,:),'color','g','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(4,:),'color','c','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(5,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(6,:),'color','m','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(7,:),'color','y','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(8,:),'color',[0.545 0.27 0.074],'marker','o','lineStyle','--','lineWidth',1);
legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6' ...
,'Max-Platoon-Size=7','Max-Platoon-Size=8');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Average Delay (S)');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
plot(trafficFlows,var(1,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(2,:),'color','g','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(4,:),'color','c','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(5,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(6,:),'color','m','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(7,:),'color','y','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(8,:),'color',[0.545 0.27 0.074],'marker','o','lineStyle','--','lineWidth',1);
legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6' ...
,'Max-Platoon-Size=7','Max-Platoon-Size=8');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Travel Delay Variance (S^2)');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
plot(trafficFlows,packets(1,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(2,:),'color','g','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(4,:),'color','c','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(5,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(6,:),'color','m','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(7,:),'color','y','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(8,:),'color',[0.545 0.27 0.074],'marker','o','lineStyle','--','lineWidth',1);
legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6' ...
,'Max-Platoon-Size=7','Max-Platoon-Size=8');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('# Packets Exchanged');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure
% congestion = totalVehicles-totalVehiclesCrossed
% plot(trafficFlows,congestion(1,:),'ro-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(2,:),'bo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(3,:),'mo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(4,:),'go-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(5,:),'ko-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(6,:),'co-.','lineWidth',2);
% legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
% ,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6');
% title('Average Congestion');
guidata(hObject,handles);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Finished');
set(handles.start,'Enable','on');
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','on');
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.simTime = round(get(handles.duration,'Value'));
handles.simSpeed = round(get(handles.simulationSpeed,'Value'));
handles.spawnRate = round(get(handles.spawn,'Value'));
axes(handles.axes1);
g = 400;
contents = str2double(get(handles.platoonSize,'String'));
maxSize= contents(get(handles.platoonSize,'Value'));
set(handles.resetbutton,'Enable','on');
set(handles.savevideo,'Enable','off');
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.runningColor);
set(handles.status, 'String','Simulation is Running');
policyNumber = get(handles.policy,'Value');
totalVehicles = 0;
totalVehiclesCrossed = 0;
trafficFlows = [];
counter=0;
seed = 1234;
callCounter=[];
%for kk =1:6
% seed = 1233+kk;
for j = 500:100:2000
trafficFlows = [trafficFlows j];
counter = counter+1;
[p,var(1,counter),vDelay,pDelay,tv,tvc] = AIM(seed,g,maxSize,j,handles.simTime,handles.simSpeed,handles);
packets(1,counter) = p;
AverageDelayPerVehicle(1,counter) = vDelay
AverageDelayPerPlatoon(1,counter) = pDelay;
cla
ver=1;
[callCounter(1,counter),p,var(2,counter),vDelay,pDelay,tv,tvc] = AIM_Optimal(ver,seed,g,maxSize,j,handles.simTime,handles.simSpeed,handles);
packets(2,counter)=p;
AverageDelayPerVehicle(2,counter) = vDelay
AverageDelayPerPlatoon(2,counter) = pDelay;
cla
ver=2;
[callCounter(2,counter),p,var(3,counter),vDelay,pDelay,tv,tvc] = AIM_Optimal(ver,seed,g,maxSize,j,handles.simTime,handles.simSpeed,handles);
packets(3,counter)=p;
AverageDelayPerVehicle(3,counter) = vDelay
var
AverageDelayPerPlatoon(3,counter) = pDelay;
callCounter;
end
%end
figure
plot(trafficFlows,AverageDelayPerVehicle(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
legend('Policy = StopSign','Policy = Optimal','Policy = Optimal-Updating');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Average Delay (S)');
grid minor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
plot(trafficFlows,var(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
legend('Policy = StopSign','Policy = Optimal','Policy = Optimal-Updating');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Travel Delay Variance (S^2)');
grid minor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure
% plot(trafficFlows,packets(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
% hold on
% plot(trafficFlows,packets(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
% hold on
% plot(trafficFlows,packets(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
% legend('Policy = StopSign','Policy = Optimal','Policy = Optimal-Updating');
% xlabel('Traffic Level (Vehicle/Hour/Lane)');
% ylabel('# Packets Exchanged With the Infrastructure');
% grid minor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure
% congestion = totalVehicles-totalVehiclesCrossed
% plot(trafficFlows,congestion(1,:),'ro-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(2,:),'bo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(3,:),'mo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(4,:),'go-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(5,:),'ko-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(6,:),'co-.','lineWidth',2);
% legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
% ,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6');
% title('Average Congestion');
guidata(hObject,handles);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Finished');
set(handles.start,'Enable','on');
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','on');
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
OccupancyGrid.m
|
.m
|
PlatoonBased-AIM-master/Matlab/OccupancyGrid.m
| 54,073 |
utf_8
|
48a2d107b354fe119551901e2740db99
|
classdef (Sealed)OccupancyGrid <OccupancyGridBase
%OCCUPANCYGRID Create an occupancy grid
% OCCUPANCYGRID creates a 2D occupancy grid map. Each cell has
% a value representing the probability of occupancy of that cell.
% Probability values close to 1 represent certainty that the workspace
% represented by the cell is occupied by an obstacle. Values close to 0
% represent certainty that the workspace represented by the cell is not
% occupied and is obstacle-free.
%
% The probability values in the occupancy grid are stored with
% a precision of at least 1e-3 to reduce memory usage and allow creation of
% occupancy grid objects to represent large workspace. The minimum and
% maximum probability that can be represented are 0.001 and 0.999
% respectively.
%
% MAP = robotics.OccupancyGrid(W, H) creates a 2D occupancy grid
% object representing a world space of width(W) and height(H) in
% meters. The default grid resolution is 1 cell per meter.
%
% MAP = robotics.OccupancyGrid(W, H, RES) creates an OccupancyGrid
% object with resolution(RES) specified in cells per meter.
%
% MAP = robotics.OccupancyGrid(M, N, RES, 'grid') creates an
% OccupancyGrid object and specifies a grid size of M rows and N columns.
% RES specifies the cells per meter resolution.
%
% MAP = robotics.OccupancyGrid(P) creates an occupancy grid object
% from the values in the matrix, P. The size of the grid matches the
% matrix with each cell value interpreted from that matrix location.
% Matrix, P, may contain any numeric type with values between zero(0)
% and one(1).
%
% MAP = robotics.OccupancyGrid(P, RES) creates an OccupancyGrid
% object from matrix, P, with RES specified in cells per meter.
%
% OccupancyGrid properties:
% FreeThreshold - Threshold to consider cells as obstacle-free
% OccupiedThreshold - Threshold to consider cells as occupied
% ProbabilitySaturation - Saturation limits on probability values as [min, max]
% GridSize - Size of the grid in [rows, cols] (number of cells)
% Resolution - Grid resolution in cells per meter
% XWorldLimits - Minimum and maximum values of X
% YWorldLimits - Minimum and maximum values of Y
% GridLocationInWorld - Location of grid in world coordinates
%
%
% OccupancyGrid methods:
% checkOccupancy - Check locations for free, occupied or unknown
% copy - Create a copy of the object
% getOccupancy - Get occupancy of a location
% grid2world - Convert grid indices to world coordinates
% inflate - Inflate each occupied grid location
% insertRay - Insert rays from laser scan observation
% occupancyMatrix - Convert occupancy grid to double matrix
% raycast - Compute cell indices along a ray
% rayIntersection - Compute map intersection points of rays
% setOccupancy - Set occupancy of a location
% show - Show grid values in a figure
% updateOccupancy - Integrate probability observation at a location
% world2grid - Convert world coordinates to grid indices
%
%
% Example:
%
% % Create a 2m x 2m empty map
% map = robotics.OccupancyGrid(2,2);
%
% % Create a 10m x 10m empty map with resolution 20
% map = robotics.OccupancyGrid(10, 10, 20);
%
% % Insert a laser scan in the occupancy grid
% ranges = 5*ones(100, 1);
% angles = linspace(-pi/2, pi/2, 100);
% insertRay(map, [5,5,0], ranges, angles, 20);
%
% % Show occupancy grid in Graphics figure
% show(map);
%
% % Create a map from a matrix with resolution 20
% p = eye(100)*0.5;
% map = robotics.OccupancyGrid(p, 20);
%
% % Check occupancy of the world location (0.3, 0.2)
% value = getOccupancy(map, [0.3 0.2]);
%
% % Set world position (1.5, 2.1) as occupied
% setOccupancy(map, [1.5 2.1], 0.8);
%
% % Get the grid cell indices for world position (2.5, 2.1)
% ij = world2grid(map, [2.5 2.1]);
%
% % Set the grid cell indices to unoccupied
% setOccupancy(map, [1 1], 0.2, 'grid');
%
% % Integrate occupancy observation at a location
% updateOccupancy(map, [1 1], 0.7);
%
% % Show occupancy grid in Graphics figure
% show(map);
%
% See also robotics.MonteCarloLocalization, robotics.BinaryOccupancyGrid.
% Copyright 2016 The MathWorks, Inc.
%#codegen
%%
properties (Dependent)
%OccupiedThreshold Probability threshold to consider cells as occupied
% A scalar representing the probability threshold above which
% cells are considered to be occupied. The OccupiedThreshold will be
% saturated based on ProbabilitySaturation property.
%
% Default: 0.65
OccupiedThreshold
%FreeThreshold Probability threshold to consider cells as obstacle-free
% A scalar representing the probability threshold below which
% cells are considered to be obstacle-free. The FreeThreshold will be
% saturated based on ProbabilitySaturation property.
%
% Default: 0.20
FreeThreshold
%ProbabilitySaturation Saturation values for probability
% A vector [MIN MAX] representing the probability saturation
% values. The probability values below MIN value will be saturated to
% MIN and above MAX values will be saturated to MAX. The MIN
% value cannot be below 0.001 and MAX value cannot be above 0.999.
%
% Default: [0.001 0.999]
ProbabilitySaturation
end
properties (Access = public)
%Logodds Internal log-odds representation for probability
Logodds
end
properties (Access = protected, Constant)
%DefaultType Default datatype used for log-odds
DefaultType = 'int16';
%ProbMaxSaturation Maximum probability saturation possible
ProbMaxSaturation = [0.001 0.999]
%LookupTable Lookup table to convert between log-odds and probability
LookupTable = createLookupTable();
%LinSpaceInt16 The line space for all integer log-odds values
LinSpaceInt16 = getIntLineSpace();
end
properties (Access = private)
%FreeThresholdIntLogodds Integer log-odds values for FreeThreshold
% The log-odds value correspond to the default threshold of 0.2
FreeThresholdIntLogodds
%OccupiedThresholdIntLogodds Integer log-odds values for OccupiedThreshold
% The log-odds value correspond to the default threshold of 0.65
OccupiedThresholdIntLogodds
end
properties (Access = public)
%LogoddsHit Integer log-odds value for update on sensor hit
% This is the default log-odds value used to update grid cells
% where a hit is detected. This value represents probability
% value of 0.7
LogoddsHit
%LogoddsMiss Integer log-odds value for update on sensor miss
% This is the default log-odds value used to update grid cells
% where a miss is detected (i.e. laser ray passes through grid
% cells). This value represents probability value of 0.4
LogoddsMiss
%ProbSatIntLogodds Int log-odds for saturation
% These values correspond to default ProbabilitySaturation
% values of [0.001 0.999]
ProbSatIntLogodds
end
methods
function set.OccupiedThreshold(obj,threshold)
freeThreshold = obj.intLogoddsToProb(obj.FreeThresholdIntLogodds);
validateattributes(threshold, {'numeric'}, ...
{'scalar', 'real', 'nonnan', 'finite', 'nonnegative'}, ...
'OccupiedThreshold');
logOddsThreshold = obj.probToIntLogodds(double(threshold));
check = obj.FreeThresholdIntLogodds > logOddsThreshold;
if check
if coder.target('MATLAB')
error(message('robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'OccupiedThreshold', ...
'>=', num2str(freeThreshold,'%.3f')));
else
coder.internal.errorIf(check, 'robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'OccupiedThreshold', ...
'>=', coder.internal.num2str(freeThreshold));
end
end
obj.OccupiedThresholdIntLogodds = logOddsThreshold;
end
function threshold = get.OccupiedThreshold(obj)
threshold = double(obj.intLogoddsToProb(obj.OccupiedThresholdIntLogodds));
end
function set.FreeThreshold(obj,threshold)
occupiedThreshold = obj.intLogoddsToProb(obj.OccupiedThresholdIntLogodds);
validateattributes(threshold, {'numeric'}, ...
{'scalar', 'real', 'nonnan', 'finite', 'nonnegative'}, ...
'FreeThreshold');
logOddsThreshold = obj.probToIntLogodds(double(threshold));
check = obj.OccupiedThresholdIntLogodds < logOddsThreshold;
if check
if coder.target('MATLAB')
error(message('robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'FreeThreshold', ...
'<=', num2str(occupiedThreshold,'%.3f')));
else
coder.internal.errorIf(check, 'robotics:robotalgs:occgrid:ThresholdOutsideBounds', 'FreeThreshold', ...
'<=', coder.internal.num2str(occupiedThreshold));
end
end
obj.FreeThresholdIntLogodds = logOddsThreshold;
end
function threshold = get.FreeThreshold(obj)
threshold = double(obj.intLogoddsToProb(obj.FreeThresholdIntLogodds));
end
function set.ProbabilitySaturation(obj, sat)
% Run basic checks
validateattributes(sat, {'numeric'}, ...
{'vector', 'real', 'nonnan', 'numel', 2}, 'ProbabilitySaturation');
% Check the limits
sortedSat = sort(sat);
validateattributes(sortedSat(1), {'numeric'}, {'>=',obj.ProbMaxSaturation(1), ...
'<=',0.5}, ...
'ProbabilitySaturation', 'lower saturation');
validateattributes(sortedSat(2), {'numeric'}, {'>=',0.5, ...
'<=',obj.ProbMaxSaturation(2)}, ...
'ProbabilitySaturation', 'upper saturation');
obj.ProbSatIntLogodds = obj.probToIntLogoddsMaxSat(double([sortedSat(1), sortedSat(2)]));
obj.Logodds(obj.Logodds < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(obj.Logodds > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
end
function sat = get.ProbabilitySaturation(obj)
sat = double(obj.intLogoddsToProb(obj.ProbSatIntLogodds));
end
function obj = OccupancyGrid(varargin)
%OccupancyGrid Constructor
% Parse input arguments
narginchk(1,4);
[resolution, isGrid, mat, width, height, isMat]...
= obj.parseConstructorInputs(varargin{:});
% Assign properties with default values
obj.FreeThresholdIntLogodds = obj.probToIntLogoddsMaxSat(0.2);
obj.OccupiedThresholdIntLogodds = obj.probToIntLogoddsMaxSat(0.65);
obj.LogoddsHit = obj.probToIntLogoddsMaxSat(0.7);
obj.LogoddsMiss = obj.probToIntLogoddsMaxSat(0.4);
obj.ProbSatIntLogodds = [intmin(obj.DefaultType), intmax(obj.DefaultType)];
% Apply probability saturation to matrix
mat(mat < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
mat(mat > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
obj.Resolution = resolution;
% Construct grid from a matrix input
if isMat
obj.Logodds = mat;
obj.GridSize = size(obj.Logodds);
return;
end
% Construct empty grid from width and height
if isGrid
obj.Logodds = mat;
else
gridsize = size(mat);
% Throw a warning if we round off the grid size
if any(gridsize ~= ([height, width]*obj.Resolution))
coder.internal.warning(...
'robotics:robotalgs:occgridcommon:RoundoffWarning');
end
obj.Logodds = mat;
end
obj.GridSize = size(obj.Logodds);
end
function cpObj = copy(obj)
%COPY Creates a copy of the object
% cpObj = COPY(obj) creates a deep copy of the
% Occupancy Grid object with the same properties.
%
% Example:
% % Create an occupancy grid of 10m x 10m world representation
% map = robotics.OccupancyGrid(10, 10);
%
% % Create a copy of the object
% cpObj = copy(map);
%
% % Access the class methods from the new object
% setOccupancy(cpObj,[2 4],true);
%
% % Delete the handle object
% delete(cpObj)
%
% See also robotics.OccupancyGrid
if isempty(obj)
% This will not be encountered in code generation
cpObj = OccupancyGrid.empty(0,1);
else
% Create a new object with the same properties
cpObj = OccupancyGrid(obj.GridSize(1),...
obj.GridSize(2),obj.Resolution,'grid');
% Assign the grid data to the new object handle
cpObj.Logodds = obj.Logodds;
cpObj.GridLocationInWorld = obj.GridLocationInWorld;
cpObj.OccupiedThresholdIntLogodds = obj.OccupiedThresholdIntLogodds;
cpObj.FreeThresholdIntLogodds = obj.FreeThresholdIntLogodds;
cpObj.ProbSatIntLogodds = obj.ProbSatIntLogodds;
end
end
function value = getOccupancy(obj, pos, frame)
%getOccupancy Get occupancy value for one or more positions
% VAL = getOccupancy(MAP, XY) returns an N-by-1 array of
% occupancy values for N-by-2 array, XY. Each row of the
% array XY corresponds to a point with [X Y] world coordinates.
%
% VAL = getOccupancy(MAP, IJ, 'grid') returns an N-by-1
% array of occupancy values for N-by-2 array IJ. Each row of
% the array IJ refers to a grid cell index [X,Y].
%
% Example:
% % Create an occupancy grid and get occupancy
% % values for a position
% map = robotics.OccupancyGrid(10, 10);
%
% % Get occupancy of the world coordinate (0, 0)
% value = getOccupancy(map, [0 0]);
%
% % Get occupancy of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = getOccupancy(map, [X(:) Y(:)]);
%
% % Get occupancy of the grid cell (1, 1)
% value = getOccupancy(map, [1 1], 'grid');
%
% % Get occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = getOccupancy(map, [I(:) J(:)], 'grid');
%
% See also robotics.OccupancyGrid, setOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 2
isGrid = obj.parseOptionalFrameInput(frame, 'getOccupancy');
end
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'getOccupancy');
value = double(obj.intLogoddsToProb(obj.Logodds(indices)));
end
function setOccupancy(obj, pos, value, frame)
%setOccupancy Set occupancy value for one or more positions
% setOccupancy(MAP, XY, VAL) assigns the scalar occupancy
% value, VAL to each coordinate specified in the N-by-2 array,
% XY. Each row of the array XY corresponds to a point with
% [X Y] world coordinates.
%
% setOccupancy(MAP, XY, VAL) assigns each element of the
% N-by-1 vector, VAL to the coordinate position of the
% corresponding row of the N-by-2 array, XY.
%
% setOccupancy(MAP, IJ, VAL, 'grid') assigns occupancy values
% to the grid positions specified by each row of the N-by-2
% array, IJ, which refers to the [row, col] index from each row
% in the array.
%
% Example:
% % Create an occupancy grid and set occupancy
% % values for a position
% map = robotics.OccupancyGrid(10, 10);
%
% % Set occupancy of the world coordinate (0, 0)
% setOccupancy(map, [0 0], 0.2);
%
% % Set occupancy of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = ones(numel(X),1)*0.65;
% setOccupancy(map, [X(:) Y(:)], values);
%
% % Set occupancy of the grid cell (1, 1)
% setOccupancy(map, [1 1], 0.4, 'grid');
%
% % Set occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% setOccupancy(map, [I(:) J(:)], 0.4, 'grid');
%
% % Set occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = ones(numel(I),1)*0.8;
% setOccupancy(map, [I(:) J(:)], values, 'grid');
%
% See also robotics.OccupancyGrid, getOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 3
isGrid = obj.parseOptionalFrameInput(frame, 'setOccupancy');
end
% Validate values
obj.validateOccupancyValues(value, size(pos, 1), 'setOccupancy', 'val');
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'setOccupancy');
obj.Logodds(indices) = probToIntLogodds(obj,double(value(:)));
end
function inflate(obj, varargin)
%INFLATE Inflate the occupied positions by a given amount
% INFLATE(MAP, R) inflates each occupied position of the
% occupancy grid by at least R meters. Each cell of the
% occupancy grid is inflated by number of cells which is the
% closest integer higher than the value MAP.Resolution*R.
%
% INFLATE(MAP, R, 'grid') inflates each cell of the
% occupancy grid by R cells.
%
% Note that the inflate function does not inflate the
% positions past the limits of the grid.
%
% Example:
% % Create an occupancy grid and inflate map
% mat = eye(100)*0.6;
% map = robotics.OccupancyGrid(mat);
%
% % Create a copy of the map for inflation
% cpMap = copy(map);
%
% % Inflate occupied cells using inflation radius in
% % meters
% inflate(cpMap, 0.1);
%
% % Inflate occupied cells using inflation radius in
% % number of cells
% inflate(cpMap, 2, 'grid');
%
% See also robotics.OccupancyGrid, copy
narginchk(2,3);
obj.Logodds = obj.inflateGrid(obj.Logodds, varargin{:});
end
function imageHandle = show(obj, varargin)
%SHOW Display the occupancy grid in a figure
% SHOW(MAP) displays the MAP occupancy grid in the
% current axes with the axes labels representing the world
% coordinates.
%
% SHOW(MAP, 'grid') displays the MAP occupancy grid in
% the current axes with the axes of the figure representing
% the grid indices.
%
% HIMAGE = SHOW(MAP, ___) returns the handle to the image
% object created by show.
%
% SHOW(MAP,___,Name,Value) provides additional options specified
% by one or more Name,Value pair arguments. Name must appear
% inside single quotes (''). You can specify several name-value
% pair arguments in any order as Name1,Value1,...,NameN,ValueN:
%
% 'Parent' - Handle of an axes that specifies
% the parent of the image object
% created by show.
%
% Example:
% % Create an occupancy grid and display
% map = robotics.OccupancyGrid(eye(5)*0.5);
%
% % Display the occupancy with axes showing the world
% % coordinates
% imgHandle = show(map);
%
% % Display the occupancy with axes showing the grid
% % indices
% imgHandle = show(map, 'grid');
%
% % Display the occupancy with axes showing the world
% % coordinates and specify a parent axes
% fHandle = figure;
% aHandle = axes('Parent', fh);
% imgHandle = show(map, 'world', 'Parent', ah);
%
% See also robotics.OccupancyGrid
[axHandle, isGrid] = obj.showInputParser(varargin{:});
[axHandle, imghandle] = showGrid(obj, obj.intLogoddsToProb(obj.Logodds), axHandle, isGrid);
title(axHandle, ...
'Platoon Based Autonomous Intersection Management');
% Only return handle if user requested it.
if nargout > 0
imageHandle = imghandle;
end
end
function occupied = checkOccupancy(obj, pos, frame)
%checkOccupancy Check ternary occupancy status for one or more positions
% VAL = checkOccupancy(MAP, XY) returns an N-by-1 array of
% occupancy status using OccupiedThreshold and FreeThreshold,
% for N-by-2 array, XY. Each row of the array XY corresponds
% to a point with [X Y] world coordinates. Occupancy status
% of 0 refers to obstacle-free cells, 1 refers to occupied
% cells and -1 refers to unknown cells.
%
% VAL = checkOccupancy(MAP, IJ, 'grid') returns an N-by-1
% array of occupancy status for N-by-2 array IJ. Each row of
% the array IJ refers to a grid cell index [X,Y].
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(10, 10);
%
% % Check occupancy status of the world coordinate (0, 0)
% value = checkOccupancy(map, [0 0]);
%
% % Check occupancy status of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = checkOccupancy(map, [X(:) Y(:)]);
%
% % Check occupancy status of the grid cell (1, 1)
% value = checkOccupancy(map, [1 1], 'grid');
%
% % Check occupancy status of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = checkOccupancy(map, [I(:) J(:)], 'grid');
%
% See also robotics.OccupancyGrid, getOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 2
isGrid = obj.parseOptionalFrameInput(frame, 'checkOccupancy');
end
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'checkOccupancy');
value = obj.Logodds(indices);
freeIdx = (value < obj.FreeThresholdIntLogodds);
occIdx = (value > obj.OccupiedThresholdIntLogodds);
occupied = ones(size(value))*(-1);
occupied(freeIdx) = 0;
occupied(occIdx) = 1;
end
function idx = world2grid(obj, pos)
%WORLD2GRID Convert world coordinates to grid indices
% IJ = WORLD2GRID(MAP, XY) converts an N-by-2 array of world
% coordinates, XY, to an N-by-2 array of grid indices, IJ. The
% input, XY, is in [X Y] format. The output grid indices, IJ,
% are in [ROW COL] format.
%
% Example:
% % Create an occupancy grid and convert world
% % coordinates to grid indices
% % Create a 10m x 10m world representation
% map = robotics.OccupancyGrid(10, 10);
%
% % Get grid indices from world coordinates
% ij = world2grid(map, [0 0])
%
% % Get grid indices from world coordinates
% [x y] = meshgrid(0:0.5:2);
% ij = world2grid(map, [x(:) y(:)])
pos = obj.validatePosition(pos, obj.XWorldLimits, ...
obj.YWorldLimits, 'world2grid', 'xy');
% Convert world coordinate to grid indices
idx = worldToGridPrivate(obj, pos);
end
function pos = grid2world(obj, idx)
%GRID2WORLD Convert grid indices to world coordinates
% XY = GRID2WORLD(MAP, IJ) converts an N-by-2 array of grid
% indices, IJ, to an N-by-2 array of world coordinates, XY. The
% input grid indices, IJ, are in [ROW COL] format. The output,
% XY, is in [X Y] format.
%
% Example:
% % Create an occupancy grid and convert grid
% % indices to world coordinates
% % Create a 10m x 10m world representation
% map = robotics.OccupancyGrid(10, 10);
%
% % Get world coordinates from grid indices
% xy = grid2world(map, [1 1])
%
% % Get world coordinates from grid indices
% [i j] = meshgrid(1:5);
% xy = world2grid(map, [i(:) j(:)])
idx = obj.validateGridIndices(idx, obj.GridSize, ...
'grid2world', 'IJ');
% Convert grid index to world coordinate
pos = gridToWorldPrivate(obj, idx);
end
function updateOccupancy(obj, pos, value, frame)
%updateOccupancy Integrate occupancy value for one or more positions
% updateOccupancy(MAP, XY, OBS) probabilistically integrates
% the scalar observation OBS for each coordinate specified in the
% N-by-2 array, XY. Each row of the array XY corresponds to a
% point with [X Y] world coordinates. Default update values
% are used if OBS is logical. Update values are 0.7 and 0.4
% for true and false respectively. Alternatively, OBS can be
% of any numeric type with value between 0 and 1.
%
% updateOccupancy(MAP, XY, OBS) probabilistically integrates
% each element of the N-by-1 vector, OBS with the coordinate
% position of the corresponding row of the N-by-2 array, XY.
%
% updateOccupancy(MAP, IJ, OBS, 'grid') probabilistically
% integrates observation values to the grid positions
% specified by each row of the N-by-2 array, IJ, which refers
% to the [row, col] index from each row in the array.
%
% Example:
% % Create an occupancy grid and update occupancy
% % values for a position
% map = robotics.OccupancyGrid(10, 10);
%
% % Update occupancy of the world coordinate (0, 0)
% updateOccupancy(map, [0 0], true);
%
% % Update occupancy of multiple coordinates
% [X, Y] = meshgrid(0:0.5:5);
% values = ones(numel(X),1)*0.65;
% updateOccupancy(map, [X(:) Y(:)], values);
%
% % Update occupancy of the grid cell (1, 1)
% updateOccupancy(map, [1 1], false, 'grid');
%
% % Update occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% updateOccupancy(map, [I(:) J(:)], 0.4, 'grid');
%
% % Update occupancy of multiple grid cells
% [I, J] = meshgrid(1:5);
% values = true(numel(I),1);
% updateOccupancy(map, [I(:) J(:)], values, 'grid');
%
% See also robotics.OccupancyGrid, setOccupancy
isGrid = false;
% If optional argument present then parse it separately
if nargin > 3
isGrid = obj.parseOptionalFrameInput(frame, 'updateOccupancy');
end
% Validate values
obj.validateOccupancyValues(value, size(pos, 1), 'updateOccupancy', 'val');
% Validate position or subscripts and convert it to indices
indices = obj.getIndices(pos, isGrid, 'updateOccupancy');
if isscalar(value)
value = cast(ones(size(pos, 1), 1)*value, 'like', value);
end
if islogical(value)
updateValuesHit = obj.Logodds(indices(logical(value(:)))) + obj.LogoddsHit;
updateValuesHit(updateValuesHit > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
obj.Logodds(indices(logical(value(:)))) = updateValuesHit;
updateValuesMiss = obj.Logodds(indices(~logical(value(:)))) + obj.LogoddsMiss;
updateValuesMiss(updateValuesMiss < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(indices(~logical(value(:)))) = updateValuesMiss;
else
updateValues = obj.Logodds(indices) + obj.probToIntLogoddsMaxSat(double(value(:)));
updateValues(updateValues > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
updateValues(updateValues < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(indices) = updateValues;
end
end
function collisionPt = rayIntersection(obj, pose, angles, maxRange, threshold)
%rayIntersection Compute map intersection points of rays
% PTS = rayIntersection(MAP, POSE, ANGLES, MAXRANGE) returns
% collision points PTS in the world coordinate frame for
% rays emanating from POSE. PTS is an N-by-2 array of points.
% POSE is a 1-by-3 array of sensor pose [X Y THETA] in the world
% coordinate frame. ANGLES is an N-element vector of angles
% at which to get ray intersection points. MAXRANGE is a
% scalar representing the maximum range of the range sensor. If
% there is no collision up-to the maximum range then [NaN NaN]
% output is returned. By default, the OccupiedThreshold
% property in MAP is used to determine occupied cells.
%
% PTS = rayIntersection(MAP, POSE, ANGLES, MAXRANGE, THRESHOLD)
% returns collision points PTS, where the THRESHOLD is used
% to determine the occupied cells. Any cell with a probability
% value greater or equal to THRESHOLD is considered occupied.
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(eye(10));
%
% % Set occupancy of the world coordinate (5, 5)
% setOccupancy(map, [5 5], 0.5);
%
% % Get collision points
% collisionPts = rayIntersection(map, [0,0,0], [pi/4, pi/6], 10);
%
% % Visualize the collision points
% show(map);
% hold('on');
% plot(collisionPts(:,1),collisionPts(:,2) , '*')
%
% % Get collision points with threshold value 0.4
% collisionPts = rayIntersection(map, [0,0,0], [pi/4, pi/6], 10, 0.4);
%
% % Visualize the collision points
% plot(collisionPts(:,1),collisionPts(:,2) , '*')
%
% See also robotics.OccupancyGrid, raycast
narginchk(4,5);
vPose = obj.validatePose(pose, obj.XWorldLimits, obj.YWorldLimits, 'rayIntersection', 'pose');
vAngles = obj.validateAngles(angles, 'rayIntersection', 'angles');
validateattributes(maxRange, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', 'positive'}, 'rayIntersection', 'maxrange');
if nargin < 5
grid = (obj.occupancyMatrix('ternary') == 1);
else
validateattributes(threshold, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', '<=', 1, '>=', 0}, 'rayIntersection', 'threshold');
grid = obj.occupancyMatrix > threshold;
end
[ranges, endPt] = robotics.algs.internal.calculateRanges(vPose, vAngles, double(maxRange), ...
grid, obj.GridSize, obj.Resolution, obj.GridLocationInWorld);
collisionPt = endPt;
collisionPt(isnan(ranges), :) = nan;
end
function [endPts, middlePts] = raycast(obj, varargin)
%RAYCAST Get cells along a ray
% [ENDPTS, MIDPTS] = RAYCAST(MAP, POSE, RANGE, ANGLE) returns
% cell indices of all cells traversed by a ray emanating from
% POSE at an angle ANGLE with length equal to RANGE. POSE is
% a 3-element vector representing robot pose [X, Y, THETA] in
% the world coordinate frame. ANGLE and RANGE are scalars.
% The ENDPTS are indices of cells touched by the
% end point of the ray. MIDPTS are all the cells touched by
% the ray excluding the ENDPTS.
%
% [ENDPTS, MIDPTS] = RAYCAST(MAP, P1, P2) returns
% the cell indices of all cells between the line segment
% P1=[X1,Y1] to P2=[X2,Y2] in the world coordinate frame.
%
% For faster insertion of range sensor data, use the insertRay
% method with an array of ranges or an array of end points.
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(10, 10, 20);
%
% % compute cells along a ray
% [endPts, midPts] = raycast(map, [5,3,0], 4, pi/3);
%
% % Change occupancy cells to visualize
% updateOccupancy(map, endPts, true, 'grid');
% updateOccupancy(map, midPts, false, 'grid');
% % Compute cells along a line segment
% [endPts, midPts] = raycast(map, [2,5], [6,8]);
%
% % Change occupancy cells to visualize
% updateOccupancy(map, endPts, true, 'grid');
% updateOccupancy(map, midPts, false, 'grid');
%
% % Visualize the raycast output
% show(map);
%
% See also robotics.OccupancyGrid, insertRay
narginchk(3,4);
if nargin == 4
pose = obj.validatePose(varargin{1}, obj.XWorldLimits, ...
obj.YWorldLimits, 'raycast', 'pose');
validateattributes(varargin{2}, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', 'nonnegative'}, 'raycast', 'range');
validateattributes(varargin{3}, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar'}, 'raycast', 'angle');
range = double(varargin{2});
angle = double(varargin{3}) + pose(3);
startPoint = pose(1:2);
endPoint = [pose(1) + range*cos(angle), ...
pose(2) + range*sin(angle)];
else
startPoint = obj.validatePosition(varargin{1}, obj.XWorldLimits, ...
obj.YWorldLimits, 'raycast', 'StartPoint');
validateattributes(varargin{1}, {'numeric'}, {'numel', 2}, ...
'raycast', 'p1');
endPoint = obj.validatePosition(varargin{2}, obj.XWorldLimits, ...
obj.YWorldLimits, 'raycast', 'EndPoint');
validateattributes(varargin{2}, {'numeric'}, {'numel', 2}, ...
'raycast', 'p2');
end
[endPts, middlePts] = robotics.algs.internal.raycastCells(startPoint, endPoint, ...
obj.GridSize(1), obj.GridSize(2), obj.Resolution, obj.GridLocationInWorld);
end
function insertRay(obj, varargin)
%insertRay Insert rays from laser scan observation
% insertRay(MAP, POSE, RANGES, ANGLES, MAXRANGE) inserts one
% or more range sensor observations in the occupancy grid.
% POSE is a 3-element vector representing sensor pose
% [X, Y, THETA] in world coordinate frame, RANGES and ANGLES
% are corresponding N-element vectors for range sensor
% readings, MAXRANGE is the maximum range of the sensor.
% The cells along the ray except the end points are observed
% as obstacle-free and updated with probability of 0.4.
% The cells touching the end point are observed as occupied
% and updated with probability of 0.7. NaN values in RANGES are
% ignored. RANGES above MAXRANGE are truncated and the end
% points are not updated for MAXRANGE readings.
%
% insertRay(MAP, POSE, RANGES, ANGLES, MAXRANGE, INVMODEL)
% inserts the ray with update probabilities according to a
% 2-element vector INVMODEL. The first element of
% INVMODEL is used to update obstacle-free observations and
% the second element is used to update occupied observations.
% Values in INVMODEL should be between 0 and 1.
%
% insertRay(MAP, STARTPT, ENDPTS) inserts cells between the
% line segments STARTPT and ENDPTS. STARTPT is 2-element vector
% representing the start point [X,Y] in the world coordinate frame.
% ENDPTS is N-by-2 array of end points in the world coordinate
% frame. The cells along the line segment except the end points
% are updated with miss probability of 0.4 and the cells
% touching the end point are updated with hit probability of 0.7.
%
% insertRay(MAP, STARTPT, ENDPTS, INVMODEL) inserts the
% line segment with update probabilities according to a
% 1-by-2 or 2-by-1 array INVMODEL.
%
% Example:
% % Create an occupancy grid
% map = robotics.OccupancyGrid(10,10,20);
%
% % Insert two rays
% insertRay(map, [5,5,0], [5, 6], [pi/4, pi/6], 20);
%
% % Insert rays with non default inverse model
% insertRay(map, [5,5,0], [5, 6], [pi/3, pi/2], 20, [0.3 0.8]);
%
% % Visualize inserted rays
% show(map);
%
% % Insert a line segment
% insertRay(map, [0,0], [3,3]);
%
% % Visualize inserted ray
% show(map);
%
% See also robotics.OccupancyGrid, raycast
% Supported syntax
%insertRay(ogmap, robotpose, ranges, angles, maxRange)
%insertRay(ogmap, robotpose, ranges, angles, maxRange, inverseModel)
%insertRay(ogmap, startPoint, endPoints)
%insertRay(ogmap, startPoint, endPoints, inverseModel)
gridSize = obj.GridSize;
res = obj.Resolution;
loc = obj.GridLocationInWorld;
narginchk(3, 6);
if nargin < 5
% Cartesian input
validateattributes(varargin{1}, {'numeric'}, ...
{'nonempty', 'numel', 2}, 'insertRay', 'startpt');
startPt = [varargin{1}(1) varargin{1}(2)];
startPt = obj.validatePosition(startPt, obj.XWorldLimits, ...
obj.YWorldLimits, 'insertRay', 'StartPoint');
endPt = obj.validatePosition(varargin{2}, obj.XWorldLimits, ...
obj.YWorldLimits, 'insertRay', 'endpts');
else
% Polar input
pose = obj.validatePose(varargin{1}, obj.XWorldLimits, ...
obj.YWorldLimits, 'insertRay', 'pose');
maxRange = varargin{4};
validateattributes(maxRange, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'scalar', 'positive'}, 'insertRay', 'maxrange');
ranges = obj.validateRanges(varargin{2}, 'insertRay', 'ranges');
angles = obj.validateAngles(varargin{3}, 'insertRay', 'angles');
isInvalidSize = (numel(ranges) ~= numel(angles));
coder.internal.errorIf(isInvalidSize, ...
'robotics:robotalgs:occgridcommon:RangeAngleMismatch', 'ranges', 'angles');
vRanges = ranges(~isnan(ranges(:)));
vAngles = angles(~isnan(ranges(:)));
vRanges = min(maxRange, vRanges);
startPt = [pose(1) pose(2)];
endPt = [pose(1) + vRanges.*cos(pose(3)+vAngles), ...
pose(2) + vRanges.*sin(pose(3)+vAngles)];
end
if nargin == 6 || nargin == 4
% Validate inverse model
validateattributes(varargin{end}, {'numeric'}, ...
{'real', 'nonnan', 'finite', 'nonempty', 'numel', 2}, 'insertRay', 'invmodel');
invModel = varargin{end}(:)';
if coder.target('MATLAB')
firstElementMsg = message('robotics:robotalgs:occgrid:FirstElement').getString;
secondElementMsg = message('robotics:robotalgs:occgrid:SecondElement').getString;
else
% Hard code error string for code generation as coder
% does not support getting string from catalog.
firstElementMsg = 'first element of';
secondElementMsg = 'second element of';
end
validateattributes(invModel(1,1), {'numeric'}, ...
{'>=', 0, '<=', 0.5, 'scalar'}, 'insertRay', [firstElementMsg 'invModel']);
validateattributes(invModel(1,2), {'numeric'}, ...
{'>=', 0.5, '<=', 1, 'scalar'}, 'insertRay', [secondElementMsg 'invModel']);
inverseModelLogodds = obj.probToIntLogoddsMaxSat(double(invModel));
else
inverseModelLogodds = [obj.LogoddsMiss obj.LogoddsHit];
end
for i = 1:size(endPt, 1)
[endPts, middlePts] = robotics.algs.internal.raycastCells(startPt, endPt(i,:), ...
gridSize(1), gridSize(2), res, loc);
if ~isempty(middlePts)
mIndex = sub2ind(gridSize, middlePts(:,1), middlePts(:,2));
updateValuesMiss = obj.Logodds(mIndex) + inverseModelLogodds(1);
updateValuesMiss(updateValuesMiss < obj.ProbSatIntLogodds(1)) = obj.ProbSatIntLogodds(1);
obj.Logodds(mIndex) = updateValuesMiss;
end
% For max range reading do not add end point
if nargin >= 5 && vRanges(i) >= maxRange
continue;
end
if ~isempty(endPts)
eIndex = sub2ind(gridSize, endPts(:,1), endPts(:,2));
updateValuesHit = obj.Logodds(eIndex) + inverseModelLogodds(2);
updateValuesHit(updateValuesHit > obj.ProbSatIntLogodds(2)) = obj.ProbSatIntLogodds(2);
obj.Logodds(eIndex) = updateValuesHit;
end
end
end
function mat = occupancyMatrix(obj, option)
%OCCUPANCYMATRIX Export occupancy grid as a matrix
% MAT = OCCUPANCYMATRIX(MAP) returns probability values stored in the
% occupancy grid object as a matrix.
%
% MAT = OCCUPANCYMATRIX(MAP, 'ternary') returns occupancy status of
% the each occupancy grid cell as a matrix. The
% OccupiedThreshold and FreeThreshold are used to determine
% obstacle-free and occupied cells. Value 0 refers to
% obstacle-free cell, 1 refers to occupied cell and -1 refers
% to unknown cell.
%
% Example:
% % Create an occupancy grid
% inputMat = repmat(0.2:0.1:0.9, 8, 1);
% map = robotics.OccupancyGrid(inputMat);
%
% % Export occupancy grid as a matrix
% mat = occupancyMatrix(map);
%
% % Export occupancy grid as a ternary matrix
% mat = occupancyMatrix(map, 'ternary');
%
% See also robotics.OccupancyGrid, getOccupancy
narginchk(1,2);
if nargin < 2
mat = double(obj.intLogoddsToProb(obj.Logodds));
return;
end
validStrings = {'Ternary'};
validatestring(option, validStrings, 'occupancyMatrix');
mat = -1*ones(size(obj.Logodds));
occupied = (obj.Logodds > obj.OccupiedThresholdIntLogodds);
free = (obj.Logodds < obj.FreeThresholdIntLogodds);
mat(occupied) = 1;
mat(free) = 0;
end
end
%================================================================
methods (Static, Access = {?matlab.unittest.TestCase, ...
?robotics.algs.internal.OccupancyGridBase})
function logodds = probToLogodds(prob)
%probToLogodds Get log-odds value from probabilities
logodds = log(prob./(1-prob));
end
function probability = logoddsToProb(logodds)
%logoddsToProb Get probabilities from log-odds values
probability = 1 - 1./(1 + exp(logodds));
end
function maxSat = getMaxSaturation()
%getMaxSaturation Get max saturation for testing purposes
maxSat = robotics.OccupancyGrid.ProbMaxSaturation;
end
end
methods (Access = {?matlab.unittest.TestCase, ...
?robotics.algs.internal.OccupancyGridBase})
function logodds = probToIntLogodds(obj, prob)
%probToIntLogodds Convert probability to int16 log-odds
prob(prob < obj.ProbabilitySaturation(1)) = obj.ProbabilitySaturation(1);
prob(prob > obj.ProbabilitySaturation(2)) = obj.ProbabilitySaturation(2);
logodds = int16(interp1(obj.LookupTable, ...
single(obj.LinSpaceInt16),prob,'nearest', 'extrap'));
end
function probability = intLogoddsToProb(obj, logodds)
%intLogoddsToProb Convert int16 log-odds to probability
probability = interp1(single(obj.LinSpaceInt16), ...
obj.LookupTable, single(logodds),'nearest', 'extrap');
end
function logodds = probToIntLogoddsMaxSat(obj, prob)
%probToIntLogoddsMaxSat Convert probability to int16 log-odds
% This method uses maximum possible saturation. Required for
% update occupancy.
prob(prob < obj.ProbMaxSaturation(1)) = obj.ProbMaxSaturation(1);
prob(prob > obj.ProbMaxSaturation(2)) = obj.ProbMaxSaturation(2);
logodds = int16(interp1(obj.LookupTable, ...
single(obj.LinSpaceInt16),prob,'nearest', 'extrap'));
end
end
methods (Access = protected)
function mat = processMatrix(obj, varargin)
%processMatrix Process construction input and create log-odds
% Supports two input patterns:
% processMatrix(obj, rows,columns);
% processMatrix(obj, mat);
if nargin == 3
rows = varargin{1};
columns = varargin{2};
mat = zeros(rows, columns, obj.DefaultType);
elseif nargin == 2
% As probability saturation is not assigned, use max
% saturation.
mat = obj.probToIntLogoddsMaxSat(single(varargin{1}));
end
end
end
methods (Static, Access =public)
function P = validateMatrixInput(P)
%validateMatrixInput Validates the matrix input
if islogical(P)
validateattributes(P, {'logical'}, ...
{'2d', 'real', 'nonempty'}, ...
'OccupancyGrid', 'P', 1);
else
validateattributes(P, {'numeric','logical'}, ...
{'2d', 'real', 'nonempty','nonnan','<=',1,'>=',0}, ...
'OccupancyGrid', 'P', 1);
end
end
function className = getClassName()
className = 'OccupancyGrid';
end
function validateOccupancyValues(values, len, fcnName, argname)
%validateOccupancyValues Validate occupancy value vector
% check that the values are numbers in [0,1]
if islogical(values)
validateattributes(values, {'logical'}, ...
{'real','vector', 'nonempty'}, fcnName, argname);
else
validateattributes(values, {'numeric'}, ...
{'real','vector', 'nonnan', '<=',1,'>=',0, 'nonempty'}, fcnName, argname);
end
isSizeMismatch = length(values) ~= 1 && length(values) ~= len;
coder.internal.errorIf(isSizeMismatch,...
'robotics:robotalgs:occgridcommon:InputSizeMismatch');
end
end
end
function linSpace = getIntLineSpace()
%getIntLineSpace Generate line space for integer log-odds
defaultType = OccupancyGrid.DefaultType;
linSpace = intmin(defaultType):intmax(defaultType);
end
function lookup = createLookupTable()
%createLookupTable Create lookup table for integer log-odds to probability
numOfPoints = abs(double(intmin(OccupancyGrid.DefaultType)))+...
double(intmax(OccupancyGrid.DefaultType))+1;
logOddsLimits = OccupancyGrid.probToLogodds(OccupancyGrid.ProbMaxSaturation);
lookup = single(OccupancyGrid.logoddsToProb(...
linspace(logOddsLimits(1), logOddsLimits(2), numOfPoints)));
end
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
AIM_Optimal.m
|
.m
|
PlatoonBased-AIM-master/Matlab/AIM_Optimal.m
| 13,184 |
utf_8
|
288e2c22a0200535ab23bf32c3793c77
|
function [delays,callCounter,packets,var,AverageDelayPerVehicle,AverageDelayPerPlatoon,totalVehicles,totalVehiclesCrossed] = AIM_Optimal(bal,seed,granularity,platoonMaxSize,spawnRate,duration,simSpeed,handles)
tic;
ver=2;
rng(seed);
packetsFromPlatoons = 0;
packetsToPlatoons = 0;
%Get Map, Show Map
intersectionData = intersection();
map = intersectionData.getMap(granularity);
show(map)
%title('Platoon-Based Intersection Management');
xlim([0 granularity]);
ylim([0 granularity]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Initialization and Constants
laneTraffic = zeros(1,4);
laneIsFull= zeros(1,4);
global simulationTime;
numVehiclesPassed = 0;
numPlatoonsPassed = 0;
currentAvgDelay = 0;
totalVehicles = [0 0 0 0];
totalVehiclesCrossed = [0 0 0 0];
%LaneTail is initialized to the stop points, this will dynamically change..
%as platoon stop for their turn.other platoons will use this data to stop
%right behind the last platoon in queue.
laneStop = [180 195;%for Lane 1
205 180;%for Lane 2
220 205;%for Lane 3
195 215;%for Lane 4
];
turns ={'straight' 'left' 'right'};
numOfPlatoons = 0;
numOfLanes = 4;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
frameCounter = 1;
%F(frameCounter) = getframe(gcf);
%legend('Vehicle');
%stoppedByUser=0;
tic;
elapsedTime = toc;
%Spawn First Platoon
laneNumber = randi([1 numOfLanes]);
platoonLeader = vehicleModel(intersectionData.spawnPoints(laneNumber,:));
%Spawn The followers
platoonSize = randi([1 platoonMaxSize]);
turnDecision = turns{randi([1 3])};
platoons(numOfPlatoons+1) = vehiclePlatoon(platoonSize,platoonLeader,turnDecision,frameCounter);
numOfPlatoons = numOfPlatoons+1;
platoons(numOfPlatoons).addVehicle(platoonSize-1);
simulationTime = 5*simSpeed;
spawnPerSec = spawnRate/3600;
lastFrame = 0;
clearTime = 0;
times = 0;
laneCapacity = 16;
%legend('Stopped Platoon','Stopped Platoon','Stopped Platoon','Stopped Platoon');
newBatch = 1;
fps=2;
index=0;
gone = [];
numOfPlatoonsInSchedule=0;
callCounter = 0;
candidates = [0 0 0 0];
while(frameCounter<duration*fps)
set(handles.timeLabel,'String',sprintf('%.2fs',frameCounter/fps));
set(handles.crossedVehicles,'String',sprintf('%d',sum(totalVehiclesCrossed)));
if(mod(frameCounter,1)==0)%Spawn 4 platoons every 100 frames
for k=1:4
%Spawn New Platoons
%decide lane
%laneNumber = randi([1 numOfLanes]);
%decide turn
turnDecision = turns{randi([1 3])};
%decide platoon size
platoonSize = randi([1 platoonMaxSize]);
%Spawn Leader
prob = rand();
threshold = spawnPerSec*0.5/platoonSize;
if(prob<threshold && ((laneTraffic(k)+platoonSize)<laneCapacity))
totalVehicles(k) = totalVehicles(k) + platoonSize;
platoonLeader = vehicleModel(intersectionData.spawnPoints(k,:));
%Spawn The followers
platoons(numOfPlatoons+1) = vehiclePlatoon(platoonSize,platoonLeader,turnDecision,frameCounter);
numOfPlatoons = numOfPlatoons+1;
platoons(numOfPlatoons).addVehicle(platoonSize-1);
laneTraffic(k) = laneTraffic(k) +platoonSize;
if(laneTraffic(k)>laneCapacity)
laneIsFull(k)=1;
else
laneIsFull(k)=0;
end
end
end
end
%Get Solution%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
arrivals = [];
lengths = [];
waitings = [];
packetsFromPlatoons = packetsFromPlatoons + length(platoons);
indices = 1:length(platoons);
indices(gone) = [];
if(isempty(indices))
drawnow;
frameCounter = frameCounter+1;
continue;
else
for j=indices
if (j==1)
waitings = [1 platoons(j).waitingTime platoons(j).arrivalTime];
%arrivals = [1 platoons(j).arrivalTime];
else
waitings = [waitings; j platoons(j).waitingTime platoons(j).arrivalTime];
%lengths = [lengths; j platoons(j).platoonSize];
end
end
schedule2 = sortrows(waitings,[3]);
sortedList = [schedule2(:,1)'];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
counter = 0;
timePassed = frameCounter-lastFrame;
lastCandidates = candidates;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if(newBatch==1 || ver==2)%index>numOfPlatoonsInSchedule || index==0)
candidates = [0 0 0 0];
candidateCounter = 0;
for pt=sortedList
if(candidateCounter==4)
break
else
lane = platoons(pt).arrivalLane;
if(candidates(lane)==0 && ~strcmp(platoons(pt).state,'crossing') ...
&& ~strcmp(platoons(pt).state,'done')...
&& platoons(pt).arrivalTime<=clearTime)
candidates(lane)=pt;
candidateCounter = candidateCounter+1;
end
end
end
candidates = candidates(candidates~=0);
if(~isempty(candidates))
if(length(candidates)~=length(lastCandidates))
newSchedule = greedySort(candidates);
callCounter = callCounter+1;
newBatch = 0;
numOfPlatoonsInSchedule = length(newSchedule);
index = 1;
elseif(candidates~=lastCandidates)
newSchedule = greedySort(candidates);
callCounter = callCounter+1;
newBatch = 0;
numOfPlatoonsInSchedule = length(newSchedule);
index = 1;
else
newSchedule = greedySort(candidates);
newBatch = 0;
numOfPlatoonsInSchedule = length(newSchedule);
index = 1;
end
else
newSchedule = 0;
index = 0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=sortedList
if(index>0 && index <=numOfPlatoonsInSchedule)
whosTurn = newSchedule(index);
else
whosTurn=0;
end
if(isvalid(platoons(j)))
if(strcmp(platoons(j).state,'done'))
gone = [gone j];
end
timePassed = frameCounter-lastFrame;
if(timePassed>=clearTime && j==whosTurn ...
&& (strcmp(platoons(j).state,'stopandwait')...
|| strcmp(platoons(j).state,'moveandwait')))
index = index + 1;
if(index>numOfPlatoonsInSchedule)
newBatch=1;
end
packetsToPlatoons = packetsToPlatoons + 1;
packetsFromPlatoons = packetsFromPlatoons + 1;
platoons(j).setPath(intersectionData.getTrajectory(platoons(j).arrivalLane,platoons(j).turn),frameCounter);
arrival = platoons(j).arrivalTime;
totalVehiclesCrossed(platoons(j).arrivalLane) = totalVehiclesCrossed(platoons(j).arrivalLane) + platoons(j).platoonSize; %counter = counter + 1;
clearTime = arrival + (25+(platoons(j).platoonSize*8))/(platoons(j).linearVelocity*simulationTime);
lastFrame = frameCounter;
laneTraffic(platoons(j).arrivalLane) = laneTraffic(platoons(j).arrivalLane) -platoons(j).platoonSize;
if(laneTraffic(platoons(j).arrivalLane)>laneCapacity)
laneIsFull(platoons(j).arrivalLane)=1;
else
laneIsFull(platoons(j).arrivalLane)=0;
end
%counter = counter + 1;
for ii= sortedList(find(sortedList==j,1)+1:end)
platoons(ii).updateStopPoint(platoons(j).stopPoints(platoons(j).arrivalLane,:),platoons(j).arrivalLane);
end
end
drive(platoons(j),simulationTime,frameCounter,true);
if(strcmp(platoons(j).state,'stopandwait')...
|| strcmp(platoons(j).state,'moveandwait'))
for ii= sortedList(find(sortedList==j,1)+1:end)
platoons(ii).updateStopPoint(platoons(j).tail(),platoons(j).arrivalLane);
end
end
end
end
drawnow;
frameCounter = frameCounter+1;
%platoonSizeSetting = platoonMaxSize
%SimulationTime = frameCounter/2
%F(frameCounter) = getframe(gcf);
%tic;
%pause(time/1000);
%times = [times toc-elapsedTime];
%elapsedTime = toc;
%platoons = sort(platoons);
end
end
aveTime = mean(times);
delays = [];
platoonDelays = [];
for j=1:length(platoons)
if(isvalid(platoons(j)))
if(strcmp(platoons(j).state,'done') || strcmp(platoons(j).state,'crossing'))
%totalVehiclesCrossed(platoons(j).arrivalLane) = totalVehiclesCrossed(platoons(j).arrivalLane) + platoons(j).platoonSize;
delay =platoons(j).totalWaiting/fps;
if(delay>=0)
platoonDelays = [platoonDelays delay];
for(i=1:platoons(j).platoonSize)
delays = [delays delay];
end
end
elseif(platoons(j).waitingTime>=0)
delay = platoons(j).waitingTime/fps;
platoonDelays = [platoonDelays delay];
for(i=1:platoons(j).platoonSize)
delays = [delays delay];
end
end
delete(platoons(j));
end
end
delays = delays;
platoonDelays = platoonDelays;
AverageDelayPerVehicle = mean(delays);
AverageDelayPerPlatoon = mean(platoonDelays);
packets = packetsFromPlatoons+packetsToPlatoons;
var = sum(delays.^2)/(length(delays)-1) - (length(delays))*mean(delays)^2/(length(delays)-1);
function sol = getSchedule(lengths,waitingTimes)
[sorted sol] = sort(waitingTimes,'descend');
end
function sol = getSchedule2(lengths,arrivalTimes)
[sorted sol] = sort(arrivalTimes);
end
function [newSchedule] = greedySort(candidates)
minimumDelay = inf;
newSchedule = candidates;
clearTimes = getClearTimes(candidates);
permutations = perms(candidates);
for i=1:size(permutations,1)
maxDelay = 0;
extraWaitTime = max(clearTime - platoons(permutations(i,1)).arrivalTime ,0);
extraWaitTime = 0;
if(bal==1)
delayPerVehicle = (platoons(permutations(i,1)).waitingTime +...
extraWaitTime)*...
platoons(permutations(i,1)).platoonSize;
else
delayPerVehicle = (platoons(permutations(i,1)).waitingTime +...
extraWaitTime)*...
platoons(permutations(i,1)).platoonSize;
end
totalDelay = clearTimes(find(candidates ==permutations(i,1),1))+clearTime+...
+max(platoons(permutations(i,1)).arrivalTime-clearTime,0);
% platoons(permutations(i,1)).waitingTime*...
% platoons(permutations(i,1)).platoonSize;
%delayPerVehicle=0;
%delayPerVehicle = delayPerVehicle +...
% platoons(permutations(i,1)).waitingTime*...
% platoons(permutations(i,1)).platoonSize;
if(delayPerVehicle>maxDelay)
maxDelay = delayPerVehicle;
end
for j=2:size(permutations,2)
extraWaitTime = max(totalDelay - platoons(permutations(i,j)).arrivalTime ,0);
extraWait = extraWaitTime>0;
if(bal==2)
delayPerVehicle =delayPerVehicle+j*(platoons(permutations(i,j)).waitingTime+...
extraWaitTime)*...
platoons(permutations(i,j)).platoonSize;
else
delayPerVehicle =delayPerVehicle+(platoons(permutations(i,j)).waitingTime+...
extraWaitTime)*...
platoons(permutations(i,j)).platoonSize;
end
%platoons(permutations(i,j)).waitingTime+
%laneTraffic(platoons(permutations(i,j)).arrivalLane);
%platoons(permutations(i,j)).platoonSize;
% + ...
totalDelay = totalDelay+max(platoons(permutations(i,j)).arrivalTime - totalDelay,0) + ...
clearTimes(find(candidates ==permutations(i,j),1));
if(delayPerVehicle>maxDelay)
maxDelay = delayPerVehicle;
end
end
if(delayPerVehicle<minimumDelay)
minimumDelay = delayPerVehicle;
newSchedule = permutations(i,:);
end
end
end
function clearTimes = getClearTimes(candidates)
for i=1:length(candidates)
if(candidates(i)==0)
pSize(i) = 0;
else
pSize(i) = platoons(candidates(i)).platoonSize;
end
end
constants = zeros(1,length(candidates)).*25;
clearTimes = (constants+(pSize.*8))./(simulationTime);
end
end
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
intersection.m
|
.m
|
PlatoonBased-AIM-master/Matlab/intersection.m
| 6,087 |
utf_8
|
c8d83f6e75ff575d165c9f3adf6d0cb6
|
classdef intersection < handle
properties(SetAccess = private)
granularity;
lineWidth;
lanePerRoad;
end
properties(SetAccess = public)
spawnPoints = [20 195 0;%for Lane 1
205 20 pi/2;%for Lane 2
380 205 pi;%for Lane 3
195 380 -pi/2;%for Lane 4
];
stopPoints = [180 195;%for Lane 1
205 180;%for Lane 2
220 205;%for Lane 3
195 215;%for Lane 4
];
endPoints = [20 205;
195 20;
380 195;
205 380;];
lane1To4 = [180 195;%Lane 1 Turn left
190 195;
195 200;
200 205;
202 210;
205 220;
205 380];
lane1To3 = [180 195;%Lane 1 Go Straight
190 195;
195 195;
200 195;
205 195;
240 195;
380 195];
lane1To2 = [180 195;%Lane 1 Turn right
185 195;
190 195;
192 195;
194 185;
195 145;
195 20];
lane2To3 = [205 180;%Lane 2 turn right
205 185;
205 190;
205 192;
215 195;
275 195;
380 195];
lane2To4 = [205 180;%Lane 2 go straight
205 190;
205 195;
205 200;
205 205;
205 245;
205 380];
lane2To1 = [205 180;
205 190;
205 195;
200 200;
190 205;
130 205;
20 205];%Lane 2 turn left
lane3To4 = [220 205;
210 205;
207 205;
205 210;
205 220;
205 280;
205 380];%Lane 3 turn right
lane3To1 = [220 205;
210 205;
200 205;
160 205;
100 205;
50 205;
20 205];%Lane 3 go straight
lane3To2 = [220 205;
205 205;
200 200;
195 195;
195 190;
195 130;
195 20];%Lane 3 turn left
lane4To1 = [195 220;
195 210;
190 208;
180 205;
130 205;
80 205;
20 205];%Lane 4 turn right
lane4To2 = [195 220;
195 210;
195 205;
195 200;
195 195;
195 155;
195 20;]%Lane 4 go straight
lane4To3 = [195 220;
195 205;
200 200;
205 195;
220 195;
280 195;
380 195;]%Lane 4 turn left
trajectories;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods(Access=public)
function path = getTrajectory(obj,arrivalLane,turn)
switch turn
case 'right'
offset=1;
case 'straight'
offset=2;
case 'left'
offset=3;
end
index = (arrivalLane-1)*3+offset;
path = obj.trajectories(:,:,index);
end
end
methods(Static)
function obj = intersection()
obj.granularity = 400;
obj.lineWidth = 1;
obj.lanePerRoad = 1;
obj.trajectories = obj.lane1To2;%Lane 1 turn right
obj.trajectories(:,:,2) = obj.lane1To3;%Lane 1 go straight
obj.trajectories(:,:,3) = obj.lane1To4;%Lane 1 turn left
obj.trajectories(:,:,4) = obj.lane2To3;%Lane 2 turn right
obj.trajectories(:,:,5) = obj.lane2To4;%Lane 2 go straight
obj.trajectories(:,:,6) = obj.lane2To1;%Lane 2 turn left
obj.trajectories(:,:,7) = obj.lane3To4;%Lane 3 turn right
obj.trajectories(:,:,8) = obj.lane3To1;%Lane 3 go straight
obj.trajectories(:,:,9) = obj.lane3To2;%Lane 3 turn left
obj.trajectories(:,:,10) = obj.lane4To1;%Lane 4 turn right
obj.trajectories(:,:,11) = obj.lane4To2;%Lane 4 go straight
obj.trajectories(:,:,12) = obj.lane4To3;%Lane 4 turn left
end
function map = getMap(varargin)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
numvarargs = length(varargin);
if numvarargs > 3
error('gridMapGenerator: TooManyInputs', ...
'This function takes 1-3 input arguments');
end
optargs = {200 1 1};
optargs(1:numvarargs) = varargin;
[granularity lineWidth lanePerRoad] = optargs{:};
obj.granularity = granularity;
obj.lineWidth = lineWidth;
obj.lanePerRoad = lanePerRoad;
%granularity = 200;
%lineWidth = 1;
intersectionGridMap = zeros(granularity, granularity);
bottomOfLane = 0.5*granularity-10;
topOfLane = 0.5* granularity+10;
intersectionGridMap(bottomOfLane:bottomOfLane+lineWidth,1:bottomOfLane)=1;
intersectionGridMap(bottomOfLane:bottomOfLane+lineWidth,topOfLane:end)=1;
intersectionGridMap(topOfLane:topOfLane+lineWidth,1:bottomOfLane)=1;
intersectionGridMap(topOfLane:topOfLane+lineWidth,topOfLane:end)=1;
intersectionGridMap(1:bottomOfLane+lineWidth,bottomOfLane:bottomOfLane+lineWidth)=1;
intersectionGridMap(topOfLane:end,bottomOfLane:bottomOfLane+lineWidth)=1;
intersectionGridMap(1:bottomOfLane,topOfLane:topOfLane+lineWidth)=1;
intersectionGridMap(topOfLane:end,topOfLane:topOfLane+lineWidth)=1;
intersectionGridMap(0.5*granularity,1:bottomOfLane)=0.5;
intersectionGridMap(0.5*granularity,topOfLane+lineWidth:end)=0.5;
intersectionGridMap(1:bottomOfLane,0.5*granularity)=0.5;
intersectionGridMap(topOfLane+lineWidth:end,0.5*granularity)=0.5;
intersectionGridMap(1:bottomOfLane,1:bottomOfLane)=0.7;
intersectionGridMap(1:bottomOfLane,topOfLane+lineWidth:end)=0.7;
intersectionGridMap(topOfLane+lineWidth:end,1:bottomOfLane)=0.7;
intersectionGridMap(topOfLane+lineWidth:end,topOfLane+lineWidth:end)=0.7;
intersectionGridMap = intersectionGridMap';
map = OccupancyGrid(intersectionGridMap);
end
end
end
|
github
|
Jeffrey28/PlatoonBased-AIM-master
|
simulator.m
|
.m
|
PlatoonBased-AIM-master/Matlab/simulator.m
| 28,773 |
utf_8
|
8ac19883ed2c0563a0e03fa0f0535b83
|
function varargout = simulator(varargin)
% SIMULATOR MATLAB code for simulator.fig
%%
%%
% SIMULATOR, by itself, creates a new SIMULATOR or raises the existing
% singleton*.
%
% H = SIMULATOR returns the handle to a new SIMULATOR or the handle to
% the existing singleton*.
%
% SIMULATOR('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SIMULATOR.M with the given input arguments.
%
% SIMULATOR('Property','Value',...) creates a new SIMULATOR or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before simulator_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to simulator_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help simulator
% Last Modified by GUIDE v2.5 02-Jan-2017 18:06:33
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @simulator_OpeningFcn, ...
'gui_OutputFcn', @simulator_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before simulator is made visible.
function simulator_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to simulator (see VARARGIN)
% Choose default command line output for simulator
handles.output = hObject;
% Update handles structure
handles.simTime = 500;
handles.readyColor = [1 1 1];
handles.runningColor = [104/255 151/255 187/255];
handles.finishedColor = [102/255 205/255 170/255];
handles.savingColor = [211/255 71/255 31/255];
grid on;
grid minor;
guidata(hObject, handles);
axes(handles.axes1);
%title('Platoon-Based Autonomous Intersection Management');
xlim([0 400]);
ylim([0 400]);
%grid on
%grid minor
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','off');
%axes(handles.axes1);
% UIWAIT makes simulator wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = simulator_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in start.
function start_Callback(hObject, eventdata, handles)
% hObject handle to start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%clf;
handles.simTime = round(get(handles.duration,'Value'));
handles.simSpeed = round(get(handles.simulationSpeed,'Value'));
handles.spawnRate = round(get(handles.spawn,'Value'));
axes(handles.axes1);
g = 400;
contents = str2double(get(handles.platoonSize,'String'));
maxSize= contents(get(handles.platoonSize,'Value'));
set(handles.resetbutton,'Enable','on');
set(handles.savevideo,'Enable','off');
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.runningColor);
set(handles.status, 'String','Simulation is Running');
policyNumber = get(handles.policy,'Value');
seed = 12345;
if(policyNumber==1)
[p,var,vDelay,pDelay,tv,tvc] = AIM(seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
elseif(policyNumber==2)
% [handles.Fcc,p,var,vDelay,pDelay,tv,tvc] = AIM_Optimal(1,seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
% vDelay
% var
% cc
[handles.F,cc,p,var,vDelay,pDelay,tv,tvc] = AIM_Optimal(2,seed,g,maxSize,handles.spawnRate,handles.simTime,handles.simSpeed,handles);
vDelay
var
cc
end
fprintf('The Average Delay per Vehicle is %f\n', vDelay)
guidata(hObject,handles);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Finished');
set(handles.start,'Enable','on');
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','on');
% --- Executes on selection change in granularity.
function granularity_Callback(hObject, eventdata, handles)
% hObject handle to granularity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns granularity contents as cell array
% contents{get(hObject,'Value')} returns selected item from granularity
% --- Executes during object creation, after setting all properties.
function granularity_CreateFcn(hObject, eventdata, handles)
% hObject handle to granularity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in resetbutton.
function resetbutton_Callback(hObject, eventdata, handles)
% hObject handle to resetbutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%axes(handles.axes1);
%error('stop requested by user');
%handles.stop=1;
%guidata(hObject,handles);
%clc;
cla;
grid on;
grid minor;
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Ready!');
set(handles.start,'Enable','on');
set(handles.savevideo,'Enable','off');
% --- Executes on slider movement.
function duration_Callback(hObject, eventdata, handles)
% hObject handle to duration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.simTime = round(get(hObject,'Value'));
labelText = strcat(num2str(handles.simTime),' Sec.');
set(handles.durationlabel,'String',labelText);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function duration_CreateFcn(hObject, eventdata, handles)
% hObject handle to duration (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on slider movement.
function slider2_Callback(hObject, eventdata, handles)
% hObject handle to slider2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% --- Executes during object creation, after setting all properties.
function slider2_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on button press in exit.
function exit_Callback(hObject, eventdata, handles)
% hObject handle to exit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(gcf);
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over start.
function start_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to start (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- Executes on button press in savevideo.
function savevideo_Callback(hObject, eventdata, handles)
% hObject handle to savevideo (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.savingColor);
set(handles.status, 'String','Saving Video');
pause(0.5);
uniqueNumber = num2str(randi([0 100])*100);
video = VideoWriter(strcat('AIM-Demo-',uniqueNumber),'MPEG-4');
video.FrameRate = 20;
open(video);
writeVideo(video,handles.F);
close(video);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Video was saved to File!');
set(handles.start,'Enable','on');
% --- Executes on slider movement.
function slider5_Callback(hObject, eventdata, handles)
% hObject handle to slider5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% --- Executes during object creation, after setting all properties.
function slider5_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider5 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on selection change in platoonSize.
function platoonSize_Callback(hObject, eventdata, handles)
% hObject handle to platoonSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns platoonSize contents as cell array
% contents{get(hObject,'Value')} returns selected item from platoonSize
% --- Executes during object creation, after setting all properties.
function platoonSize_CreateFcn(hObject, eventdata, handles)
% hObject handle to platoonSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on slider movement.
function simulationSpeed_Callback(hObject, eventdata, handles)
% hObject handle to simulationSpeed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.simSpeed = round(get(hObject,'Value'));
labelText = strcat(num2str(handles.simSpeed),'X');
set(handles.speedlabel,'String',labelText);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function simulationSpeed_CreateFcn(hObject, eventdata, handles)
% hObject handle to simulationSpeed (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on slider movement.
function spawn_Callback(hObject, eventdata, handles)
% hObject handle to spawn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
handles.spawnRate = round(get(hObject,'Value'));
labelText = strcat(num2str(handles.spawnRate),' Veh/H/L');
set(handles.spawnLabel,'String',labelText);
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function spawn_CreateFcn(hObject, eventdata, handles)
% hObject handle to spawn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- Executes on selection change in policy.
function policy_Callback(hObject, eventdata, handles)
% hObject handle to policy (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns policy contents as cell array
% contents{get(hObject,'Value')} returns selected item from policy
% --- Executes during object creation, after setting all properties.
function policy_CreateFcn(hObject, eventdata, handles)
% hObject handle to policy (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in experiment.
function experiment_Callback(hObject, eventdata, handles)
% hObject handle to experiment (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.simTime = round(get(handles.duration,'Value'));
handles.simSpeed = round(get(handles.simulationSpeed,'Value'));
handles.spawnRate = round(get(handles.spawn,'Value'));
axes(handles.axes1);
g = 400;
contents = str2double(get(handles.platoonSize,'String'));
maxSize= contents(get(handles.platoonSize,'Value'));
set(handles.resetbutton,'Enable','on');
set(handles.savevideo,'Enable','off');
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.runningColor);
set(handles.status, 'String','Simulation is Running');
policyNumber = get(handles.policy,'Value');
totalVehicles = 0;
totalVehiclesCrossed = 0;
trafficFlows = [];
counter=0;
seed = 1234;
for j = 500:100:2000
trafficFlows = [trafficFlows j];
counter = counter+1;
n_exp = 1;
for i=1:8
seed = 1234;
if(policyNumber==1)
p = zeros(1,n_exp);
v = zeros(1,n_exp);
vDelay = zeros(1,n_exp);
pDelay = zeros(1,n_exp);
fprintf('Max_Platoon = %d, Traffic Level = %d\n',i,j);
for n=1:n_exp
seed = seed+n;
[p(n),v(n),vDelay(n),pDelay(n),tv,tvc] = AIM(seed,g,i,j,handles.simTime,handles.simSpeed,handles);
fprintf('Experiment #%d\n',n);
Average_Delay_Per_Vehicle = vDelay(n)
cla
end
fprintf('Max_Platoon = %d, Traffic Level = %d\n',i,j);
v;
vDelay;
packets(i,counter) = mean(p);
var(i,counter) = mean(v);
AverageDelayPerVehicle(i,counter) = mean(vDelay)
AverageDelayPerPlatoon(i,counter) = mean(pDelay);
elseif(policyNumber==2)
[p,var(i,counter),vDelay,pDelay,tv,tvc] = AIM_Optimal(g,i,j,handles.simTime,handles.simSpeed,handles);
packets(i,counter)=p;
AverageDelayPerVehicle(i,counter) = vDelay;
AverageDelayPerPlatoon(i,counter) = pDelay;
end
%totalVehicles(i,counter) = sum(tv);
%totalVehiclesCrossed(i,counter) = sum(tvc);
%AverageDelayPerVehicle
%packets
end
end
figure
plot(trafficFlows,AverageDelayPerVehicle(1,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(2,:),'color','g','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(4,:),'color','c','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(5,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(6,:),'color','m','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(7,:),'color','y','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(8,:),'color',[0.545 0.27 0.074],'marker','o','lineStyle','--','lineWidth',1);
legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6' ...
,'Max-Platoon-Size=7','Max-Platoon-Size=8');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Average Delay (S)');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
plot(trafficFlows,var(1,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(2,:),'color','g','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(4,:),'color','c','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(5,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(6,:),'color','m','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(7,:),'color','y','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(8,:),'color',[0.545 0.27 0.074],'marker','o','lineStyle','--','lineWidth',1);
legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6' ...
,'Max-Platoon-Size=7','Max-Platoon-Size=8');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Travel Delay Variance (S^2)');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
plot(trafficFlows,packets(1,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(2,:),'color','g','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(4,:),'color','c','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(5,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(6,:),'color','m','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(7,:),'color','y','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,packets(8,:),'color',[0.545 0.27 0.074],'marker','o','lineStyle','--','lineWidth',1);
legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6' ...
,'Max-Platoon-Size=7','Max-Platoon-Size=8');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('# Packets Exchanged');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure
% congestion = totalVehicles-totalVehiclesCrossed
% plot(trafficFlows,congestion(1,:),'ro-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(2,:),'bo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(3,:),'mo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(4,:),'go-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(5,:),'ko-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(6,:),'co-.','lineWidth',2);
% legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
% ,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6');
% title('Average Congestion');
guidata(hObject,handles);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Finished');
set(handles.start,'Enable','on');
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','on');
% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton6 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.simTime = round(get(handles.duration,'Value'));
handles.simSpeed = round(get(handles.simulationSpeed,'Value'));
handles.spawnRate = round(get(handles.spawn,'Value'));
axes(handles.axes1);
g = 400;
contents = str2double(get(handles.platoonSize,'String'));
maxSize= contents(get(handles.platoonSize,'Value'));
set(handles.resetbutton,'Enable','on');
set(handles.savevideo,'Enable','off');
set(handles.start,'Enable','off');
set(handles.status, 'BackgroundColor',handles.runningColor);
set(handles.status, 'String','Simulation is Running');
policyNumber = get(handles.policy,'Value');
totalVehicles = 0;
totalVehiclesCrossed = 0;
trafficFlows = [];
counter=0;
seed = 1234;
callCounter=[];
%for kk =1:6
% seed = 1233+kk;
max1=0;
max2=0;
max3=0;
for j = 1000:100:1000
trafficFlows = [trafficFlows j];
counter = counter+1;
[delays1,p,var(1,counter),vDelay,pDelay,tv,tvc] = AIM(seed,g,maxSize,j,handles.simTime,handles.simSpeed,handles);
packets(1,counter) = p;
maxDelay(1,counter) = max(delays1);
AverageDelayPerVehicle(1,counter) = vDelay
AverageDelayPerPlatoon(1,counter) = pDelay;
cla
ver=1;
[delays2,callCounter(1,counter),p,var(2,counter),vDelay,pDelay,tv,tvc] = AIM_Optimal(ver,seed,g,maxSize,j,handles.simTime,handles.simSpeed,handles);
packets(2,counter)=p;
maxDelay(2,counter) = max(delays2);
AverageDelayPerVehicle(2,counter) = vDelay
AverageDelayPerPlatoon(2,counter) = pDelay;
cla
ver=2;
[delays3,callCounter(2,counter),p,var(3,counter),vDelay,pDelay,tv,tvc] = AIM_Optimal(ver,seed,g,maxSize,j,handles.simTime,handles.simSpeed,handles);
packets(3,counter)=p;
maxDelay(3,counter) = max(delays3);
AverageDelayPerVehicle(3,counter) = vDelay
var
AverageDelayPerPlatoon(3,counter) = pDelay;
callCounter;
csvwrite('delays_stopsign.csv',delays1);
csvwrite('delays_pdm.csv',delays2);
csvwrite('delays_pvm.csv',delays3);
end
%end
% bins = [min(delays1):0.5:max(delays1)];
% %bins = 100;
% figure
% hh = histogram(delays1,bins);
% plot(hh.BinEdges(2:end),hh.Values,'k');
%
% %delete(hh(1));
% %plot(hh(2));
% hold on
% gg = histogram(delays2,bins);
% plot(gg.BinEdges(2:end),gg.Values,'r');
%
% %delete(gg(1));
% hold on
% ff = histogram(delays3,bins);
% plot(ff.BinEdges(2:end),ff.Values,'b');
% %delete(ff(1));
% %figure
% delete(ff);
% delete(gg);
% delete(hh);
% legend('avali','dovomi','sevomi');
figure
plot(trafficFlows,AverageDelayPerVehicle(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,AverageDelayPerVehicle(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,maxDelay(1,:),'color','k','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,maxDelay(2,:),'color','r','marker','o','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,maxDelay(3,:),'color','b','marker','o','lineStyle','--','lineWidth',1);
legend('Average\_Delay_{StopSigns}',...
'Average\_Delay_{MD}',...
'Average\_Delay_{MV}',...
'MAX\_Delay_{StopSigns}',...
'MAX\_Delay_{MD}',...
'MAX\_Delay_{MV}');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Delay(S)');
grid minor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure
plot(trafficFlows,var(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
hold on
plot(trafficFlows,var(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
legend('Policy = StopSigns','Policy = Minimize_Delay','Policy = Minimize_Variance');
xlabel('Traffic Level (Vehicle/Hour/Lane)');
ylabel('Travel Delay Variance (S^2)');
grid minor
% figure
% plot(trafficFlows,maxDelay(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
% hold on
% plot(trafficFlows,maxDelay(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
% hold on
% plot(trafficFlows,maxDelay(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
% legend('Policy = StopSigns','Policy = Minimize_Delay','Policy = Minimize_Variance');
% xlabel('Traffic Level (Vehicle/Hour/Lane)');
% ylabel('MAX_{DelayPerVehicle} (S^2)');
% grid minor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure
% plot(trafficFlows,packets(1,:),'color','k','marker','d','lineStyle','--','lineWidth',1);
% hold on
% plot(trafficFlows,packets(2,:),'color','r','marker','d','lineStyle','--','lineWidth',1);
% hold on
% plot(trafficFlows,packets(3,:),'color','b','marker','d','lineStyle','--','lineWidth',1);
% legend('Policy = StopSign','Policy = Optimal','Policy = Optimal-Updating');
% xlabel('Traffic Level (Vehicle/Hour/Lane)');
% ylabel('# Packets Exchanged With the Infrastructure');
% grid minor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% figure
% congestion = totalVehicles-totalVehiclesCrossed
% plot(trafficFlows,congestion(1,:),'ro-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(2,:),'bo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(3,:),'mo-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(4,:),'go-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(5,:),'ko-.','lineWidth',2);
% hold on
% plot(trafficFlows,congestion(6,:),'co-.','lineWidth',2);
% legend('Max-Platoon-Size=1','Max-Platoon-Size=2','Max-Platoon-Size=3' ...
% ,'Max-Platoon-Size=4','Max-Platoon-Size=5','Max-Platoon-Size=6');
% title('Average Congestion');
guidata(hObject,handles);
set(handles.status, 'BackgroundColor',handles.finishedColor);
set(handles.status, 'String','Finished');
set(handles.start,'Enable','on');
set(handles.resetbutton,'Enable','off');
set(handles.savevideo,'Enable','on');
|
github
|
felipe-vrgs/QuadMat-master
|
PID.m
|
.m
|
QuadMat-master/src/PID.m
| 2,558 |
utf_8
|
3f3b4dc3905901015e37226434bbfb47
|
% PID: Aplicação de PID
%
% @param Gains Os ganhos [kp ki kd]
% @param x Vetor de esp est
% @param SetPoint Ponto que queremos chegar
% @param Ref Qual malha está sendo controlada
% @param t Passo de tempo atual
%
% @return U Esforço de controle
%
function [U] = PID(Gains, x, SetPoint, Ref, t)
% Globais do PID
global err_ant err_int windup t_ant err_dot U_ant err_2ant;
% Pegando as variáveis de acordo com quem chamou a função
if strcmp(Ref,'U1')
idx = 1;
trgt = x(7);
elseif strcmp(Ref,'U2')
idx = 2;
trgt = x(1);
elseif strcmp(Ref,'U3')
idx = 3;
trgt = x(3);
elseif strcmp(Ref,'U4')
idx = 4;
trgt = x(5);
end
% Ganhos do PID
Kp = Gains(1);
Ki = Gains(2);
Kd = Gains(3);
% Passo de tempo atual
dt = t - t_ant(idx);
% Calcula-se o erro
err = SetPoint - trgt;
% Tem que verificar se o tempo foi pra frente (os algoritmos ode tem esse comportamento de não seguirem o tempo de forma linear)
if (t > t_ant(idx))
% Erro integrativo acumulado
err_int(idx) = err_int(idx) + ((err+err_ant(idx))/2)*dt;
% Erro derivativo com uma suavização
if dt ~= 0
if err_dot(idx) == 0
err_dot(idx) = (err - err_ant(idx))/dt;
else
% Isso é feito para reduzir variações bruscas no valor devido a derivada
err_dot(idx) = (err_dot(idx) + (err - err_ant(idx))/dt)/2;
end
else
err_dot(idx) = 0;
end
% Quase um tony hawk fechando S K A T E aqui
P = Kp*err;
I = Ki*err_int(idx);
D = Kd*err_dot(idx);
% Calculando o U com o valor do PID
U = Err2U((P+I+D), x, Ref);
% Saturação
if U > windup(idx)
U = windup(idx);
elseif U < -windup(idx)
U = - windup(idx);
end
% Filtro para a saída (melhorar o esforço de controle)
U = U_ant(idx) + (dt/0.01)*(U - U_ant(idx));
else
% Caso seja um passo retroativo não faz nada
U = U_ant(idx);
end
% Atualiza as variáveis para o prox passo
t_ant(idx) = t;
U_ant(idx) = U;
err_2ant(idx) = err_ant(idx);
err_ant(idx) = err;
end
%% Err2U: Pega o erro devolve o esforço de controle.
function [U] = Err2U(val, x, Ref)
% Só isola o valor de cada U das equações de espaço de estados
% TODO: Fazer o omegar vir nessa equação
global g L Kf Km m a b;
if strcmp(Ref,'U1')
U = (val+g)*m/(cos(x(1))*cos(x(3)));
elseif strcmp(Ref,'U2')
U = (val-a(1)*x(6)*x(4))/b(1);
elseif strcmp(Ref,'U3')
U = (val-a(3)*x(2)*x(6))/b(2);
elseif strcmp(Ref,'U4')
U = (val-a(5)*x(2)*x(4))/b(3);
end
end
|
github
|
felipe-vrgs/QuadMat-master
|
PlotDrone.m
|
.m
|
QuadMat-master/src/PlotDrone.m
| 8,620 |
utf_8
|
f33f1fc20471e03c83cbb487034015d9
|
% PlotDrone: Funão que realiza a plotagem dos gráficos.
%
% @param t Tempo
% @param X X
% @param ty Tipo do gráfico
%
% @return graphs !
%
function PlotDrone(t,X,ty)
% Verifica qual é o tipo e redireciona para a função correta
% Não vou entrar muito em detalhes nesse arquivo tendo em vista que as funções são bem simples
if strcmp(ty,'XYZ')
PlotXYZ(t,X)
elseif strcmp(ty,'XYZAng')
PlotXYZAng(t,X)
elseif strcmp(ty,'Ang')
PlotAngles(t,X)
elseif strcmp(ty,'VelXYZ')
PlotXYZVel(t,X)
elseif strcmp(ty,'VelAng')
PlotAngVel(t,X)
elseif strcmp(ty,'U')
PlotU(t)
elseif strcmp(ty,'W')
PlotW()
end
end
%% PlotU: function description
function PlotU(t)
global U_hist;
figure()
subplot(2,2,1)
plot(t, U_hist(:,1))
title('Empuxo Vertical','Interpreter','Latex')
ylabel('U1','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
subplot(2,2,2)
plot(t, U_hist(:,2))
title('Rolagem','Interpreter','Latex')
ylabel('U2','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
subplot(2,2,3)
plot(t, U_hist(:,3))
title('Arfagem','Interpreter','Latex')
ylabel('U3','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
subplot(2,2,4)
plot(t, U_hist(:,4))
title('Guinada','Interpreter','Latex')
ylabel('U4','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
end
%% PlotU: function description
function PlotW()
global W_hist T_hist;
figure()
subplot(2,2,1)
plot(T_hist(:,1), Rad2RPM(W_hist(:,1)))
title('Vel. Ang. Motor 1','Interpreter','Latex')
ylabel('W1 (rpm)','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
subplot(2,2,2)
plot(T_hist(:,1), Rad2RPM(W_hist(:,2)))
title('Vel. Ang. Motor 2','Interpreter','Latex')
ylabel('W2 (rpm)','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
subplot(2,2,3)
plot(T_hist(:,1), Rad2RPM(W_hist(:,3)))
title('Vel. Ang. Motor 3','Interpreter','Latex')
ylabel('W3 (rpm)','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
subplot(2,2,4)
plot(T_hist(:,1), Rad2RPM(W_hist(:,4)))
title('Vel. Ang. Motor 4','Interpreter','Latex')
ylabel('W4 (rpm)','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
suptitle('Velocidade Angular dos motores (rpm)')
end
%% Rad2RPM: function description
function [RPM] = Rad2RPM(rad)
RPM = rad*9.54929658551;
end
%% Rad2RPM: function description
function [Deg] = Rad2Deg(rad)
Deg = rad*57.2958;
end
%% getOS: function description
function [os] = getOS(vals, setpoint, deg)
if nargin == 2
deg = 1;
end
% Verifica o % de OS
if vals(1) > setpoint
os = min(vals);
elseif vals(1) == setpoint
os = 0;
else
os = max(vals);
end
os
if deg == 1
os = (abs(os)/abs(vals(1)))*100
else
os = ((abs(os) - setpoint)/setpoint)*100
end
end
%% getSetTime: function description
function [setTime] = getSetTime(x, t, setpoint, deg)
if nargin == 3
deg = 1;
end
if deg == 1
varbl = Rad2Deg(x(1));
else
varbl = x(1);
end
setTime = 0;
if varbl > setpoint
cmp = 1.02*setpoint;
elseif varbl == setpoint
cmp = 0;
else
cmp = 0.98*setpoint;
end
if setpoint == 0
if varbl > setpoint
cmp = 0.02*varbl;
elseif varbl < setpoint
cmp = -0.02*varbl;
end
end
for I = 1:size(t)
if deg == 1
varbl = Rad2Deg(x(I));
else
newVar = x(I);
end
if varbl > setpoint
if (newVar <= cmp)
setTime = t(I);
break
end
elseif varbl < setpoint
if (newVar >= cmp)
setTime = t(I);
break
end
end
end
setTime
end
function PlotXYZ(t,X)
figure()
% subplot(2,2,1)
% plot(t,X(:,9)) % Posição em X
% title('Posi\c{c}\~{a}o em X','Interpreter','Latex')
% ylabel('X','Interpreter','Latex')
% xlabel('Tempo (s)','Interpreter','Latex')
% grid on
% subplot(2,2,2)
% plot(t,X(:,11)) % Posição em Y
% title('Posi\c{c}\~{a}o em Y','Interpreter','Latex')
% ylabel('Y','Interpreter','Latex')
% xlabel('Tempo (s)','Interpreter','Latex')
% grid on
% subplot(2,1,2)
plot(t,X(:,7)) % Posição em Z
title('Posi\c{c}\~{a}o em Z','Interpreter','Latex')
ylabel('Z','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
% getSetTime(X(:,7),t, 2, 0)
% getOS(X(:,7),2,0);
% X(350,7)
% suptitle('Movimento em XYZ')
end
function PlotXYZVel(t,X)
figure()
subplot(2,2,1)
plot(t,X(:,10)) % Velocidade em X
title('Velocidade em X','Interpreter','Latex')
ylabel('$\dot{X}$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(2,2,2)
plot(t,X(:,12)) % Velocidade em Y
title('Velocidade em Y','Interpreter','Latex')
ylabel('$\dot{Y}$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(2,1,2)
plot(t,X(:,8)) % Velocidade em Z
title('Velocidade em Z','Interpreter','Latex')
ylabel('$\dot{Z}$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
suptitle('Velocidade em XYZ')
end
function PlotAngles(t,X)
figure()
subplot(2,2,1)
plot(t,Rad2Deg(X(:,1))) % Angulo phi
title('\^Angulo $\phi$','Interpreter','Latex')
ylabel('Graus','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
getSetTime(X(:,1),t,0);
getOS(X(:,1),0);
Rad2Deg(X(350,1))
subplot(2,2,2)
plot(t,Rad2Deg(X(:,3))) % Posição em theta
title('\^Angulo $\theta$','Interpreter','Latex')
ylabel('Graus','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
getSetTime(X(:,3),t,0);
getOS(X(:,3),0);
Rad2Deg(X(350,3))
subplot(2,1,2)
plot(t,Rad2Deg(X(:,5))) % Posição em psi
title('\^Angulo $\psi$','Interpreter','Latex')
ylabel('Graus','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
getSetTime(X(:,5),t,0);
getOS(X(:,5),0);
Rad2Deg(X(350,5))
suptitle('Movimento Angular')
end
function PlotXYZAng(t,X)
figure()
hold on
subplot(3,2,1)
plot(t,X(:,9)) % Posição em X
% title('Posi\c{c}\~{a}o em X','Interpreter','Latex')
ylabel('X','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(3,2,2)
plot(t,X(:,1)) % Angulo phi
% title('\^Angulo $\phi$','Interpreter','Latex')
ylabel('$\phi$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(3,2,3)
plot(t,X(:,11)) % Posição em Y
% title('Posi\c{c}\~{a}o em Y','Interpreter','Latex')
ylabel('Y','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(3,2,5)
plot(t,X(:,7)) % Posição em Z
% title('Posi\c{c}\~{a}o em Z','Interpreter','Latex')
ylabel('Z','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(3,2,4)
plot(t,X(:,3)) % Posição em theta
% title('\^Angulo $\theta$','Interpreter','Latex')
ylabel('$\theta$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(3,2,6)
plot(t,X(:,5)) % Posição em psi
% title('\^Angulo $\psi$','Interpreter','Latex')
ylabel('$\psi$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
suptitle('Variacao das Posicoes Angulares e Lineares')
end
function PlotAngVel(t,X)
figure()
subplot(2,2,1)
plot(t,X(:,2)) % Velocidade phi
title('Velocidade $\dot\phi$','Interpreter','Latex')
ylabel('$\dot\phi$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(2,2,2)
plot(t,X(:,4)) % Posição em theta
title('Velocidade $\dot\theta$','Interpreter','Latex')
ylabel('$\dot\theta$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
subplot(2,1,2)
plot(t,X(:,6)) % Posição em psi
title('Velocidade $\dot\psi$','Interpreter','Latex')
ylabel('$\dot\psi$','Interpreter','Latex')
xlabel('Tempo (s)','Interpreter','Latex')
grid on
suptitle('Velocidade Angular')
end
|
github
|
felipe-vrgs/QuadMat-master
|
Fitness.m
|
.m
|
QuadMat-master/src/Fitness.m
| 1,564 |
utf_8
|
b6c06b639c3ac9425948e088bb14c101
|
% Fitness: function description
%
% @param target Quem será controlado
% @param gains Os ganhos do PID
% @param setpoint O SetPoint
%
% @return O fitness
%
function fit = Fitness(target, gains, setpoint, p)
if nargin == 3
p = 0;
end
global err_int;
%{
Apesar do código estar pronto para um fitness diferente por malha foi utilizada a mesma equação, ou seja, apenas a soma do erro é levada em conta no fitness
No caso do Z o fitness é multiplicado por 2000*20 para que a sua escala fique mais agradável, tendo em vista que o seu erro seria alto
por ser uma malha lenta que possui valores grandes, o que é diferente para os ângulos, tendo em vista que apresentam uma variação média entre -0.32 e 0.32.
%}
[t,X] = QuadMat(gains,target,setpoint,p);
errMax = 0;
err = zeros(size(t));
chkVar = zeros(size(t));
Kfit = 30;
KOS = 100;
switch target
case 'z'
chkVar(:) = X(:,7);
Kfit = 2000*2;
case 'phi'
chkVar(:) = X(:,1);
case 'theta'
chkVar(:) = X(:,3);
case 'psi'
chkVar(:) = X(:,5);
end
for n = 1:size(t)
err(n) = t(n)*(real(chkVar(n)) - setpoint)^2;
errMax = errMax + err(n);
end
% Verifica o % de OS
if chkVar(1) > setpoint
osValue = min(chkVar);
elseif chkVar(1) == setpoint
osValue = 0;
else
osValue = max(chkVar);
end
if p == 1
if setpoint ~= 0
((osValue - setpoint)/setpoint)*100;
else
osValue*100;
end
end
errMax = errMax + (abs(osValue - setpoint)^2)*KOS;
if errMax == 0
fit = 10000000;
else
fit = (1/errMax)*Kfit;
end
end
|
github
|
felipe-vrgs/QuadMat-master
|
cacm.m
|
.m
|
QuadMat-master/src/cacm.m
| 3,926 |
utf_8
|
1c3f4d672c3c3d9f50124b348ded3773
|
% CACM: function description
%
% @param target Quem será controlado
% @param gains Os ganhos do PID
% @param setpoint O SetPoint
%
% @return O CACM
%
function CACM()
% CACM
global divisoes numSim z_val zdot_val x1ini x1fim x1divs x2ini x2fim x2divs x1delta x2delta numCores CodigoCores cacm U_MAP;
numCores = 255;
CodigoCores = zeros(numCores,3); % cores RGB
for n=1:numCores
CodigoCores(n,1) = 255 - 255*((n-1)/255);
CodigoCores(n,2) = 255 - 255*((n-1)/255);
CodigoCores(n,3) = 255 - 255*((n-1)/255);
end
divisoes=100;
x1ini=-0; x1fim=4; x1divs=divisoes;
x2ini=-4; x2fim=4; x2divs=divisoes;
x1delta=(x1fim-x1ini)/(x1divs);
x2delta=(x2fim-x2ini)/(x2divs);
cacm = zeros(divisoes,divisoes);
U_MAP = zeros(divisoes,divisoes);
numact = 0;
numSim = 20;
% figure(1); hold on;
for num=1:numSim+1
numact = numact + 1;
z_val = (num - 1)/((numSim)/4);
for num2=1:numSim+1
zdot_val = -4 + 2*(num2 - 1)/((numSim)/4);
fprintf('z_val=%g zdot_val=%g Sim n: %g\n',z_val,zdot_val,numact);
if (z_val == 2 && zdot_val == 0)
else
[t,X] = QuadMat([],'',0,0);
end
numact = numact + 1;
% plot(t(1:500),X(1:500,7))
end
end
% hold off;
assignin('base', 'cacm', cacm);
assignin('base', 'U_MAP', U_MAP);
plot1(cacm, U_MAP);
end
%% InterpolaRGB: function description
function [c] = InterpolaRGB(ci,cf,intr)
c = zeros(3,1);
c(1) = (((cf(1)-ci(1))*intr(1,1)/255) + ci(1))/255;
c(2) = (((cf(2)-ci(2))*intr(1,2)/255) + ci(2))/255;
c(3) = (((cf(3)-ci(3))*intr(1,3)/255) + ci(3))/255;
end
%% Plot1: function description
%! @brief Does the plotting of the space state in the shape
%! of colored squares.
%! @param cacm The space state matrix
function plot1(cacm, U_MAP)
global CodigoCores divisoes x1ini x1delta x2ini x2delta numCores;
figure(); hold on;
for j=1:divisoes
for i=1:divisoes
coordx=x1ini+(i-1)*x1delta;
coordy=x2ini+(j-1)*x2delta;
val=cacm(i,j)+1;
c = zeros(1,3);
if val >= numCores
val = numCores;
end
c = InterpolaRGB([0 0 0],[255 255 255],CodigoCores(val,:));
% [100 0 0],[239 255 203]
% fprintf('i=%g j=%g cacmij=%g\n',i,j,val);
% fprintf('x=%g y=%g [%g %g %g]\n\n',coordx,coordy,c(1),c(2),c(3));
plot(coordx,coordy,'s',...
'Markersize',16,...
'MarkerEdgeColor',[0.96 0.96 0.96],...
'MarkerFaceColor',[c(1) c(2) c(3)]);
%drawnow;
end
end
hold off;
ylabel('$\dot{Z}$','Interpreter','Latex')
xlabel('Z','Interpreter','Latex')
title('Evolu\c{c}\~{a}o dos Estados','Interpreter','Latex');
figure()
mesh(U_MAP)
ylabel('$\dot{Z}$','Interpreter','Latex')
xlabel('$Z$','Interpreter','Latex')
zlabel('$U_{1}$','Interpreter','Latex')
% figure()
% pcolor(cacm)
% ylabel('$\dot{Z}$','Interpreter','Latex')
% xlabel('Z','Interpreter','Latex')
end
%% AchaCelula: function description
%! @brief Calculates the i-th, j-th partition of the state space the
% states x1 and x2 belongs to.
%! @param x1,x2 states x1 and x2
%! @return i, j partition i,j of the state space
function [i,j] = AchaCelula(x1,x2)
global divisoes x1ini x1fim x1divs x2ini x2fim x2divs x1delta x2delta;
% Aqui é o único cálculo a ser feito:
i=(abs(x1)-x1ini)/x1delta; i=floor(i+1);
if i > divisoes
i=divisoes;
elseif i < 1
i = 1;
end
j=(x2-x2ini)/x2delta; j=floor(j+1);
if j > divisoes
j=divisoes;
elseif j < 1
j = 1;
end
% somar 1 e arredondar para baixo
end
|
github
|
felipe-vrgs/QuadMat-master
|
magnifyOnFigure.m
|
.m
|
QuadMat-master/src/magnifyOnFigure.m
| 97,117 |
utf_8
|
602ece8d29b1a3fea8602b011364b137
|
% NAME: magnifyOnFigure
%
% AUTHOR: David Fernandez Prim ([email protected])
%
% PURPOSE: Shows a functional zoom tool, suitable for publishing of zoomed
% images and 2D plots
%
% INPUT ARGUMENTS:
% figureHandle [double 1x1]: graphic handle of the target figure
% axesHandle [double 1x1]: graphic handle of the target axes.
%
% OUTPUT ARGUMENTS:
% none
%
% SINTAX:
% 1) magnifyOnFigure;
% $ Adds magnifier on the first axes of the current figure, with
% default behavior.
%
% 2) magnifyOnFigure( figureHandle );
% $ Adds magnifier on the first axes of the figure with handle
% 'figureHandle', with default behavior.
%
% 3) magnifyOnFigure( figureHandle, 'property1', value1,... );
% $ Adds magnifier on the first axes of the figure with handle
% 'figureHandle', with modified behavior.
%
% 4) magnifyOnFigure( axesHandle );
% $ Adds magnifier on the axes with handle 'axesHandle', with
% default behavior.
%
% 5) magnifyOnFigure( axesHandle, 'property1', value1,... );
% $ Adds magnifier on the axes with handle 'axesHandle', with
% modified behavior.
%
% 6) Consecutive calls to this function (in any of the syntaxes
% exposed above) produce multiple selectable magnifiers on the target axes.
%
% USAGE EXAMPLES: see script 'magnifyOnFigure_examples.m'
%
% PROPERTIES:
% 'magnifierShape': 'Shape of the magnifier ('rectangle' or 'ellipse' allowed, 'rectangle' as default)
% 'secondaryAxesFaceColor': ColorSpec
% 'edgeWidth' Color of the box surrounding the secondary
% axes, magnifier and link. Default 1
% 'edgeColor': Color of the box surrounding the secondary
% axes, magnifier and link. Default 'black'
% 'displayLinkStyle': Style of the link. 'none', 'straight' or
% 'edges', with 'straight' as default.
% 'mode': 'manual' or 'interactive' (allowing
% adjustments through mouse/keyboard). Default
% 'interactive'.
% 'units' Units in which the position vectors are
% given. Only 'pixels' currently supported
% 'initialPositionSecondaryAxes': Initial position vector ([left bottom width height])
% of secondary axes, in pixels
% 'initialPositionMagnifier': Initial position vector ([left bottom width height])
% of magnifier, in pixels
% 'secondaryAxesXLim': Initial XLim value of the secondary axes
% 'secondaryAxesYLim': Initial YLim value of the secondary axes
% 'frozenZoomAspectRatio': Specially useful for images, forces the use of the same zoom
% factor on both X and Y axes, in order to keep the aspect ratio
% ('on' or 'off' allowed, 'off' by default
%
% HOT KEYS (active if 'mode' set to 'interactive')
%
% -In a figure with multiple tool instances
% 'Tab': Switch the focus from one magnifier instance
% to the next one on the current figure.
% 'Mouse pointer on secondary axes or magnifier of a tool+double left click'
% Regain focus
%
% -On the focused magnifier instance
% 'up arrow': Moves magnifier 1 pixel upwards
% 'down arrow': Moves magnifier 1 pixel downwards
% 'left arrow': Moves magnifier 1 pixel to the left
% 'right arrow': Moves magnifier 1 pixel to the right
% 'Shift+up arrow': Expands magnifier 10% on the Y-axis
% 'Shift+down arrow': Compress magnifier 10% on the Y-axis
% 'Shift+left arrow': Compress magnifier 10% on the X-axis
% 'Shift+right arrow': Expands magnifier 10% on the X-axis
% 'Control+up arrow': Moves secondary axes 1 pixel upwards
% 'Control+down arrow': Moves secondary axes 1 pixel downwards
% 'Control+left arrow': Moves secondary axes 1 pixel to the left
% 'Control+right arrow': Moves secondary axes 1 pixel to the right
% 'Alt+up arrow': Expands secondary axes 10% on the Y-axis
% 'Alt+down arrow': Compress secondary axes 10% on the Y-axis
% 'Alt+left arrow': Compress secondary axes 10% on the X-axis
% 'Alt+right arrow': Expands secondary axes 10% on the X-axis
% 'PageUp': Increase additional zooming factor on X-axis
% 'PageDown': Decrease additional zooming factor on X-axis
% 'Shift+PageUp': Increase additional zooming factor on Y-axis
% 'Shift+PageDown': Decrease additional zooming factor on Y-axis
% 'Control+Q': Resets the additional zooming factors to 0
% 'Control+A': Displays position of secondary axes and
% magnifier in the command window
% 'Control+D': Deletes the focused tool
% 'Control+I': Shows/hides the tool identifier (red
% background color when the tool has the focus,
% black otherwise)
% 'Mouse pointer on magnifier+left click' Drag magnifier to any
% direction
% 'Mouse pointer on secondary axes+left click' Drag secondary axes in any
% direction
%
% TODO:
% - Use another axes copy as magnifier instead of rectangle (no ticks).
% - Adapt to work on 3D plots.
% - Add tip tool with interface description?.
%
% KNOWN ISSUES:
% - Secondary axes are not updated when the zoomming or panning tools of the figure are used.
% - Degraded performance for big data sets or big window sizes.
% - The size and position of the magnifier are modified for
% 'PaperPositionMode' equal to 'auto', when the figure is printed to file
% through 'print'
%
% CHANGE HISTORY:
%
% Version | Date | Author | Description
%---------------|---------------|-------------------|---------------------------------------
% 1.0 | 28/11/2009 | D. Fernandez | First version
% 1.1 | 29/11/2009 | D. Fernandez | Added link from magnifier to secondary axes
% 1.2 | 30/11/2009 | D. Fernandez | Keyboard support added
% 1.3 | 01/12/2009 | D. Fernandez | Properties added
% 1.4 | 02/12/2009 | D. Fernandez | Manual mode supported
% 1.5 | 03/12/2009 | D. Fernandez | New link style added ('edges')
% 1.6 | 03/12/2009 | D. Fernandez | Bug solved in display of link style 'edges'
% 1.7 | 04/12/2009 | D. Fernandez | Target axes selection added
% 1.8 | 07/12/2009 | D. Fernandez | Solved bug when any of the axes are reversed.
% 1.9 | 08/12/2009 | D. Fernandez | Adapted to work under all axes modes (tight, square, image, ...)
% 1.10 | 08/12/2009 | D. Fernandez | Added frozenZoomAspectRatio zoom mode, useful for images
% 1.11 | 08/12/2009 | D. Fernandez | Solved bug when axes contain other than 'line' or 'image' objects
% 1.12 | 05/01/2010 | D. Fernandez | Added support to multiple instances
% 1.13 | 05/01/2010 | D. Fernandez | Added 'delete' functionality
% 1.14 | 05/01/2010 | D. Fernandez | Solved bug when initial positions for secondary axes and/or magnifier are specified
% 1.15 | 07/01/2010 | D. Fernandez | Solved bug when resizing window
% 1.16 | 07/01/2010 | D. Fernandez | Improved documentation
% 1.17 | 28/03/2010 | D. Fernandez | Added tool identifications feature
%
function magnifyOnFigure( varargin )
clear global appDataStruct
global appDataStruct
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%CHECK OUTPUT ARGUMENTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch nargout
case 0
%Correct
outputObjectExpected = false;
case 1
%tool object expected at the output
outputObjectExpected = false;
otherwise
error('Number of output arguments not supported.');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%CHECK INPUT ARGUMENTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin == 0
%Initialize 'appDataStructuct' with default values
appDataStruct = initializeToolStruct();
%Set figure handle
appDataStruct.figureHandle = gcf;
% Get number of axes in the same figure
childHandle = get(appDataStruct.figureHandle, 'Children');
iAxes = find(strcmpi(get(childHandle, 'Type'), 'axes'));
% If no target axes specified, select the first found as mainAxes
appDataStruct.mainAxesHandle = childHandle( iAxes(end) );
elseif nargin > 0
if isstruct(varargin{1})
%Initialize 'appDataStructuct' with existent structure
appDataStruct = initializeToolStruct( varargin{1} );
elseif ishandle(varargin{1}) && strcmpi(get(varargin{1}, 'Type'), 'figure')
%Initialize 'appDataStructuct' with default values
appDataStruct = initializeToolStruct();
%Set figure handle
appDataStruct.figureHandle = varargin{1};
% Get number of axes in the same figure
childHandle = get(appDataStruct.figureHandle, 'Children');
iAxes = find(strcmpi(get(childHandle, 'Type'), 'axes'));
% If no target axes specified, select the first found as mainAxes
appDataStruct.mainAxesHandle = childHandle( iAxes(end) );
elseif ishandle(varargin{1}) && strcmpi(get(varargin{1}, 'Type'), 'axes')
%Initialize 'appDataStructuct' with default values
appDataStruct = initializeToolStruct();
appDataStruct.mainAxesHandle = varargin{1};
% Get figure handle
parentHandle = get(varargin{1}, 'Parent');
iHandle = find(strcmpi(get(parentHandle, 'Type'), 'figure'));
% Figure is the parent of the axes
appDataStruct.figureHandle = parentHandle( iHandle(1) );
else
if ishandle(varargin{1})
warning('Wrong figure/axes handle specified. The magnifier will be applied on the current figure.');
elseif isobject(varargin{1})
error('Wrong object specified.');
else
error('Wrong input class specified.');
end
end
if mod(nargin-1, 2) == 0
%Check input properties
for i = 2:2:nargin
if ~strcmpi( varargin{i}, 'frozenZoomAspectRatio' ) &&...
~strcmpi( varargin{i}, 'magnifierShape' ) &&...
~strcmpi( varargin{i}, 'secondaryaxesxlim' ) &&...
~strcmpi( varargin{i}, 'secondaryaxesylim' ) &&...
~strcmpi( varargin{i}, 'secondaryaxesfacecolor' ) &&...
~strcmpi( varargin{i}, 'edgewidth' ) &&...
~strcmpi( varargin{i}, 'edgecolor' ) &&...
~strcmpi( varargin{i}, 'displayLinkStyle' ) &&...
~strcmpi( varargin{i}, 'mode' ) &&...
~strcmpi( varargin{i}, 'units' ) &&...
~strcmpi( varargin{i}, 'initialpositionsecondaryaxes' ) &&...
~strcmpi( varargin{i}, 'initialpositionmagnifier' )
error('Illegal property specified. Please check.');
end
if strcmpi( varargin{i}, 'frozenZoomAspectRatio' )
if ischar(varargin{i+1}) &&...
( strcmpi(varargin{i+1}, 'on') || strcmpi(varargin{i+1}, 'off') )
appDataStruct.globalZoomMode = lower(varargin{i+1});
else
warning(sprintf('Specified zoom mode not supported. Default values will be applied [%s].', appDataStruct.globalZoomMode));
end
end
if strcmpi( varargin{i}, 'mode' )
if ischar(varargin{i+1}) &&...
( strcmpi(varargin{i+1}, 'manual') || strcmpi(varargin{i+1}, 'interactive') )
appDataStruct.globalMode = lower(varargin{i+1});
else
warning(sprintf('Specified mode descriptor not supported. Default values will be applied [%s].', appDataStruct.globalMode));
end
end
if strcmpi( varargin{i}, 'magnifierShape' )
if ischar(varargin{i+1}) &&...
( strcmpi(varargin{i+1}, 'rectangle') || strcmpi(varargin{i+1}, 'ellipse') )
appDataStruct.magnifierShape = lower(varargin{i+1});
else
warning(sprintf('Specified magnifier shape not supported. Default values will be applied [%s].', appDataStruct.magnifierShape));
end
end
if strcmpi( varargin{i}, 'displayLinkStyle' )
if ischar(varargin{i+1}) &&...
( strcmpi(varargin{i+1}, 'straight') || strcmpi(varargin{i+1}, 'none') || strcmpi(varargin{i+1}, 'edges') )
if ~strcmpi(appDataStruct.magnifierShape, 'rectangle') && strcmpi(varargin{i+1}, 'edges')
warning(sprintf('Specified link style not supported. Default values will be applied for ''displayLinkStyle''[%s].', appDataStruct.linkDisplayStyle));
else
appDataStruct.linkDisplayStyle = lower(varargin{i+1});
end
else
warning(sprintf('Specified descriptor not supported. Default values will be applied for ''displayLink''[%s].', appDataStruct.linkDisplayStyle));
end
end
if strcmpi( varargin{i}, 'units' )
if ischar(varargin{i+1}) && strcmpi(varargin{i+1}, 'pixels')
appDataStruct.globalUnits = lower(varargin{i+1});
else
warning(sprintf('Specified units descriptor not supported. Default values will be applied [%s].', appDataStruct.globalUnits));
end
end
if strcmpi( varargin{i}, 'edgewidth' )
if length(varargin{i+1})==1 && isnumeric(varargin{i+1})
appDataStruct.globalEdgeWidth = varargin{i+1};
else
warning(sprintf('Incorrect edge width value. Default value will be applied [%g].', appDataStruct.globalEdgeWidth ))
end
end
if strcmpi( varargin{i}, 'edgecolor' )
if ( length(varargin{i+1})==3 && isnumeric(varargin{i+1}) ) ||...
( ischar(varargin{i+1}) )
appDataStruct.globalEdgeColor = varargin{i+1};
else
warning('Incorrect edge color value. Default black will be applied.');
end
end
if strcmpi( varargin{i}, 'secondaryaxesfacecolor' )
if ( length(varargin{i+1})==3 && isnumeric(varargin{i+1}) ) ||...
( ischar(varargin{i+1}) )
appDataStruct.secondaryAxesFaceColor = varargin{i+1};
else
warning('Incorrect secondary axes face color value. Default white will be applied.');
end
end
if strcmpi( varargin{i}, 'secondaryaxesxlim' )
if ( length(varargin{i+1})==2 && isnumeric(varargin{i+1}) )
appDataStruct.secondaryAxesXLim = varargin{i+1};
else
warning('Incorrect secondary axes XLim value. Default white will be applied.');
end
end
if strcmpi( varargin{i}, 'secondaryaxesylim' )
if ( length(varargin{i+1})==2 && isnumeric(varargin{i+1}) )
appDataStruct.secondaryAxesYLim = varargin{i+1};
else
warning('Incorrect secondary axes YLim value. Default white will be applied.');
end
end
if strcmpi( varargin{i}, 'initialpositionsecondaryaxes' )
if length(varargin{i+1})==4 && isnumeric(varargin{i+1})
appDataStruct.secondaryAxesPosition = varargin{i+1};
else
warning('Incorrect initial position of secondary axes. Default values will be applied.')
end
end
if strcmpi( varargin{i}, 'initialpositionmagnifier' )
if length(varargin{i+1})==4 && isnumeric(varargin{i+1})
appDataStruct.magnifierPosition = varargin{i+1};
else
warning('Incorrect initial position of magnifier. Default values will be applied.')
end
end
end
else
error('Number of input arguments not supported.');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%ENTRY POINT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Create secondary axes
if isempty(appDataStruct.secondaryAxesHandle)
appDataStruct.secondaryAxesHandle = copyobj(appDataStruct.mainAxesHandle, appDataStruct.figureHandle);
end
%Configure secondary axis
set( appDataStruct.secondaryAxesHandle, 'Color', get(appDataStruct.mainAxesHandle,'Color'), 'Box','on');
set( appDataStruct.secondaryAxesHandle, 'FontWeight', 'bold',...
'LineWidth', appDataStruct.globalEdgeWidth,...
'XColor', appDataStruct.globalEdgeColor,...
'YColor', appDataStruct.globalEdgeColor,...
'Color', appDataStruct.secondaryAxesFaceColor );
set( appDataStruct.figureHandle, 'CurrentAxes', appDataStruct.secondaryAxesHandle );
xlabel(''); ylabel(''); zlabel(''); title('');
axis( appDataStruct.secondaryAxesHandle, 'normal'); %Ensure that secondary axes are not resizing
set( appDataStruct.figureHandle, 'CurrentAxes', appDataStruct.mainAxesHandle );
%Default magnifier position
if isempty(appDataStruct.magnifierPosition)
appDataStruct.magnifierPosition = computeMagnifierDefaultPosition();
end
%Default secondary axes position
if isempty(appDataStruct.secondaryAxesPosition)
appDataStruct.secondaryAxesPosition = computeSecondaryAxesDefaultPosition();
end
% #PATCH 1 (part 1)
toolArrayAux = get(appDataStruct.figureHandle, 'userdata');
set(appDataStruct.figureHandle, 'userdata', []);
% #END PATCH 1 (part 1)
%Set initial position of secondary axes
setSecondaryAxesPositionInPixels( appDataStruct.secondaryAxesPosition );
%Set initial position of magnifier
setMagnifierPositionInPixels( appDataStruct.magnifierPosition );
% #PATCH 1 (part 2)
set(appDataStruct.figureHandle, 'userdata', toolArrayAux);
% #END PATCH 1 (part 2)
%Update view limits on secondary axis
refreshSecondaryAxisLimits();
%Update link between secondary axes and magnifier
refreshMagnifierToSecondaryAxesLink();
%Set actions for interactive mode
if strcmpi( appDataStruct.globalMode, 'interactive')
toolArray = get(appDataStruct.figureHandle, 'userdata');
nTools = length(toolArray);
if nTools == 0
%Store figure position
appDataStruct.figurePosition = getFigurePositionInPixels();
%Store old callbacks
appDataStruct.figureOldWindowButtonDownFcn = get( appDataStruct.figureHandle, 'WindowButtonDownFcn');
appDataStruct.figureOldWindowButtonUpFcn = get( appDataStruct.figureHandle, 'WindowButtonUpFcn');
appDataStruct.figureOldWindowButtonMotionFcn = get( appDataStruct.figureHandle, 'WindowButtonMotionFcn');
appDataStruct.figureOldKeyPressFcn = get( appDataStruct.figureHandle, 'KeyPressFcn');
appDataStruct.figureOldDeleteFcn = get( appDataStruct.figureHandle, 'DeleteFcn');
appDataStruct.figureOldResizeFcn = get( appDataStruct.figureHandle, 'ResizeFcn');
%Set service funcions to events
set( appDataStruct.figureHandle, ...
'WindowButtonDownFcn', @ButtonDownCallback, ...
'WindowButtonUpFcn', @ButtonUpCallback, ...
'WindowButtonMotionFcn', @ButtonMotionCallback, ...
'KeyPressFcn', @KeyPressCallback, ...
'DeleteFcn', @DeleteCallback,...
'ResizeFcn', @ResizeCallback...
);
end
else
%Set service funcions to events
set( appDataStruct.figureHandle, ...
'WindowButtonDownFcn', '', ...
'WindowButtonUpFcn', '', ...
'WindowButtonMotionFcn', '', ...
'KeyPressFcn', '', ...
'DeleteFcn', '',...
'ResizeFcn', ''...
);
end
%Set focus
appDataStruct.focusOnThisTool = true;
%Compute unique ID of this magnifying tool, from handles of its elements
toolId = appDataStruct.figureHandle +...
appDataStruct.mainAxesHandle +...
appDataStruct.magnifierHandle +...
appDataStruct.linkHandle +...
appDataStruct.secondaryAxesHandle;
%Set ID of this magnifying tool
appDataStruct.toolId = toolId;
%Get active figure
figureHandle = appDataStruct.figureHandle;
%Save object of this tool to userdata in figure object
toolArray = get(figureHandle, 'UserData');
if isempty(toolArray)
toolArray = struct(appDataStruct);
toolArray.focusOnThisTool = true;
else
%Set focus to this tool
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool).focusOnThisTool = false;
%search tool ID
indexFoundToolId = find([toolArray.toolId] == toolId);
if isempty(indexFoundToolId)
%If not found, create new
indexFoundToolId = length(toolArray)+1;
end
toolArray(indexFoundToolId) = struct(appDataStruct);
toolArray(indexFoundToolId).focusOnThisTool = true;
end
set( figureHandle, 'UserData', toolArray );
%Set callback global behaviour
set(appDataStruct.figureHandle, 'Interruptible', 'off');
set(appDataStruct.figureHandle, 'BusyAction', 'cancel');
%Return created object if requested
if outputObjectExpected == true
varargout{1} = appDataStruct;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: refreshSecondaryAxisLimits
%
% PURPOSE: Updates the view on the secondary axis, based on position and
% span of magnifier, and extend of secondary axis.
%
% INPUT ARGUMENTS:
% appDataStructuct [struct 1x1]: global variable
% OUTPUT ARGUMENTS:
% change 'XLim' and 'YLim' of secondary axis (ACTION)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function refreshSecondaryAxisLimits()
global appDataStruct;
if isempty(appDataStruct)
return;
end
%If limits specified
if ~(isempty(appDataStruct.secondaryAxesXLim) ||...
isempty(appDataStruct.secondaryAxesYLim))
initialXLim = appDataStruct.secondaryAxesXLim;
initialYLim = appDataStruct.secondaryAxesYLim;
limitsToSet = [...
initialXLim(1)...
initialXLim(2)...
initialYLim(1)...
initialYLim(2)...
];
axis(appDataStruct.secondaryAxesHandle, limitsToSet);
appDataStruct.secondaryAxesXLim = [];
appDataStruct.secondaryAxesYLim = [];
else
%Get main axes limits, in axes units
mainAxesXLim = get( appDataStruct.mainAxesHandle, 'XLim' );
mainAxesYLim = get( appDataStruct.mainAxesHandle, 'YLim' );
mainAxesXDir = get( appDataStruct.mainAxesHandle, 'XDir' );
mainAxesYDir = get( appDataStruct.mainAxesHandle, 'YDir' );
%Get position and size of main axes in pixels
mainAxesPositionInPixels = getMainAxesPositionInPixels();
%Compute Pixels-to-axes units conversion factors
xMainAxisPixels2UnitsFactor = determineSpan( mainAxesXLim(1), mainAxesXLim(2) )/mainAxesPositionInPixels(3);
yMainAxisPixels2UnitsFactor = determineSpan( mainAxesYLim(1), mainAxesYLim(2) )/mainAxesPositionInPixels(4);
%Get position and extend of magnifier, in pixels
magnifierPosition = getMagnifierPositionInPixels(); %In pixels
%Relative to the lower-left corner of the axes
magnifierPosition(1) = magnifierPosition(1) - mainAxesPositionInPixels(1);
magnifierPosition(2) = magnifierPosition(2) - mainAxesPositionInPixels(2);
%Compute position and exted of magnifier, in axes units
magnifierPosition(3) = magnifierPosition(3) * xMainAxisPixels2UnitsFactor;
magnifierPosition(4) = magnifierPosition(4) * yMainAxisPixels2UnitsFactor;
if strcmpi(mainAxesXDir, 'normal') && strcmpi(mainAxesYDir, 'normal')
magnifierPosition(1) = mainAxesXLim(1) + magnifierPosition(1)*xMainAxisPixels2UnitsFactor;
magnifierPosition(2) = mainAxesYLim(1) + magnifierPosition(2)*yMainAxisPixels2UnitsFactor;
end
if strcmpi(mainAxesXDir, 'normal') && strcmpi(mainAxesYDir, 'reverse')
magnifierPosition(1) = mainAxesXLim(1) + magnifierPosition(1)*xMainAxisPixels2UnitsFactor;
magnifierPosition(2) = mainAxesYLim(2) - magnifierPosition(2)*yMainAxisPixels2UnitsFactor - magnifierPosition(4);
end
if strcmpi(mainAxesXDir, 'reverse') && strcmpi(mainAxesYDir, 'normal')
magnifierPosition(1) = mainAxesXLim(2) - magnifierPosition(1)*xMainAxisPixels2UnitsFactor - magnifierPosition(3);
magnifierPosition(2) = mainAxesYLim(1) + magnifierPosition(2)*yMainAxisPixels2UnitsFactor;
end
if strcmpi(mainAxesXDir, 'reverse') && strcmpi(mainAxesYDir, 'reverse')
magnifierPosition(1) = mainAxesXLim(2) - magnifierPosition(1)*xMainAxisPixels2UnitsFactor - magnifierPosition(3);
magnifierPosition(2) = mainAxesYLim(2) - magnifierPosition(2)*yMainAxisPixels2UnitsFactor - magnifierPosition(4);
end
secondaryAxisXlim = [magnifierPosition(1) magnifierPosition(1)+magnifierPosition(3)];
secondaryAxisYlim = [magnifierPosition(2) magnifierPosition(2)+magnifierPosition(4)];
zoomFactor = appDataStruct.secondaryAxesAdditionalZoomingFactor;
xZoom = zoomFactor(1);
yZoom = zoomFactor(2);
aux_secondaryAxisXlim(1) = mean(secondaryAxisXlim) -...
determineSpan( secondaryAxisXlim(1), mean(secondaryAxisXlim) )*(1-xZoom);
aux_secondaryAxisXlim(2) = mean(secondaryAxisXlim) +...
determineSpan( secondaryAxisXlim(2), mean(secondaryAxisXlim) )*(1-xZoom);
aux_secondaryAxisYlim(1) = mean(secondaryAxisYlim) -...
determineSpan( secondaryAxisYlim(1), mean(secondaryAxisYlim) )*(1-yZoom);
aux_secondaryAxisYlim(2) = mean(secondaryAxisYlim) +...
determineSpan( secondaryAxisYlim(2), mean(secondaryAxisYlim) )*(1-yZoom);
if aux_secondaryAxisXlim(1)<aux_secondaryAxisXlim(2) &&...
all(isfinite(aux_secondaryAxisXlim))
set( appDataStruct.secondaryAxesHandle, 'XLim', aux_secondaryAxisXlim );
end
if aux_secondaryAxisYlim(1)<aux_secondaryAxisYlim(2) &&...
all(isfinite(aux_secondaryAxisYlim))
set( appDataStruct.secondaryAxesHandle, 'YLim', aux_secondaryAxisYlim );
end
end
%Increase line width in plots on secondary axis
childHandle = get( appDataStruct.secondaryAxesHandle, 'Children');
for iChild = 1:length(childHandle)
if strcmpi(get(childHandle(iChild), 'Type'), 'line')
set(childHandle(iChild), 'LineWidth', 2);
end
if strcmpi(get(childHandle(iChild), 'Type'), 'image')
%Do nothing for now
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: determineSpan
%
% PURPOSE: Computes the distance between two real numbers on a 1D space.
%
% INPUT ARGUMENTS:
% v1 [double 1x1]: first number
% v2 [double 1x1]: second number
% OUTPUT ARGUMENTS:
% span [double 1x1]: computed span
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function span = determineSpan( v1, v2 )
if v1>=0 && v2>=0
span = max(v1,v2) - min(v1,v2);
end
if v1>=0 && v2<0
span = v1 - v2;
end
if v1<0 && v2>=0
span = -v1 + v2;
end
if v1<0 && v2<0
span = max(-v1,-v2) - min(-v1,-v2);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: ResizeCallback
%
% PURPOSE: Service routine to Resize event.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ResizeCallback(src,eventdata)
global appDataStruct;
if isempty(appDataStruct)
return;
end
%Get userdata
toolArray = get(src, 'userdata');
if isempty(toolArray)
return;
end
nTools = length( toolArray );
%Store Old&New Figure positions
oldFigurePosition = toolArray(1).figurePosition;
newFigurePosition = getFigurePositionInPixels();
%Backup global appDataStruct
appDataStructAux = appDataStruct;
for i=1:nTools
%Modify global vaiable, accessed by functions called below
appDataStruct = initializeToolStruct( toolArray(i) );
%Set position of secondaryAxes (automatically modified)
toolArray(i).secondaryAxesPosition = getSecondaryAxesPositionInPixels();
toolArray(i).magnifierPosition(1) = toolArray(i).magnifierPosition(1) * newFigurePosition(3)/oldFigurePosition(3);
toolArray(i).magnifierPosition(2) = toolArray(i).magnifierPosition(2) * newFigurePosition(4)/oldFigurePosition(4);
toolArray(i).magnifierPosition(3) = toolArray(i).magnifierPosition(3) * newFigurePosition(3)/oldFigurePosition(3);
toolArray(i).magnifierPosition(4) = toolArray(i).magnifierPosition(4) * newFigurePosition(4)/oldFigurePosition(4);
setMagnifierPositionInPixels( toolArray(i).magnifierPosition );
%Update view limits on secondary axis
refreshSecondaryAxisLimits();
%Update link between secondary axes and magnifier
refreshMagnifierToSecondaryAxesLink();
if i==1
%Update figure position
toolArray(i).figurePosition = getFigurePositionInPixels();
appDataStruct.figurePosition = toolArray(i).figurePosition;
end
end
%Update userdata
set(toolArray(1).figureHandle, 'userdata', toolArray);
%Update appDataStruct
appDataStruct = appDataStructAux;
%Get current position of seconday axes (in pixels)
appDataStruct.secondaryAxesPosition = getSecondaryAxesPositionInPixels();
%Get magnifier current position and size
appDataStruct.magnifierPosition = getMagnifierPositionInPixels();
clear appDataStructAux;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: KeyPressCallback
%
% PURPOSE: Service routine to KeyPress event.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function KeyPressCallback(src,eventdata)
global appDataStruct
if isempty(appDataStruct)
return;
end
currentCaracter = eventdata.Key;
currentModifier = eventdata.Modifier;
switch(currentCaracter)
case {'leftarrow'} % left arrow
%Move magnifier to the left
if isempty(currentModifier)
position = getMagnifierPositionInPixels();
magnifierPosition(1) = position(1)-1;
magnifierPosition(2) = position(2);
magnifierPosition(3) = position(3);
magnifierPosition(4) = position(4);
setMagnifierPositionInPixels( magnifierPosition );
toolArray = get( src, 'UserData' );
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool) = updateToolId( toolArray(focusedTool), focusedTool, 'noToggle' );
set( src, 'UserData', toolArray );
end
%Compress magnifier on the X axis
if strcmp(currentModifier, 'shift')
position = getMagnifierPositionInPixels();
magnifierPosition(3) = position(3)*(1 - 0.1);
if strcmpi( appDataStruct.globalZoomMode, 'off')
magnifierPosition(4) = position(4);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
magnifierPosition(4) = position(4)*(1 - 0.1);
end
magnifierPosition(1) = position(1)-(-position(3)+magnifierPosition(3))/2;
magnifierPosition(2) = position(2)-(-position(4)+magnifierPosition(4))/2;
setMagnifierPositionInPixels( magnifierPosition );
end
%Move secondary axes to the left
if strcmp(currentModifier, 'control')
position = getSecondaryAxesPositionInPixels();
secondaryAxesPosition(1) = position(1)-1;
secondaryAxesPosition(2) = position(2);
secondaryAxesPosition(3) = position(3);
secondaryAxesPosition(4) = position(4);
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
%Compress secondary axes on the X axis
if strcmp(currentModifier, 'alt')
position = getSecondaryAxesPositionInPixels();
secondaryAxesPosition(3) = position(3)*(1 - 0.1);
if strcmpi( appDataStruct.globalZoomMode, 'off')
secondaryAxesPosition(4) = position(4);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
secondaryAxesPosition(4) = position(4)*(1 - 0.1);
end
secondaryAxesPosition(1) = position(1)-(-position(3)+secondaryAxesPosition(3))/2;
secondaryAxesPosition(2) = position(2)-(-position(4)+secondaryAxesPosition(4))/2;
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
case {'rightarrow'} % right arrow
%Move magnifier to the right
if isempty(currentModifier)
position = getMagnifierPositionInPixels();
magnifierPosition(1) = position(1)+1;
magnifierPosition(2) = position(2);
magnifierPosition(3) = position(3);
magnifierPosition(4) = position(4);
setMagnifierPositionInPixels( magnifierPosition );
toolArray = get( src, 'UserData' );
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool) = updateToolId( toolArray(focusedTool), focusedTool, 'noToggle' );
set( src, 'UserData', toolArray );
end
%Expand magnifier on the X axis
if strcmp(currentModifier, 'shift')
position = getMagnifierPositionInPixels();
magnifierPosition(3) = position(3)*(1 + 0.1);
if strcmpi( appDataStruct.globalZoomMode, 'off')
magnifierPosition(4) = position(4);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
magnifierPosition(4) = position(4)*(1 + 0.1);
end
magnifierPosition(1) = position(1)-(-position(3)+magnifierPosition(3))/2;
magnifierPosition(2) = position(2)-(-position(4)+magnifierPosition(4))/2;
setMagnifierPositionInPixels( magnifierPosition );
end
%Move secondary axes to the right
if strcmp(currentModifier, 'control')
position = getSecondaryAxesPositionInPixels();
secondaryAxesPosition(1) = position(1)+1;
secondaryAxesPosition(2) = position(2);
secondaryAxesPosition(3) = position(3);
secondaryAxesPosition(4) = position(4);
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
%Expand secondary axes on the X axis
if strcmp(currentModifier, 'alt')
position = getSecondaryAxesPositionInPixels();
secondaryAxesPosition(3) = position(3)*(1 + 0.1);
if strcmpi( appDataStruct.globalZoomMode, 'off')
secondaryAxesPosition(4) = position(4);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
secondaryAxesPosition(4) = position(4)*(1 + 0.1);
end
secondaryAxesPosition(1) = position(1)-(-position(3)+secondaryAxesPosition(3))/2;
secondaryAxesPosition(2) = position(2)-(-position(4)+secondaryAxesPosition(4))/2;
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
case {'uparrow'} % up arrow
%Move magnifier to the top
if isempty(currentModifier)
position = getMagnifierPositionInPixels();
magnifierPosition(1) = position(1);
magnifierPosition(2) = position(2)+1;
magnifierPosition(3) = position(3);
magnifierPosition(4) = position(4);
setMagnifierPositionInPixels( magnifierPosition );
toolArray = get( src, 'UserData' );
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool) = updateToolId( toolArray(focusedTool), focusedTool, 'noToggle' );
set( src, 'UserData', toolArray );
end
%Expand magnifier on the Y axis
if strcmp(currentModifier, 'shift')
position = getMagnifierPositionInPixels();
if strcmpi( appDataStruct.globalZoomMode, 'off')
magnifierPosition(3) = position(3);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
magnifierPosition(3) = position(3)*(1 + 0.1);
end
magnifierPosition(4) = position(4)*(1 + 0.1);
magnifierPosition(1) = position(1)-(-position(3)+magnifierPosition(3))/2;
magnifierPosition(2) = position(2)-(-position(4)+magnifierPosition(4))/2;
setMagnifierPositionInPixels( magnifierPosition );
end
%Move secondary axes to the top
if strcmp(currentModifier, 'control')
position = getSecondaryAxesPositionInPixels();
secondaryAxesPosition(1) = position(1);
secondaryAxesPosition(2) = position(2)+1;
secondaryAxesPosition(3) = position(3);
secondaryAxesPosition(4) = position(4);
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
%Expand secondary axes on the Y axis
if strcmp(currentModifier, 'alt')
position = getSecondaryAxesPositionInPixels();
if strcmpi( appDataStruct.globalZoomMode, 'off')
secondaryAxesPosition(3) = position(3);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
secondaryAxesPosition(3) = position(3)*(1 + 0.1);
end
secondaryAxesPosition(4) = position(4)*(1 + 0.1);
secondaryAxesPosition(1) = position(1)-(-position(3)+secondaryAxesPosition(3))/2;
secondaryAxesPosition(2) = position(2)-(-position(4)+secondaryAxesPosition(4))/2;
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
case {'downarrow'} % down arrow
%Move magnifier to the bottom
if isempty(currentModifier)
position = getMagnifierPositionInPixels();
magnifierPosition(1) = position(1);
magnifierPosition(2) = position(2)-1;
magnifierPosition(3) = position(3);
magnifierPosition(4) = position(4);
setMagnifierPositionInPixels( magnifierPosition );
toolArray = get( src, 'UserData' );
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool) = updateToolId( toolArray(focusedTool), focusedTool, 'noToggle' );
set( src, 'UserData', toolArray );
end
%Compress magnifier on the Y axis
if strcmp(currentModifier, 'shift')
position = getMagnifierPositionInPixels();
if strcmpi( appDataStruct.globalZoomMode, 'off')
magnifierPosition(3) = position(3);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
magnifierPosition(3) = position(3)*(1 - 0.1);
end
magnifierPosition(4) = position(4)*(1 - 0.1);
magnifierPosition(1) = position(1)-(-position(3)+magnifierPosition(3))/2;
magnifierPosition(2) = position(2)-(-position(4)+magnifierPosition(4))/2;
setMagnifierPositionInPixels( magnifierPosition );
end
%Move secondary axes to the bottom
if strcmp(currentModifier, 'control')
position = getSecondaryAxesPositionInPixels();
secondaryAxesPosition(1) = position(1);
secondaryAxesPosition(2) = position(2)-1;
secondaryAxesPosition(3) = position(3);
secondaryAxesPosition(4) = position(4);
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
%Compress secondary axes on the Y axis
if strcmp(currentModifier, 'alt')
position = getSecondaryAxesPositionInPixels();
if strcmpi( appDataStruct.globalZoomMode, 'off')
secondaryAxesPosition(3) = position(3);
else
%If 'freezeZoomAspectRatio' to 'on', be consistent
secondaryAxesPosition(3) = position(3)*(1 - 0.1);
end
secondaryAxesPosition(4) = position(4)*(1 - 0.1);
secondaryAxesPosition(1) = position(1)-(-position(3)+secondaryAxesPosition(3))/2;
secondaryAxesPosition(2) = position(2)-(-position(4)+secondaryAxesPosition(4))/2;
setSecondaryAxesPositionInPixels( secondaryAxesPosition );
end
case {'tab'} % Tabulator
%Switch focus to next magnifier instance on the current figure
toolArray = get( src, 'UserData' );
nTools = length(toolArray);
focusedTool = find([toolArray.focusOnThisTool] == 1);
if focusedTool ~= nTools
nextFocusedTool = focusedTool+1;
else
nextFocusedTool = 1;
end
appDataStruct = initializeToolStruct( toolArray(nextFocusedTool) );
appDataStruct.focusOnThisTool = 1;
toolArray(focusedTool).focusOnThisTool = 0;
toolArray(nextFocusedTool).focusOnThisTool = 1;
if not(isempty(toolArray(focusedTool).toolIdHandle))
set(toolArray(focusedTool).toolIdHandle,'BackgroundColor', 'black', 'Color', 'white');
set(toolArray(nextFocusedTool).toolIdHandle,'BackgroundColor', 'red', 'Color', 'white');
end
set( src, 'UserData', toolArray );
case {'d'} % 'd'
%Delete focused instance
if strcmp(currentModifier, 'control')
toolArray = get( src, 'UserData' );
nTools = length(toolArray);
focusedTool = find([toolArray.focusOnThisTool] == 1);
delete(toolArray(focusedTool).magnifierHandle);
delete(toolArray(focusedTool).linkHandle);
delete(toolArray(focusedTool).secondaryAxesHandle);
if nTools > 1
%Set focus to next instance
if focusedTool ~= nTools
nextFocusedTool = focusedTool+1;
else
nextFocusedTool = 1;
end
toolArray(nextFocusedTool).focusOnThisTool = 1;
appDataStruct = initializeToolStruct( toolArray(nextFocusedTool) );
toolArray(focusedTool) = [];
set( src, 'UserData', toolArray );
else
%No instance to set focus on
appDataStruct = [];
set( src, 'UserData', [] );
end
end
case {'a'} % 'a'
%Debug info
if strcmp(currentModifier, 'control')
magnifierPosition = getMagnifierPositionInPixels();
disp(sprintf('Magnifier position: [%g %g %g %g];', magnifierPosition(1), magnifierPosition(2), magnifierPosition(3), magnifierPosition(4) ));
secondaryAxesPosition = getSecondaryAxesPositionInPixels();
disp(sprintf('Secondary axes position: [%g %g %g %g];', secondaryAxesPosition(1), secondaryAxesPosition(2), secondaryAxesPosition(3), secondaryAxesPosition(4) ));
end
case {'q'} % 'q'
%additional xooming factors reseted
if strcmp(currentModifier, 'control')
appDataStruct.secondaryAxesAdditionalZoomingFactor = [0 0];
end
case {'i'} % 'i'
%display/hide on-screen tool identifier
if strcmp(currentModifier, 'control')
toolArray = get( src, 'UserData' );
nTools = length(toolArray);
for iTool = 1:nTools
toolArray(iTool) = updateToolId( toolArray(iTool), iTool, 'toggle' );
end
set( src, 'UserData', toolArray );
end
case {'pageup'} % '+'
zoomFactor = appDataStruct.secondaryAxesAdditionalZoomingFactor;
%Increase additional zooming factor on X-axis
if isempty(currentModifier)
zoomFactor(1) = zoomFactor(1) + 0.1;
if strcmpi( appDataStruct.globalZoomMode, 'on')
zoomFactor(2) = zoomFactor(2) + 0.1;
end
appDataStruct.secondaryAxesAdditionalZoomingFactor = zoomFactor;
end
%Increase additional zooming factor on Y-axis
if strcmp(currentModifier, 'shift')
zoomFactor(2) = zoomFactor(2) + 0.1;
if strcmpi( appDataStruct.globalZoomMode, 'on')
zoomFactor(1) = zoomFactor(1) + 0.1;
end
appDataStruct.secondaryAxesAdditionalZoomingFactor = zoomFactor;
end
case {'pagedown'} % '-'
zoomFactor = appDataStruct.secondaryAxesAdditionalZoomingFactor;
%Redude additional zooming factor on X-axis
if isempty(currentModifier)
zoomFactor(1) = zoomFactor(1) - 0.1;
if strcmpi( appDataStruct.globalZoomMode, 'on')
zoomFactor(2) = zoomFactor(2) - 0.1;
end
appDataStruct.secondaryAxesAdditionalZoomingFactor = zoomFactor;
end
%Redude additional zooming factor on Y-axis
if strcmp(currentModifier, 'shift')
zoomFactor(2) = zoomFactor(2) - 0.1;
if strcmpi( appDataStruct.globalZoomMode, 'on')
zoomFactor(1) = zoomFactor(1) - 0.1;
end
appDataStruct.secondaryAxesAdditionalZoomingFactor = zoomFactor;
end
otherwise
end
%Update view limits on secondary axis
refreshSecondaryAxisLimits();
%Update link between secondary axes and magnifier
refreshMagnifierToSecondaryAxesLink();
% %Update userdata
% toolArray = get(src, 'userdata');
% focusedTool = find([toolArray.focusOnThisTool] == 1);
% toolArray(focusedTool) = appDataStruct;
% set(src, 'userData', toolArray);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: ButtonMotionCallback
%
% PURPOSE: Service routine to ButtonMotion event.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ButtonMotionCallback(src,eventdata)
global appDataStruct
if isempty(appDataStruct)
return;
end
% pointerPos = get(appDataStructuct.figure.handle, 'CurrentPoint');
% disp(sprintf('X: %g ; Y: %g', pointerPos(1), pointerPos(2)) );
getPointerArea();
%If Left mouse button not pressed, exit
if appDataStruct.ButtonDown == false
return;
end
%If Left mouse button pressed while the pointer is moving (drag)
switch appDataStruct.pointerArea
case 'insideSecondaryAxis'
%Get current position of seconday axes (in pixels)
appDataStruct.secondaryAxesPosition = getSecondaryAxesPositionInPixels();
%Get pointer position on figure's frame
currentPointerPositionOnFigureFrame = getPointerPositionOnFigureFrame();
pointerPositionOnButtonDown = appDataStruct.pointerPositionOnButtonDown;
%Modify position
secondaryAxisPosition_W = appDataStruct.secondaryAxesPosition(3);
secondaryAxisPosition_H = appDataStruct.secondaryAxesPosition(4);
secondaryAxisPosition_X = appDataStruct.secondaryAxesPosition(1) + (-pointerPositionOnButtonDown(1)+currentPointerPositionOnFigureFrame(1));
secondaryAxisPosition_Y = appDataStruct.secondaryAxesPosition(2) + (-pointerPositionOnButtonDown(2)+currentPointerPositionOnFigureFrame(2));
appDataStruct.pointerPositionOnButtonDown = currentPointerPositionOnFigureFrame;
%Set initial position and size of secondary axes
setSecondaryAxesPositionInPixels( [...
secondaryAxisPosition_X,...
secondaryAxisPosition_Y,...
secondaryAxisPosition_W,...
secondaryAxisPosition_H...
] );
case 'insideMagnifier'
%Get magnifier current position and size
appDataStruct.magnifierPosition = getMagnifierPositionInPixels();
%Get pointer position on figure's frame
currentPointerPosition = getPointerPositionOnFigureFrame();
pointerPositionOnButtonDown = appDataStruct.pointerPositionOnButtonDown;
%Modify magnifier position
magnifierPosition_W = appDataStruct.magnifierPosition(3);
magnifierPosition_H = appDataStruct.magnifierPosition(4);
magnifierPosition_X = appDataStruct.magnifierPosition(1) + (-pointerPositionOnButtonDown(1)+currentPointerPosition(1));
magnifierPosition_Y = appDataStruct.magnifierPosition(2) + (-pointerPositionOnButtonDown(2)+currentPointerPosition(2));
appDataStruct.pointerPositionOnButtonDown = currentPointerPosition;
%Set initial position and size of magnifying rectangle
setMagnifierPositionInPixels( [...
magnifierPosition_X...
magnifierPosition_Y...
magnifierPosition_W...
magnifierPosition_H...
] );
%Refresh zooming on secondary axis, based on magnifier position and extend
refreshSecondaryAxisLimits();
toolArray = get( src, 'UserData' );
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool) = updateToolId( toolArray(focusedTool), focusedTool, 'noToggle' );
set( src, 'UserData', toolArray );
otherwise
% appDataStructuct.pointerArea
end
%Update link between secondary axes and magnifier
refreshMagnifierToSecondaryAxesLink();
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: ButtonDownCallback
%
% PURPOSE: Service routine to ButtonDown event.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ButtonDownCallback(src,eventdata)
global appDataStruct
if isempty(appDataStruct)
return;
end
if strcmpi( get(appDataStruct.figureHandle, 'SelectionType'), 'normal' )
%Respond to left mouse button
appDataStruct.ButtonDown = true;
%Get pointer position on figure's frame
appDataStruct.pointerPositionOnButtonDown = getPointerPositionOnFigureFrame();
elseif strcmpi( get(appDataStruct.figureHandle, 'SelectionType'), 'alt' )
%Display contextual menu?
elseif strcmpi( get(appDataStruct.figureHandle, 'SelectionType'), 'open' )
%Is pointer on any active area?
toolArray = get(src, 'userdata');
nTools = length(toolArray);
focusedTool = find([toolArray.focusOnThisTool] == 1);
nextFocusedTool = 0;
foundActive = false;
while nextFocusedTool<=nTools-1 && foundActive == false
nextFocusedTool = nextFocusedTool+1;
appDataStructAux = appDataStruct;
appDataStruct = initializeToolStruct( toolArray(nextFocusedTool) );
getPointerArea();
if ~strcmp( appDataStruct.pointerArea, 'none')
foundActive = true;
end
end
if foundActive == true
%Switch focus to next magnifier instance on the current figure
appDataStruct = initializeToolStruct( toolArray(nextFocusedTool) );
appDataStruct.focusOnThisTool = 1;
toolArray(focusedTool).focusOnThisTool = 0;
toolArray(nextFocusedTool).focusOnThisTool = 1;
if not(isempty(toolArray(focusedTool).toolIdHandle))
set(toolArray(focusedTool).toolIdHandle,'BackgroundColor', 'black', 'Color', 'white');
set(toolArray(nextFocusedTool).toolIdHandle,'BackgroundColor', 'red', 'Color', 'white');
end
set( src, 'UserData', toolArray );
else
appDataStruct = appDataStructAux;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: ButtonUpCallback
%
% PURPOSE: Service routine to ButtonUp event.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ButtonUpCallback(src,eventdata)
global appDataStruct
if isempty(appDataStruct)
return;
end
% if strcmp(appDataStruct.pointerArea, 'insideMagnifier')
% %Refresh zooming on secondary axis, based on magnifier position and extend
% refreshSecondaryAxisLimits();
% end
appDataStruct.ButtonDown = false;
toolArray = get(src, 'userdata');
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool).ButtonDown = false;
set(src, 'userdata', toolArray);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: DeleteCallback
%
% PURPOSE: Service routine to Delete event.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DeleteCallback(src,eventdata)
global appDataStruct;
if isempty(appDataStruct)
return;
end
toolArray = get(src, 'UserData');
%Recover old callback handles from the first instance
set( src, 'WindowButtonDownFcn', toolArray(1).figureOldWindowButtonDownFcn );
set( src, 'WindowButtonUpFcn', toolArray(1).figureOldWindowButtonUpFcn );
set( src, 'WindowButtonMotionFcn', toolArray(1).figureOldWindowButtonMotionFcn );
set( src, 'KeyPressFcn', toolArray(1).figureOldKeyPressFcn );
set( src, 'DeleteFcn', toolArray(1).figureOldDeleteFcn );
set( src, 'ResizeFcn', toolArray(1).figureOldResizeFcn );
%Clear global variable when figure is closed
clear global appDataStructuct;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: getPointerPositionOnFigureFrame
%
% PURPOSE: determine if the position of the mouse pointer on the figure frame, in pixels.
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% pointerPositionOnFigureFrame [double 1x2]: (X Y)
% position
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function pointerPositionOnFigureFrame = getPointerPositionOnFigureFrame()
global appDataStruct
if isempty(appDataStruct)
return;
end
%Get position of mouse pointer on screen
defaultUnits = get(appDataStruct.figureHandle,'Units');
set(appDataStruct.figureHandle, 'Units', 'pixels');
pointerPositionOnFigureFrame = get(appDataStruct.figureHandle,'CurrentPoint');
set(appDataStruct.figureHandle, 'Units', defaultUnits);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: getPointerArea
%
% PURPOSE: determine if the mouse pointer is on an active area. Change
% pointer image if this is the case, and communicate the status.
%
% INPUT ARGUMENTS:
% appDataStructuct [struct 1x1]: global variable
% OUTPUT ARGUMENTS:
% change image of pointer (ACTION)
% appDataStructuct.pointerArea: ID of the active area
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function getPointerArea()
global appDataStruct
if isempty(appDataStruct)
return;
end
%Get current pointer position on figure frame
pointerPositionOnFigureFrame = getPointerPositionOnFigureFrame();
%Get current secondaryAxes position
secondaryAxesPosition = getSecondaryAxesPositionInPixels();
%Get current magnifier position
magnifierPosition = getMagnifierPositionInPixels();
%If mouse pointer on the secondary axis
if pointerPositionOnFigureFrame(1)>=secondaryAxesPosition(1) &&...
pointerPositionOnFigureFrame(1)<=secondaryAxesPosition(1)+secondaryAxesPosition(3) &&...
pointerPositionOnFigureFrame(2)>=secondaryAxesPosition(2) &&...
pointerPositionOnFigureFrame(2)<=secondaryAxesPosition(2)+secondaryAxesPosition(4)
%Pointer inside secondary axis
set(appDataStruct.figureHandle, 'Pointer', 'fleur');
appDataStruct.pointerArea = 'insideSecondaryAxis';
elseif pointerPositionOnFigureFrame(1)>=magnifierPosition(1) &&...
pointerPositionOnFigureFrame(1)<=magnifierPosition(1)+magnifierPosition(3) &&...
pointerPositionOnFigureFrame(2)>=magnifierPosition(2) &&...
pointerPositionOnFigureFrame(2)<=magnifierPosition(2)+magnifierPosition(4)
%Pointer inside magnifier
set(appDataStruct.figureHandle, 'Pointer', 'fleur');
appDataStruct.pointerArea = 'insideMagnifier';
else
%Otherwise
set(appDataStruct.figureHandle, 'Pointer', 'arrow');
appDataStruct.pointerArea = 'none';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: getFigurePositionInPixels
%
% PURPOSE: obtain the position and size of the figure, relative to the
% lower left corner of the screen, in pixels.
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the figure frame
% Y of lower left corner of the figure frame
% Width of the figure frame
% Height of the figure frame
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function position = getFigurePositionInPixels()
global appDataStruct
if isempty(appDataStruct)
return;
end
defaultUnits = get(appDataStruct.figureHandle,'Units');
set(appDataStruct.figureHandle,'Units', 'pixels');
position = get(appDataStruct.figureHandle,'Position'); %pixels [ low bottom width height]
set(appDataStruct.figureHandle,'Units', defaultUnits);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: getMainAxesPositionInPixels
%
% PURPOSE: obtain the position and size of the main axes, relative to the
% lower left corner of the figure, in pixels. This fucntion locates the
% lower-left corner of the displayed axes, accounting for all conditions of
% DataAspectRatio and PlotBoxAspectRatio.
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the axis frame
% Y of lower left corner of the axis frame
% Width of the axis frame
% Height of the axis frame
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function position = getMainAxesPositionInPixels()
global appDataStruct
if isempty(appDataStruct)
position = [];
return;
end
%Characterize mainAxes in axes units
mainAxisXLim = get( appDataStruct.mainAxesHandle, 'XLim' );
mainAxisYLim = get( appDataStruct.mainAxesHandle, 'YLim' );
spanX = determineSpan(mainAxisXLim(1), mainAxisXLim(2) );
spanY = determineSpan(mainAxisYLim(1), mainAxisYLim(2));
%Capture default units of mainAxes, and fix units to 'pixels'
defaultUnits = get(appDataStruct.mainAxesHandle,'Units');
set(appDataStruct.mainAxesHandle, 'Units', 'pixels');
%Obtain values in 'pixels'
mainAxesPosition = get(appDataStruct.mainAxesHandle, 'Position');
dataAspectRatioMode = get(appDataStruct.mainAxesHandle, 'DataAspectRatioMode');
dataAspectRatio = get(appDataStruct.mainAxesHandle, 'DataAspectRatio');
plotBoxAspectRatioMode = get(appDataStruct.mainAxesHandle, 'PlotBoxAspectRatioMode');
plotBoxAspectRatio = get(appDataStruct.mainAxesHandle, 'PlotBoxAspectRatio');
%Determine correction values
dataAspectRatioLimits = (spanX/dataAspectRatio(1))/(spanY/dataAspectRatio(2));
plotBoxAspectRatioRelation = plotBoxAspectRatio(1)/plotBoxAspectRatio(2);
mainAxesRatio = mainAxesPosition(3)/mainAxesPosition(4);
%Id DataAspectRatio to auto and PlotBoxAspectRatio to auto
if ~strcmpi( dataAspectRatioMode, 'manual') && ~strcmpi( plotBoxAspectRatioMode, 'manual')
%Recover default units of mainAxes
set(appDataStruct.mainAxesHandle,'Units', defaultUnits);
%Obtain 'real' position from a temporal axes
temporalAxes = axes('Visible', 'off');
set(temporalAxes, 'Units', 'pixels');
set(temporalAxes, 'Position', mainAxesPosition);
position = get(temporalAxes, 'Position');
delete(temporalAxes);
return;
end
%If DataAspectRatio to manual
if strcmpi( dataAspectRatioMode, 'manual')
if dataAspectRatioLimits <= mainAxesRatio
position(4) = mainAxesPosition(4);
position(3) = mainAxesPosition(4) * dataAspectRatioLimits;
position(2) = mainAxesPosition(2);
position(1) = mainAxesPosition(1) + (mainAxesPosition(3) - position(3))/2;
else
position(1) = mainAxesPosition(1);
position(3) = mainAxesPosition(3);
position(4) = mainAxesPosition(3)/dataAspectRatioLimits;
position(2) = mainAxesPosition(2) + (mainAxesPosition(4) - position(4))/2;
end
elseif strcmpi( plotBoxAspectRatioMode, 'manual')
% Or PlotBoxAspectRatio to manual
if plotBoxAspectRatioRelation <= mainAxesRatio
position(4) = mainAxesPosition(4);
position(3) = mainAxesPosition(4) * plotBoxAspectRatioRelation;
position(2) = mainAxesPosition(2);
position(1) = mainAxesPosition(1) + (mainAxesPosition(3) - position(3))/2;
else
position(1) = mainAxesPosition(1);
position(3) = mainAxesPosition(3);
position(4) = mainAxesPosition(3)/plotBoxAspectRatioRelation;
position(2) = mainAxesPosition(2) + (mainAxesPosition(4) - position(4))/2;
end
end
%Recover default units of mainAxes
set(appDataStruct.mainAxesHandle, 'Units', defaultUnits);
%Obtain 'real' position from a temporal axes
temporalAxes = axes('Visible', 'off');
set(temporalAxes, 'Units', 'pixels');
set(temporalAxes, 'Position', position );
position = get(temporalAxes, 'Position');
delete(temporalAxes);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: getMagnifierPositionInPixels
%
% PURPOSE: obtain the position (of the lower left corner) and size of the
% magnifier, relative to the lower left corner of the figure, in pixels.
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the magnifier
% Y of lower left corner of the magnifier
% Width of the magnifier
% Height of the magnifier
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function position = getMagnifierPositionInPixels()
global appDataStruct
if isempty(appDataStruct)
return;
end;
defaultUnits = get(appDataStruct.magnifierHandle, 'Units');
set(appDataStruct.magnifierHandle, 'Units', 'pixels');
position = get(appDataStruct.magnifierHandle, 'Position');
set(appDataStruct.magnifierHandle, 'Units', defaultUnits );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: getSecondaryAxesPositionInPixels
%
% PURPOSE: obtain the position and size of the secondary axis, relative to the
% lower left corner of the figure, in pixels. Includes legends and axes
% numbering
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the axis frame
% Y of lower left corner of the axis frame
% Width of the axis frame
% Height of the axis frame
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function position = getSecondaryAxesPositionInPixels()
global appDataStruct
if isempty(appDataStruct)
return;
end
defaultUnits = get(appDataStruct.secondaryAxesHandle,'Units');
set(appDataStruct.secondaryAxesHandle,'Units', 'pixels');
position = get(appDataStruct.secondaryAxesHandle,'Position'); %[ left bottom width height]
set(appDataStruct.secondaryAxesHandle,'Units', defaultUnits);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: setSecondaryAxesPositionInPixels
%
% PURPOSE: fix the position and size of the secondary axis, relative to the
% lower left corner of the figure, in pixels.
%
% INPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the axis frame
% Y of lower left corner of the axis frame
% Width of the axis frame
% Height of the axis frame
% OUTPUT ARGUMENTS:
% none
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function setSecondaryAxesPositionInPixels( position )
global appDataStruct
if isempty(appDataStruct)
return;
end
%Get position of secondary axes
defaultUnits = get(appDataStruct.secondaryAxesHandle,'Units');
set(appDataStruct.secondaryAxesHandle, 'Units', 'pixels');
set( appDataStruct.secondaryAxesHandle,...
'Position', [...
position(1),...
position(2),...
position(3),...
position(4)...
]...
);
% tightInset = get( appDataStruct.secondaryAxes.handle, 'TightInset' );
set(appDataStruct.secondaryAxesHandle,'Units', defaultUnits);
%Update appDataStruct
appDataStruct.secondaryAxesPosition = getSecondaryAxesPositionInPixels();
%Update 'userdata'
toolArray = get(appDataStruct.figureHandle, 'userdata');
if ~isempty(toolArray)
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool).secondaryAxesPosition = appDataStruct.secondaryAxesPosition;
set(appDataStruct.figureHandle, 'userdata', toolArray);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: setMagnifierPositionInPixels
%
% PURPOSE: fix the position and size of the magnifier, relative to the
% lower left corner of the figure, in pixels.
%
% INPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the magnifier
% Y of lower left corner of the magnifier
% Width of the magnifier frame
% Height of the magnifier frame
% OUTPUT ARGUMENTS:
% none
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function setMagnifierPositionInPixels( position )
global appDataStruct
if isempty(appDataStruct)
return;
end
%Limit position of magnifier within the main axes
mainAxesPosition = getMainAxesPositionInPixels();
if position(1)<mainAxesPosition(1)
position(1) = mainAxesPosition(1);
end
if position(1)+position(3)>mainAxesPosition(1)+mainAxesPosition(3)
position(1) = mainAxesPosition(1)+mainAxesPosition(3)-position(3);
end
if position(2)<mainAxesPosition(2)
position(2) = mainAxesPosition(2);
end
if position(2)+position(4)>mainAxesPosition(2)+mainAxesPosition(4)
position(2) = mainAxesPosition(2)+mainAxesPosition(4)-position(4);
end
%Create of set magnifier
if isempty(appDataStruct.magnifierHandle)
if strcmpi(appDataStruct.magnifierShape, 'rectangle')
appDataStruct.magnifierHandle = ...
annotation( 'rectangle',...
'Units', 'pixels',...
'Position', position,...
'LineWidth', appDataStruct.globalEdgeWidth,...
'LineStyle','-',...
'EdgeColor', appDataStruct.globalEdgeColor...
);
end
if strcmpi(appDataStruct.magnifierShape, 'ellipse')
appDataStruct.magnifierHandle = ...
annotation( 'ellipse',...
'Units', 'pixels',...
'Position', position,...
'LineWidth', appDataStruct.globalEdgeWidth,...
'LineStyle','-',...
'EdgeColor', appDataStruct.globalEdgeColor...
);
end
else
set( appDataStruct.magnifierHandle,...
'Position', position,...
'LineWidth', appDataStruct.globalEdgeWidth,...
'EdgeColor', appDataStruct.globalEdgeColor );
end
%Update appDataStruct
appDataStruct.magnifierPosition = getMagnifierPositionInPixels();
%Update 'userdata'
toolArray = get(appDataStruct.figureHandle, 'userdata');
if ~isempty(toolArray)
focusedTool = find([toolArray.focusOnThisTool] == 1);
toolArray(focusedTool).magnifierPosition = appDataStruct.magnifierPosition;
set(appDataStruct.figureHandle, 'userdata', toolArray);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: refreshMagnifierToSecondaryAxesLink
%
% PURPOSE: Updates the line connection between the magnifier and the secondary axes.
%
% INPUT ARGUMENTS:
%
% OUTPUT ARGUMENTS:
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function refreshMagnifierToSecondaryAxesLink()
global appDataStruct;
if isempty(appDataStruct)
return;
end
%Don't display link if not requestred
linkStyle = appDataStruct.linkDisplayStyle;
if strcmpi( linkStyle(1), 'none')
return;
end
%Get position and size of figure in pixels
figurePosition = getFigurePositionInPixels();
%Get position and size of secondary axes in pixels
secondaryAxesPosition = getSecondaryAxesPositionInPixels();
defaultUnits = get(appDataStruct.secondaryAxesHandle, 'Units');
set(appDataStruct.secondaryAxesHandle, 'Units', 'pixels');
tightInset = get(appDataStruct.secondaryAxesHandle, 'TightInset');
set(appDataStruct.secondaryAxesHandle, 'Units', defaultUnits);
%Get position and size of secondary axes in pixels
magnifierPosition = getMagnifierPositionInPixels();
if strcmpi( linkStyle, 'straight')
%Magnifier Hot points
magnifierHotPoints = [...
magnifierPosition(1) + magnifierPosition(3)/2 magnifierPosition(2);...
magnifierPosition(1) + magnifierPosition(3) magnifierPosition(2)+magnifierPosition(4)/2;...
magnifierPosition(1) + magnifierPosition(3)/2 magnifierPosition(2)+magnifierPosition(4);...
magnifierPosition(1) magnifierPosition(2)+magnifierPosition(4)/2;...
];
%Secondary axes Hot points
secondaryAxesHotPoints = [...
secondaryAxesPosition(1) + secondaryAxesPosition(3)/2 secondaryAxesPosition(2) - tightInset(2) - 2;...
secondaryAxesPosition(1) + secondaryAxesPosition(3) secondaryAxesPosition(2)+secondaryAxesPosition(4)/2;...
secondaryAxesPosition(1) + secondaryAxesPosition(3)/2 secondaryAxesPosition(2)+secondaryAxesPosition(4);...
secondaryAxesPosition(1) - tightInset(1) - 2 secondaryAxesPosition(2)+secondaryAxesPosition(4)/2;...
];
%Minimize distance between hot spots
L1 = size(magnifierHotPoints, 1);
L2 = size(secondaryAxesHotPoints, 1);
[iMagnifierHotPoints iSecondaryAxesHotPoints] = meshgrid(1:L1, 1:L2);
D2 = ( magnifierHotPoints(iMagnifierHotPoints(:),1) - secondaryAxesHotPoints(iSecondaryAxesHotPoints(:),1) ).^2 + ...
( magnifierHotPoints(iMagnifierHotPoints(:),2) - secondaryAxesHotPoints(iSecondaryAxesHotPoints(:),2) ).^2;
[C,I] = sort( D2, 'ascend' );
X(1) = magnifierHotPoints(iMagnifierHotPoints(I(1)),1);
Y(1) = magnifierHotPoints(iMagnifierHotPoints(I(1)),2);
X(2) = secondaryAxesHotPoints(iSecondaryAxesHotPoints(I(1)),1);
Y(2) = secondaryAxesHotPoints(iSecondaryAxesHotPoints(I(1)),2);
%Plot/update line
if isempty(appDataStruct.linkHandle)
appDataStruct.linkHandle = annotation( 'line', X/figurePosition(3), Y/figurePosition(4),...
'LineWidth', appDataStruct.globalEdgeWidth,...
'Color', appDataStruct.globalEdgeColor );
else
set(appDataStruct.linkHandle, 'X', X/figurePosition(3), 'Y', Y/figurePosition(4),...
'LineWidth', appDataStruct.globalEdgeWidth,...
'Color', appDataStruct.globalEdgeColor );
end
end
if strcmpi( linkStyle, 'edges')
%Magnifier Hot points
magnifierHotPoints = [...
magnifierPosition(1) - 3 magnifierPosition(2);...
magnifierPosition(1) + magnifierPosition(3) magnifierPosition(2);...
magnifierPosition(1) + magnifierPosition(3) magnifierPosition(2)+magnifierPosition(4);...
magnifierPosition(1) - 3 magnifierPosition(2)+magnifierPosition(4)...
];
%Secondary axes Hot points
secondaryAxesHotPoints = [...
secondaryAxesPosition(1) secondaryAxesPosition(2);...
secondaryAxesPosition(1) + secondaryAxesPosition(3) secondaryAxesPosition(2);...
secondaryAxesPosition(1) + secondaryAxesPosition(3) secondaryAxesPosition(2)+secondaryAxesPosition(4);...
secondaryAxesPosition(1) secondaryAxesPosition(2)+secondaryAxesPosition(4)...
];
for i=1:4
X(1) = magnifierHotPoints(i,1);
Y(1) = magnifierHotPoints(i,2);
X(2) = secondaryAxesHotPoints(i,1);
Y(2) = secondaryAxesHotPoints(i,2);
%If intersection with secondary Axes bottom edge
% intersectionPoint = intersectionPointInPixels(...
% [X(1) Y(1) X(2) Y(2)], ...
% [ secondaryAxesPosition(1)...
% secondaryAxesPosition(2)...
% secondaryAxesPosition(1)+secondaryAxesPosition(3)...
% secondaryAxesPosition(2) ]...
% );
% if ~isempty(intersectionPoint)
% D2_1 = (X(1)-X(2))^2 + (Y(1)-Y(2))^2;
% D2_2 = (X(1)-intersectionPoint(1))^2 + (Y(1)-intersectionPoint(2))^2;
% if D2_2<D2_1
% %link to intersecting point
% X(2) = intersectionPoint(1);
% Y(2) = intersectionPoint(2);
% end
% end
%
% %If intersection with secondary Axes top edge
% intersectionPoint = intersectionPointInPixels(...
% [X(1) Y(1) X(2) Y(2)], ...
% [ secondaryAxesPosition(1)...
% secondaryAxesPosition(2)+secondaryAxesPosition(4)...
% secondaryAxesPosition(1)+secondaryAxesPosition(3)...
% secondaryAxesPosition(2)+secondaryAxesPosition(4) ]...
% );
% if ~isempty(intersectionPoint)
% D2_1 = (X(1)-X(2))^2 + (Y(1)-Y(2))^2;
% D2_2 = (X(1)-intersectionPoint(1))^2 + (Y(1)-intersectionPoint(2))^2;
% if D2_2<D2_1
% %link to intersecting point
% X(2) = intersectionPoint(1);
% Y(2) = intersectionPoint(2);
% end
% end
%
% %If intersection with secondary Axes left edge
% intersectionPoint = intersectionPointInPixels(...
% [X(1) Y(1) X(2) Y(2)], ...
% [ secondaryAxesPosition(1)...
% secondaryAxesPosition(2)...
% secondaryAxesPosition(1)...
% secondaryAxesPosition(2)+secondaryAxesPosition(4) ]...
% );
% if ~isempty(intersectionPoint)
% D2_1 = (X(1)-X(2))^2 + (Y(1)-Y(2))^2;
% D2_2 = (X(1)-intersectionPoint(1))^2 + (Y(1)-intersectionPoint(2))^2;
% if D2_2<D2_1
% %link to intersecting point
% X(2) = intersectionPoint(1);
% Y(2) = intersectionPoint(2);
% end
% end
%
% %If intersection with secondary Axes right edge
% intersectionPoint = intersectionPointInPixels(...
% [X(1) Y(1) X(2) Y(2)], ...
% [ secondaryAxesPosition(1)+secondaryAxesPosition(3)...
% secondaryAxesPosition(2)...
% secondaryAxesPosition(1)+secondaryAxesPosition(3)...
% secondaryAxesPosition(2)+secondaryAxesPosition(4) ]...
% );
% if ~isempty(intersectionPoint)
% D2_1 = (X(1)-X(2))^2 + (Y(1)-Y(2))^2;
% D2_2 = (X(1)-intersectionPoint(1))^2 + (Y(1)-intersectionPoint(2))^2;
% if D2_2<D2_1
% %link to intersecting point
% X(2) = intersectionPoint(1);
% Y(2) = intersectionPoint(2);
% end
% end
%Plot/update line
if isempty( appDataStruct.linkHandle )
newlinkHandle = annotation( 'line', X/figurePosition(3), Y/figurePosition(4),...
'LineWidth', appDataStruct.globalEdgeWidth,...
'LineStyle', ':',...
'Color', appDataStruct.globalEdgeColor );
linkHandle = appDataStruct.linkHandle;
appDataStruct.linkHandle = [linkHandle newlinkHandle];
else
linkHandle = appDataStruct.linkhandle;
set( linkHandle(i), 'X', X/figurePosition(3), 'Y', Y/figurePosition(4),...
'LineWidth', appDataStruct.globalEdgeWidth,...
'Color', appDataStruct.globalEdgeColor );
end
end
end
if strcmpi( linkStyle, 'elbow')
%Magnifier Hot points
magnifierHotPoints = [...
magnifierPosition(1) + magnifierPosition(3)/2 magnifierPosition(2);...
magnifierPosition(1) + magnifierPosition(3) magnifierPosition(2)+magnifierPosition(4)/2;...
magnifierPosition(1) + magnifierPosition(3)/2 magnifierPosition(2)+magnifierPosition(4);...
magnifierPosition(1) magnifierPosition(2)+magnifierPosition(4)/2;...
];
%Secondary axes Hot points
secondaryAxesHotPoints = [...
secondaryAxesPosition(1) + secondaryAxesPosition(3)/2 secondaryAxesPosition(2) - tightInset(2) - 2;...
secondaryAxesPosition(1) + secondaryAxesPosition(3) secondaryAxesPosition(2)+secondaryAxesPosition(4)/2;...
secondaryAxesPosition(1) + secondaryAxesPosition(3)/2 secondaryAxesPosition(2)+secondaryAxesPosition(4);...
secondaryAxesPosition(1) - tightInset(1) - 2 secondaryAxesPosition(2)+secondaryAxesPosition(4)/2;...
];
%Allowed connections
% iMagnifierHotPoints(1) = 1;
% iSecondaryAxesHotPoints(1) = 4;
% iMagnifierHotPoints(2) = 1;
% iSecondaryAxesHotPoints(2) = 2;
% iMagnifierHotPoints(3) = 2;
% iSecondaryAxesHotPoints(3) = 3;
% iMagnifierHotPoints(4) = 2;
% iSecondaryAxesHotPoints(4) = 1;
% iMagnifierHotPoints(5) = 3;
% iSecondaryAxesHotPoints(5) = 4;
% iMagnifierHotPoints(6) = 3;
% iSecondaryAxesHotPoints(6) = 2;
% iMagnifierHotPoints(7) = 4;
% iSecondaryAxesHotPoints(7) = 1;
% iMagnifierHotPoints(8) = 4;
% iSecondaryAxesHotPoints(8) = 3;
% iMagnifierHotPoints(9) = 1;
% iSecondaryAxesHotPoints(9) = 3;
% iMagnifierHotPoints(10) = 2;
% iSecondaryAxesHotPoints(10) = 4;
% iMagnifierHotPoints(11) = 3;
% iSecondaryAxesHotPoints(11) = 1;
% iMagnifierHotPoints(12) = 4;
% iSecondaryAxesHotPoints(12) = 2;
%Minimize distance between hot spots
L1 = size(magnifierHotPoints, 1);
L2 = size(secondaryAxesHotPoints, 1);
[iMagnifierHotPoints iSecondaryAxesHotPoints] = meshgrid(1:L1, 1:L2);
D2 = ( magnifierHotPoints(iMagnifierHotPoints(:),1) - secondaryAxesHotPoints(iSecondaryAxesHotPoints(:),1) ).^2 + ...
( magnifierHotPoints(iMagnifierHotPoints(:),2) - secondaryAxesHotPoints(iSecondaryAxesHotPoints(:),2) ).^2;
[C,I] = sort( D2, 'ascend' );
X(1) = magnifierHotPoints(iMagnifierHotPoints(I(1)),1);
Y(1) = magnifierHotPoints(iMagnifierHotPoints(I(1)),2);
X(2) = secondaryAxesHotPoints(iSecondaryAxesHotPoints(I(1)),1);
Y(2) = secondaryAxesHotPoints(iSecondaryAxesHotPoints(I(1)),2);
%Plot/update line
if isempty( appDataStruct.linkHandle )
newlinkHandle = annotation( 'line', X/figurePosition(3), Y/figurePosition(4),...
'LineWidth', appDataStruct.globalEdgeWidth,...
'Color', appDataStruct.globalEdgeColor );
linkHandle = appDataStruct.linkHandle;
appDataStruct.linkHandle = [linkHandle newlinkHandle];
else
linkHandle = appDataStruct.linkhandle;
set( linkHandle, 'X', X/figurePosition(3), 'Y', Y/figurePosition(4),...
'LineWidth', appDataStruct.globalEdgeWidth,...
'Color', appDataStruct.globalEdgeColor );
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: intersectionPointInPixels
%
% PURPOSE: Computes constrained intersection of two lines in pixels, on the 2D space
%
% INPUT ARGUMENTS:
% line1 [double 1x4]: [Xstart Ystart Xend Yend]
% line2 [double 1x4]: [Xstart Ystart Xend Yend]
%
% OUTPUT ARGUMENTS:
% intersectionPont [double 1x2]: [X Y] intersection
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function intersectionPoint = intersectionPointInPixels( line1, line2)
%Cartessian caracterization of line 1
X1(1) = line1(1);
Y1(1) = line1(2);
X1(2) = line1(3);
Y1(2) = line1(4);
a1 = (Y1(2) - Y1(1)) / (X1(2) - X1(1));
b1 = Y1(1) - X1(1)*a1;
%Cartessian caracterization of line 2
X2(1) = line2(1);
Y2(1) = line2(2);
X2(2) = line2(3);
Y2(2) = line2(4);
a2 = (Y2(2) - Y2(1)) / (X2(2) - X2(1));
b2 = Y2(1) - X2(1)*a2;
%Intersection
if isfinite(a1) && isfinite(a2)
intersectionPoint(1) = (b2-b1) / (a1-a2);
intersectionPoint(2) = intersectionPoint(1)*a1 + b1;
end
%Pathologic case 1 (line2 x=constant)
if isfinite(a1) && ~isfinite(a2)
intersectionPoint(1) = X2(1);
intersectionPoint(2) = intersectionPoint(1)*a1 + b1;
end
%Pathologic case 2 (line1 x=constant)
if ~isfinite(a1) && isfinite(a2)
intersectionPoint(1) = X1(1);
intersectionPoint(2) = intersectionPoint(1)*a2 + b2;
end
if intersectionPoint(1)<min([X1(1) X2(1)]) ||...
intersectionPoint(1)>max([X1(2) X2(2)]) ||...
intersectionPoint(2)<min([Y1(1) Y2(1)]) ||...
intersectionPoint(2)>max([Y1(2) Y2(2)])
intersectionPoint = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: computeSecondaryAxesDefaultPosition
%
% PURPOSE: obtain the default position and size of the secondary axis, relative to the
% lower left corner of the figure, in pixels. Includes legends and axes
% numbering
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the axis frame
% Y of lower left corner of the axis frame
% Width of the axis frame
% Height of the axis frame
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function defaultPosition = computeSecondaryAxesDefaultPosition()
global appDataStruct
if isempty(appDataStruct)
return;
end;
% If image, defualt aspect ratio of magnifier and secondary axes to [1 1]
childHandle = get(appDataStruct.mainAxesHandle, 'Children');
plotFlag = ~isempty( find(strcmpi(get(childHandle, 'Type'), 'line'),1) );
imageFlag = ~isempty( find(strcmpi(get(childHandle, 'Type'), 'image'),1) );
%Get position and size of main Axis (left & bottom relative to figure frame)
mainAxesPosition = getMainAxesPositionInPixels();
if plotFlag
%Set initial position and size for secondary axis
secondaryAxisPosition_W = mainAxesPosition(3)*0.3;
secondaryAxisPosition_H = mainAxesPosition(4)*0.3;
secondaryAxisPosition_X = mainAxesPosition(1)+mainAxesPosition(3)-secondaryAxisPosition_W-10;
secondaryAxisPosition_Y = mainAxesPosition(2)+mainAxesPosition(4)-secondaryAxisPosition_H-10;
else
%Set initial position and size for secondary axis
secondaryAxisPosition_W = mainAxesPosition(3)*0.3;
secondaryAxisPosition_H = mainAxesPosition(4)*0.3;
secondaryAxisPosition_X = mainAxesPosition(1)+mainAxesPosition(3)-secondaryAxisPosition_W-10;
secondaryAxisPosition_Y = mainAxesPosition(2)+mainAxesPosition(4)-secondaryAxisPosition_H-10;
end
defaultPosition = [...
secondaryAxisPosition_X...
secondaryAxisPosition_Y...
secondaryAxisPosition_W...
secondaryAxisPosition_H...
];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: computeMagnifierDefaultPosition
%
% PURPOSE: obtain the default position and size of the magnifier, relative to the
% lower left corner of the figure, in pixels. Includes legends and axes
% numbering
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% position [double 1x4]:
% X of lower left corner of the rectangle
% Y of lower left corner of the rectangle
% Width of the rectangle
% Height of the rectangle
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function defaultPosition = computeMagnifierDefaultPosition()
global appDataStruct
if isempty(appDataStruct)
return;
end;
% If image, defualt aspect ratio of magnifier and secondary axes to [1 1]
childHandle = get(appDataStruct.mainAxesHandle, 'Children');
plotFlag = ~isempty( find(strcmpi(get(childHandle, 'Type'), 'line'),1) );
imageFlag = ~isempty( find(strcmpi(get(childHandle, 'Type'), 'image'),1) );
%Set initial position and size of magnifying rectangle
mainAxisXLim = get( appDataStruct.mainAxesHandle, 'XLim' );
mainAxisYLim = get( appDataStruct.mainAxesHandle, 'YLim' );
mainAxesPositionInPixels = getMainAxesPositionInPixels();
xMainAxisUnits2PixelsFactor = mainAxesPositionInPixels(3)/determineSpan( mainAxisXLim(1), mainAxisXLim(2) );
yMainAxisUnits2PixelsFactor = mainAxesPositionInPixels(4)/determineSpan( mainAxisYLim(1), mainAxisYLim(2) );
if plotFlag
%Get main axis position and dimensions, in pixels
magnifierPosition_W = determineSpan(mainAxisXLim(1), mainAxisXLim(2))*xMainAxisUnits2PixelsFactor*0.1;
magnifierPosition_H = determineSpan(mainAxisYLim(1), mainAxisYLim(2))*yMainAxisUnits2PixelsFactor*0.3;
magnifierPosition_X = determineSpan(mean(mainAxisXLim), mainAxisXLim(1))*xMainAxisUnits2PixelsFactor - magnifierPosition_W/2;
magnifierPosition_Y = determineSpan(mean(mainAxisYLim), mainAxisYLim(1))*yMainAxisUnits2PixelsFactor - magnifierPosition_H/2;
else
%Get main axis position and dimensions, in pixels
magnifierPosition_W = determineSpan(mainAxisXLim(1), mainAxisXLim(2))*xMainAxisUnits2PixelsFactor*0.1;
magnifierPosition_H = determineSpan(mainAxisYLim(1), mainAxisYLim(2))*yMainAxisUnits2PixelsFactor*0.1;
magnifierPosition_X = determineSpan(mean(mainAxisXLim), mainAxisXLim(1))*xMainAxisUnits2PixelsFactor - magnifierPosition_W/2;
magnifierPosition_Y = determineSpan(mean(mainAxisYLim), mainAxisYLim(1))*yMainAxisUnits2PixelsFactor - magnifierPosition_H/2;
end
defaultPosition = [...
magnifierPosition_X+mainAxesPositionInPixels(1)...
magnifierPosition_Y+mainAxesPositionInPixels(2)...
magnifierPosition_W...
magnifierPosition_H...
];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: initializeToolStruct
%
% PURPOSE: Set value for default properties
%
% INPUT ARGUMENTS:
% none
% OUTPUT ARGUMENTS:
% none
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function obj = initializeToolStruct(varargin)
if nargin == 0
obj.toolId = [];
obj.focusOnThisTool = true;
obj.toolIdHandle = [];
%figure
obj.figureHandle = [];
obj.figurePosition = [];
obj.figureOldWindowButtonDownFcn = [];
obj.figureOldWindowButtonUpFcn = [];
obj.figureOldWindowButtonMotionFcn = [];
obj.figureOldKeyPressFcn = [];
obj.figureOldDeleteFcn = [];
obj.figureOldResizeFcn = [];
%main axes
obj.mainAxesHandle = [];
%magnifier
obj.magnifierHandle = [];
obj.magnifierPosition = [];
obj.magnifierShape = 'rectangle';
%link
obj.linkHandle = [];
obj.linkDisplayStyle = 'straight';
%secondary axes
obj.secondaryAxesHandle = [];
obj.secondaryAxesFaceColor = 'white';
obj.secondaryAxesPosition = [];
obj.secondaryAxesXLim = [];
obj.secondaryAxesYLim = [];
obj.secondaryAxesAdditionalZoomingFactor = [0 0];
%global
obj.globalUnits = 'pixels';
obj.globalMode = 'interactive';
obj.globalEdgeWidth = 1;
obj.globalEdgeColor = 'black';
obj.globalZoomMode = 'off';
%Temp
obj.pointerArea = 'none';
obj.ButtonDown = false;
obj.pointerPositionOnButtonDown = [];
end
if nargin == 1 && isstruct(varargin{1})
structIn = varargin{1};
if all(isfield(structIn, {'toolId','focusOnThisTool',...
'figureHandle', 'figurePosition', 'figureOldWindowButtonDownFcn',...
'figureOldWindowButtonUpFcn', 'figureOldWindowButtonMotionFcn',...
'figureOldKeyPressFcn', 'figureOldDeleteFcn', 'figureOldResizeFcn',...
'mainAxesHandle', 'magnifierHandle', 'magnifierPosition', ...
'magnifierShape', 'linkHandle', 'linkDisplayStyle', 'secondaryAxesHandle',...
'secondaryAxesFaceColor', 'secondaryAxesPosition', 'secondaryAxesXLim',...
'secondaryAxesYLim', 'secondaryAxesAdditionalZoomingFactor', ...
'globalUnits', 'globalMode', 'globalEdgeWidth', 'globalEdgeColor',...
'globalZoomMode', 'pointerArea', 'ButtonDown', 'pointerPositionOnButtonDown'}))
else
error('Input structure not recognized');
end
obj = structIn;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NAME: updateToolId
%
% PURPOSE: Updated position and status of tool id
%
% INPUT ARGUMENTS:
% toolArray structure of the tool in focus
% OUTPUT ARGUMENTS:
% none
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function toolArrayOut = updateToolId( toolArrayIn, toolNum, modeStr )
toolArrayOut = toolArrayIn;
set(toolArrayOut.figureHandle, 'currentAxes', toolArrayOut.secondaryAxesHandle);
if strcmp(modeStr, 'toggle')
if isempty(toolArrayOut.toolIdHandle)
xL = get(toolArrayOut.secondaryAxesHandle, 'XLim');
yL = get(toolArrayOut.secondaryAxesHandle, 'YLim');
toolArrayOut.toolIdHandle = text( (xL(2)+xL(1))/2, (yL(2)+yL(1))/2, num2str(toolNum));
set(toolArrayOut.toolIdHandle, 'FontSize', 30, 'FontWeight', 'bold' );
if toolArrayOut.focusOnThisTool
set(toolArrayOut.toolIdHandle,'BackgroundColor', 'red', 'Color', 'white');
else
set(toolArrayOut.toolIdHandle,'BackgroundColor', 'black', 'Color', 'white');
end
else
delete(toolArrayOut.toolIdHandle);
toolArrayOut.toolIdHandle = [];
end
else
if not(isempty(toolArrayOut.toolIdHandle))
xL = get(toolArrayOut.secondaryAxesHandle, 'XLim');
yL = get(toolArrayOut.secondaryAxesHandle, 'YLim');
set(toolArrayOut.toolIdHandle, 'Position', [(xL(2)+xL(1))/2, (yL(2)+yL(1))/2] );
if toolArrayOut.focusOnThisTool
set(toolArrayOut.toolIdHandle,'BackgroundColor', 'red', 'Color', 'white');
else
set(toolArrayOut.toolIdHandle,'BackgroundColor', 'black', 'Color', 'white');
end
end
end
set(toolArrayOut.figureHandle, 'currentAxes', toolArrayOut.mainAxesHandle);
|
github
|
medooze/swig-master
|
member_pointer_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/member_pointer_runme.m
| 922 |
utf_8
|
5d65cb03abdda4efc4dd89ee739e27b6
|
# Example using pointers to member functions
member_pointer
function check(what,expected,actual)
if (expected != actual)
error ("Failed: %s, Expected: %f, Actual: %f",what,expected,actual);
endif
end
# Get the pointers
area_pt = areapt;
perim_pt = perimeterpt;
# Create some objects
s = Square(10);
# Do some calculations
check ("Square area ", 100.0, do_op(s,area_pt));
check ("Square perim", 40.0, do_op(s,perim_pt));
memberPtr = cvar.areavar;
memberPtr = cvar.perimetervar;
# Try the variables
check ("Square area ", 100.0, do_op(s,cvar.areavar));
check ("Square perim", 40.0, do_op(s,cvar.perimetervar));
# Modify one of the variables
cvar.areavar = perim_pt;
check ("Square perimeter", 40.0, do_op(s,cvar.areavar));
# Try the constants
memberPtr = AREAPT;
memberPtr = PERIMPT;
memberPtr = NULLPT;
check ("Square area ", 100.0, do_op(s,AREAPT));
check ("Square perim", 40.0, do_op(s,PERIMPT));
|
github
|
medooze/swig-master
|
director_basic_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/director_basic_runme.m
| 1,778 |
utf_8
|
7cc0b3cfcf243842955e597f2f9889f2
|
director_basic
function self=OctFoo()
global director_basic;
self=subclass(director_basic.Foo());
self.ping=@OctFoo_ping;
end
function string=OctFoo_ping(self)
string="OctFoo::ping()";
end
a = OctFoo();
if (!strcmp(a.ping(),"OctFoo::ping()"))
error(a.ping())
endif
if (!strcmp(a.pong(),"Foo::pong();OctFoo::ping()"))
error(a.pong())
endif
b = director_basic.Foo();
if (!strcmp(b.ping(),"Foo::ping()"))
error(b.ping())
endif
if (!strcmp(b.pong(),"Foo::pong();Foo::ping()"))
error(b.pong())
endif
a = director_basic.A1(1);
if (a.rg(2) != 2)
error("failed");
endif
function self=OctClass()
global director_basic;
self=subclass(director_basic.MyClass());
self.method=@OctClass_method;
self.vmethod=@OctClass_vmethod;
end
function OctClass_method(self,vptr)
self.cmethod = 7;
end
function out=OctClass_vmethod(self,b)
b.x = b.x + 31;
out=b;
end
b = director_basic.Bar(3);
d = director_basic.MyClass();
c = OctClass();
cc = director_basic.MyClass_get_self(c);
dd = director_basic.MyClass_get_self(d);
bc = cc.cmethod(b);
bd = dd.cmethod(b);
cc.method(b);
if (c.cmethod != 7)
error("failed");
endif
if (bc.x != 34)
error("failed");
endif
if (bd.x != 16)
error("failed");
endif
function self=OctMulti()
global director_basic;
self=subclass(director_basic.Foo(),director_basic.MyClass());
self.vmethod=@OctMulti_vmethod;
self.ping=@OctMulti_ping;
end
function out=OctMulti_vmethod(self,b)
b.x = b.x + 31;
out=b;
end
function out=OctMulti_ping(self)
out="OctFoo::ping()";
end
a = 0;
for i=0:100,
octmult = OctMulti();
octmult.pong();
clear octmult
endfor
octmult = OctMulti();
p1 = director_basic.Foo_get_self(octmult);
p2 = director_basic.MyClass_get_self(octmult);
p1.ping();
p2.vmethod(bc);
|
github
|
medooze/swig-master
|
director_string_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/director_string_runme.m
| 566 |
utf_8
|
d0a720bc282afbf1ac33203b567084f3
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
director_string
function out=get_first(self)
out = strcat(self.A.get_first()," world!");
end
function process_text(self,string)
self.A.process_text(string);
self.smem = "hello";
end
B=@(string) subclass(A(string),'get_first',@get_first,'process_text',@process_text);
b = B("hello");
b.get(0);
if (!strcmp(b.get_first(),"hello world!"))
error(b.get_first())
endif
b.call_process_func();
if (!strcmp(b.smem,"hello"))
error(b.smem)
endif
|
github
|
medooze/swig-master
|
overload_null_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/overload_null_runme.m
| 945 |
utf_8
|
96d0d2a599a578a152484af795a6992b
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
overload_null
function check(a, b)
if (a != b)
error("%i does not equal %i", a, b);
endif
end
o = Overload();
x = X();
null = []; # NULL pointer
check(1, o.byval1(x));
check(2, o.byval1(null));
check(3, o.byval2(null));
check(4, o.byval2(x));
check(5, o.byref1(x));
check(6, o.byref1(null));
check(7, o.byref2(null));
check(8, o.byref2(x));
check(9, o.byconstref1(x));
check(10, o.byconstref1(null));
check(11, o.byconstref2(null));
check(12, o.byconstref2(x));
# const pointer references
check(13, o.byval1cpr(x));
check(14, o.byval1cpr(null));
check(15, o.byval2cpr(null));
check(16, o.byval2cpr(x));
# fwd class declaration
check(17, o.byval1fwdptr(x));
check(18, o.byval1fwdptr(null));
check(19, o.byval2fwdptr(null));
check(20, o.byval2fwdptr(x));
check(21, o.byval1fwdref(x));
check(22, o.byval2fwdref(x));
|
github
|
medooze/swig-master
|
li_boost_shared_ptr_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/li_boost_shared_ptr_runme.m
| 15,667 |
utf_8
|
4ba4347214279b5ab96617f27384b547
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
1;
li_boost_shared_ptr;
function verifyValue(expected, got)
if (expected ~= got)
error("verify value failed.");% Expected: ", expected, " Got: ", got)
end
endfunction
function verifyCount(expected, k)
got = use_count(k);
if (expected ~= got)
error("verify use_count failed. Expected: %d Got: %d ", expected, got);
end
endfunction
function runtest()
li_boost_shared_ptr; # KTTODO this needs to be here at present. Global module failure?
# simple shared_ptr usage - created in C++
k = Klass("me oh my");
val = k.getValue();
verifyValue("me oh my", val)
verifyCount(1, k)
# simple shared_ptr usage - not created in C++
k = factorycreate();
val = k.getValue();
verifyValue("factorycreate", val)
verifyCount(1, k)
# pass by shared_ptr
k = Klass("me oh my");
kret = smartpointertest(k);
val = kret.getValue();
verifyValue("me oh my smartpointertest", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by shared_ptr pointer
k = Klass("me oh my");
kret = smartpointerpointertest(k);
val = kret.getValue();
verifyValue("me oh my smartpointerpointertest", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by shared_ptr reference
k = Klass("me oh my");
kret = smartpointerreftest(k);
val = kret.getValue();
verifyValue("me oh my smartpointerreftest", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by shared_ptr pointer reference
k = Klass("me oh my");
kret = smartpointerpointerreftest(k);
val = kret.getValue();
verifyValue("me oh my smartpointerpointerreftest", val)
verifyCount(2, k)
verifyCount(2, kret)
# const pass by shared_ptr
k = Klass("me oh my");
kret = constsmartpointertest(k);
val = kret.getValue();
verifyValue("me oh my", val)
verifyCount(2, k)
verifyCount(2, kret)
# const pass by shared_ptr pointer
k = Klass("me oh my");
kret = constsmartpointerpointertest(k);
val = kret.getValue();
verifyValue("me oh my", val)
verifyCount(2, k)
verifyCount(2, kret)
# const pass by shared_ptr reference
k = Klass("me oh my");
kret = constsmartpointerreftest(k);
val = kret.getValue();
verifyValue("me oh my", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by value
k = Klass("me oh my");
kret = valuetest(k);
val = kret.getValue();
verifyValue("me oh my valuetest", val)
verifyCount(1, k)
verifyCount(1, kret)
# pass by pointer
k = Klass("me oh my");
kret = pointertest(k);
val = kret.getValue();
verifyValue("me oh my pointertest", val)
verifyCount(1, k)
verifyCount(1, kret)
# pass by reference
k = Klass("me oh my");
kret = reftest(k);
val = kret.getValue();
verifyValue("me oh my reftest", val)
verifyCount(1, k)
verifyCount(1, kret)
# pass by pointer reference
k = Klass("me oh my");
kret = pointerreftest(k);
val = kret.getValue();
verifyValue("me oh my pointerreftest", val)
verifyCount(1, k)
verifyCount(1, kret)
# null tests
#KTODO None not defined
# k = None;
# if (smartpointertest(k) ~= None)
# error("return was not null")
# end
# if (smartpointerpointertest(k) ~= None)
# error("return was not null")
# end
# if (smartpointerreftest(k) ~= None)
# error("return was not null")
# end
# if (smartpointerpointerreftest(k) ~= None)
# error("return was not null")
# end
# if (nullsmartpointerpointertest(None) ~= "null pointer")
# error("not null smartpointer pointer")
# end
# # try:
# # valuetest(k)
# # error("Failed to catch null pointer")
# # except ValueError:
# # pass
# if (pointertest(k) ~= None)
# error("return was not null")
# end
# # try:
# # reftest(k)
# # error("Failed to catch null pointer")
# # except ValueError:
# # pass
# $owner
k = pointerownertest();
val = k.getValue();
verifyValue("pointerownertest", val)
verifyCount(1, k)
k = smartpointerpointerownertest();
val = k.getValue();
verifyValue("smartpointerpointerownertest", val)
verifyCount(1, k)
# //////////////////////////////// Derived class ////////////////////////////////////////
# derived pass by shared_ptr
k = KlassDerived("me oh my");
kret = derivedsmartptrtest(k);
val = kret.getValue();
verifyValue("me oh my derivedsmartptrtest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# derived pass by shared_ptr pointer
k = KlassDerived("me oh my");
kret = derivedsmartptrpointertest(k);
val = kret.getValue();
verifyValue("me oh my derivedsmartptrpointertest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# derived pass by shared_ptr ref
k = KlassDerived("me oh my");
kret = derivedsmartptrreftest(k);
val = kret.getValue();
verifyValue("me oh my derivedsmartptrreftest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# derived pass by shared_ptr pointer ref
k = KlassDerived("me oh my");
kret = derivedsmartptrpointerreftest(k);
val = kret.getValue();
verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# derived pass by pointer
k = KlassDerived("me oh my");
kret = derivedpointertest(k);
val = kret.getValue();
verifyValue("me oh my derivedpointertest-Derived", val)
verifyCount(1, k)
verifyCount(1, kret)
# derived pass by ref
k = KlassDerived("me oh my");
kret = derivedreftest(k);
val = kret.getValue();
verifyValue("me oh my derivedreftest-Derived", val)
verifyCount(1, k)
verifyCount(1, kret)
# //////////////////////////////// Derived and base class mixed ////////////////////////////////////////
# pass by shared_ptr (mixed)
k = KlassDerived("me oh my");
kret = smartpointertest(k);
val = kret.getValue();
verifyValue("me oh my smartpointertest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by shared_ptr pointer (mixed)
k = KlassDerived("me oh my");
kret = smartpointerpointertest(k);
val = kret.getValue();
verifyValue("me oh my smartpointerpointertest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by shared_ptr reference (mixed)
k = KlassDerived("me oh my");
kret = smartpointerreftest(k);
val = kret.getValue();
verifyValue("me oh my smartpointerreftest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by shared_ptr pointer reference (mixed)
k = KlassDerived("me oh my");
kret = smartpointerpointerreftest(k);
val = kret.getValue();
verifyValue("me oh my smartpointerpointerreftest-Derived", val)
verifyCount(2, k)
verifyCount(2, kret)
# pass by value (mixed)
k = KlassDerived("me oh my");
kret = valuetest(k);
val = kret.getValue();
verifyValue("me oh my valuetest", val) # note slicing
verifyCount(1, k)
verifyCount(1, kret)
# pass by pointer (mixed)
k = KlassDerived("me oh my");
kret = pointertest(k);
val = kret.getValue();
verifyValue("me oh my pointertest-Derived", val)
verifyCount(1, k)
verifyCount(1, kret)
# pass by ref (mixed)
k = KlassDerived("me oh my");
kret = reftest(k);
val = kret.getValue();
verifyValue("me oh my reftest-Derived", val)
verifyCount(1, k)
verifyCount(1, kret)
# //////////////////////////////// Overloading tests ////////////////////////////////////////
# Base class
k = Klass("me oh my");
verifyValue(overload_rawbyval(k), "rawbyval")
verifyValue(overload_rawbyref(k), "rawbyref")
verifyValue(overload_rawbyptr(k), "rawbyptr")
verifyValue(overload_rawbyptrref(k), "rawbyptrref")
verifyValue(overload_smartbyval(k), "smartbyval")
verifyValue(overload_smartbyref(k), "smartbyref")
verifyValue(overload_smartbyptr(k), "smartbyptr")
verifyValue(overload_smartbyptrref(k), "smartbyptrref")
# Derived class
k = KlassDerived("me oh my");
verifyValue(overload_rawbyval(k), "rawbyval")
verifyValue(overload_rawbyref(k), "rawbyref")
verifyValue(overload_rawbyptr(k), "rawbyptr")
verifyValue(overload_rawbyptrref(k), "rawbyptrref")
verifyValue(overload_smartbyval(k), "smartbyval")
verifyValue(overload_smartbyref(k), "smartbyref")
verifyValue(overload_smartbyptr(k), "smartbyptr")
verifyValue(overload_smartbyptrref(k), "smartbyptrref")
# 3rd derived class
k = Klass3rdDerived("me oh my");
val = k.getValue();
verifyValue("me oh my-3rdDerived", val)
verifyCount(1, k)
val = test3rdupcast(k);
verifyValue("me oh my-3rdDerived", val)
verifyCount(1, k)
# //////////////////////////////// Member variables ////////////////////////////////////////
# smart pointer by value
m = MemberVariables();
k = Klass("smart member value");
m.SmartMemberValue = k;
val = k.getValue();
verifyValue("smart member value", val)
verifyCount(2, k)
kmember = m.SmartMemberValue;
val = kmember.getValue();
verifyValue("smart member value", val)
verifyCount(3, kmember)
verifyCount(3, k)
clear m
verifyCount(2, kmember)
verifyCount(2, k)
# smart pointer by pointer
m = MemberVariables();
k = Klass("smart member pointer");
m.SmartMemberPointer = k;
val = k.getValue();
verifyValue("smart member pointer", val)
verifyCount(1, k)
kmember = m.SmartMemberPointer;
val = kmember.getValue();
verifyValue("smart member pointer", val)
verifyCount(2, kmember)
verifyCount(2, k)
clear m
verifyCount(2, kmember)
verifyCount(2, k)
# smart pointer by reference
m = MemberVariables();
k = Klass("smart member reference");
m.SmartMemberReference = k;
val = k.getValue();
verifyValue("smart member reference", val)
verifyCount(2, k)
kmember = m.SmartMemberReference;
val = kmember.getValue();
verifyValue("smart member reference", val)
verifyCount(3, kmember)
verifyCount(3, k)
# The C++ reference refers to SmartMemberValue...
kmemberVal = m.SmartMemberValue;
val = kmember.getValue();
verifyValue("smart member reference", val)
verifyCount(4, kmemberVal)
verifyCount(4, kmember)
verifyCount(4, k)
clear m
verifyCount(3, kmemberVal)
verifyCount(3, kmember)
verifyCount(3, k)
# plain by value
m = MemberVariables();
k = Klass("plain member value");
m.MemberValue = k;
val = k.getValue();
verifyValue("plain member value", val)
verifyCount(1, k)
kmember = m.MemberValue;
val = kmember.getValue();
verifyValue("plain member value", val)
verifyCount(1, kmember)
verifyCount(1, k)
clear m
verifyCount(1, kmember)
verifyCount(1, k)
# plain by pointer
m = MemberVariables();
k = Klass("plain member pointer");
m.MemberPointer = k;
val = k.getValue();
verifyValue("plain member pointer", val)
verifyCount(1, k)
kmember = m.MemberPointer;
val = kmember.getValue();
verifyValue("plain member pointer", val)
verifyCount(1, kmember)
verifyCount(1, k)
clear m
verifyCount(1, kmember)
verifyCount(1, k)
# plain by reference
m = MemberVariables();
k = Klass("plain member reference");
m.MemberReference = k;
val = k.getValue();
verifyValue("plain member reference", val)
verifyCount(1, k)
kmember = m.MemberReference;
val = kmember.getValue();
verifyValue("plain member reference", val)
verifyCount(1, kmember)
verifyCount(1, k)
clear m
verifyCount(1, kmember)
verifyCount(1, k)
# null member variables
m = MemberVariables();
# shared_ptr by value
k = m.SmartMemberValue;
#KTODO None not defined
# if (k ~= None)
# error("expected null")
# end
# m.SmartMemberValue = None
# k = m.SmartMemberValue
# if (k ~= None)
# error("expected null")
# end
# verifyCount(0, k)
# # plain by value
# # try:
# # m.MemberValue = None
# # error("Failed to catch null pointer")
# # except ValueError:
# # pass
# # ////////////////////////////////// Global variables ////////////////////////////////////////
# # smart pointer
# kglobal = cvar.GlobalSmartValue
# if (kglobal ~= None)
# error("expected null")
# end
k = Klass("smart global value");
cvar.GlobalSmartValue = k;
verifyCount(2, k)
kglobal = cvar.GlobalSmartValue;
val = kglobal.getValue();
verifyValue("smart global value", val)
verifyCount(3, kglobal)
verifyCount(3, k)
verifyValue("smart global value", cvar.GlobalSmartValue.getValue())
#KTTODO cvar.GlobalSmartValue = None
# plain value
k = Klass("global value");
cvar.GlobalValue = k;
verifyCount(1, k)
kglobal = cvar.GlobalValue;
val = kglobal.getValue();
verifyValue("global value", val)
verifyCount(1, kglobal)
verifyCount(1, k)
verifyValue("global value", cvar.GlobalValue.getValue())
# try:
# cvar.GlobalValue = None
# error("Failed to catch null pointer")
# except ValueError:
# pass
# plain pointer
kglobal = cvar.GlobalPointer;
#KTODO if (kglobal ~= None)
#KTODO error("expected null")
#KTODO end
k = Klass("global pointer");
cvar.GlobalPointer = k;
verifyCount(1, k)
kglobal = cvar.GlobalPointer;
val = kglobal.getValue();
verifyValue("global pointer", val)
verifyCount(1, kglobal)
verifyCount(1, k)
#KTODO cvar.GlobalPointer = None
# plain reference
k = Klass("global reference");
cvar.GlobalReference = k;
verifyCount(1, k)
kglobal = cvar.GlobalReference;
val = kglobal.getValue();
verifyValue("global reference", val)
verifyCount(1, kglobal)
verifyCount(1, k)
# try:
# cvar.GlobalReference = None
# error("Failed to catch null pointer")
# except ValueError:
# pass
# ////////////////////////////////// Templates ////////////////////////////////////////
pid = PairIntDouble(10, 20.2);
if (pid.baseVal1 ~= 20 || pid.baseVal2 ~= 40.4)
error("Base values wrong")
end
if (pid.val1 ~= 10 || pid.val2 ~= 20.2)
error("Derived Values wrong")
end
endfunction
debug = false;%true;
if (debug)
fprintf( "Started\n" )
end
cvar.debug_shared = debug;
# Change loop count to run for a long time to monitor memory
loopCount = 1; #5000
for i=0:loopCount
runtest()
end
# Expect 1 instance - the one global variable (GlobalValue)
#KTTODO next fails, possibly because we commented GlobalSmartValue=None
#if (Klass.getTotal_count() ~= 1)
# error("Klass.total_count=%d", Klass.getTotal_count())
#end
wrapper_count = shared_ptr_wrapper_count() ;
#KTTODO next fails as NOT_COUNTING not in octave name space, so we hard-wire it here
#if (wrapper_count ~= NOT_COUNTING)
if (wrapper_count ~= -123456)
# Expect 1 instance - the one global variable (GlobalSmartValue)
if (wrapper_count ~= 1)
error("shared_ptr wrapper count=%s", wrapper_count)
end
end
if (debug)
fprintf( "Finished\n" )
end
|
github
|
medooze/swig-master
|
voidtest_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/voidtest_runme.m
| 632 |
utf_8
|
8328758f24f7f57e3360e2e34ffae9c7
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
voidtest
voidtest.globalfunc();
f = voidtest.Foo();
f.memberfunc();
voidtest.Foo_staticmemberfunc();
function fvoid()
end
try
a = f.memberfunc();
catch
end_try_catch
try
a = fvoid();
catch
end_try_catch
v1 = voidtest.vfunc1(f);
v2 = voidtest.vfunc2(f);
if (swig_this(v1) != swig_this(v2))
error("failed");
endif
v3 = voidtest.vfunc3(v1);
if (swig_this(v3) != swig_this(f))
error("failed");
endif
v4 = voidtest.vfunc1(f);
if (swig_this(v4) != swig_this(v1))
error("failed");
endif
v3.memberfunc();
|
github
|
medooze/swig-master
|
director_detect_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/director_detect_runme.m
| 654 |
utf_8
|
b67110f81021223aa13bcfcf1a6db401
|
director_detect
global MyBar=@(val=2) subclass(director_detect.Bar(),'val',val,@get_value,@get_class,@just_do_it,@clone);
function val=get_value(self)
self.val = self.val + 1;
val = self.val;
end
function ptr=get_class(self)
global director_detect;
self.val = self.val + 1;
ptr=director_detect.A();
end
function just_do_it(self)
self.val = self.val + 1;
end
function ptr=clone(self)
global MyBar;
ptr=MyBar(self.val);
end
b = MyBar();
f = b.baseclass();
v = f.get_value();
a = f.get_class();
f.just_do_it();
c = b.clone();
vc = c.get_value();
if ((v != 3) || (b.val != 5) || (vc != 6))
error("Bad virtual detection")
endif
|
github
|
medooze/swig-master
|
preproc_constants_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/preproc_constants_runme.m
| 533 |
utf_8
|
917a1bdadc03d5ce92d7468e9c4c81b2
|
preproc_constants
assert(CONST_INT1, 10)
assert(CONST_DOUBLE3, 12.3)
assert(CONST_BOOL1, true)
assert(CONST_CHAR, 'x')
assert(CONST_STRING1, "const string")
# Test global constants can be seen within functions
function test_global()
global CONST_INT1
global CONST_DOUBLE3
global CONST_BOOL1
global CONST_CHAR
global CONST_STRING1
assert(CONST_INT1, 10)
assert(CONST_DOUBLE3, 12.3)
assert(CONST_BOOL1, true)
assert(CONST_CHAR, 'x')
assert(CONST_STRING1, "const string")
endfunction
test_global
|
github
|
medooze/swig-master
|
director_classic_runme.m
|
.m
|
swig-master/Examples/test-suite/octave/director_classic_runme.m
| 2,521 |
utf_8
|
34c0a5c2bef2aca0089be422d83e3982
|
# do not dump Octave core
if exist("crash_dumps_octave_core", "builtin")
crash_dumps_octave_core(0);
endif
director_classic
TargetLangPerson=@() subclass(Person(),'id',@(self) "TargetLangPerson");
TargetLangChild=@() subclass(Child(),'id',@(self) "TargetLangChild");
TargetLangGrandChild=@() subclass(GrandChild(),'id',@(self) "TargetLangGrandChild");
# Semis - don't override id() in target language
TargetLangSemiPerson=@() subclass(Person());
TargetLangSemiChild=@() subclass(Child());
TargetLangSemiGrandChild=@() subclass(GrandChild());
# Orphans - don't override id() in C++
TargetLangOrphanPerson=@() subclass(OrphanPerson(),'id',@(self) "TargetLangOrphanPerson");
TargetLangOrphanChild=@() subclass(OrphanChild(),'id',@(self) "TargetLangOrphanChild");
function check(person,expected)
global Caller;
# Normal target language polymorphic call
ret = person.id();
if (ret != expected)
raise ("Failed. Received: " + ret + " Expected: " + expected);
endif
# Polymorphic call from C++
caller = Caller();
caller.setCallback(person);
ret = caller.call();
if (ret != expected)
error ("Failed. Received: " + ret + " Expected: " + expected);
endif
# Polymorphic call of object created in target language and passed to C++ and back again
baseclass = caller.baseClass();
ret = baseclass.id();
if (ret != expected)
error ("Failed. Received: " + ret + " Expected: " + expected);
endif
caller.resetCallback();
end
person = Person();
check(person, "Person");
clear person;
person = Child();
check(person, "Child");
clear person;
person = GrandChild();
check(person, "GrandChild");
clear person;
person = TargetLangPerson();
check(person, "TargetLangPerson");
clear person;
person = TargetLangChild();
check(person, "TargetLangChild");
clear person;
person = TargetLangGrandChild();
check(person, "TargetLangGrandChild");
clear person;
# Semis - don't override id() in target language
person = TargetLangSemiPerson();
check(person, "Person");
clear person;
person = TargetLangSemiChild();
check(person, "Child");
clear person;
person = TargetLangSemiGrandChild();
check(person, "GrandChild");
clear person;
# Orphans - don't override id() in C++
person = OrphanPerson();
check(person, "Person");
clear person;
person = OrphanChild();
check(person, "Child");
clear person;
person = TargetLangOrphanPerson();
check(person, "TargetLangOrphanPerson");
clear person;
person = TargetLangOrphanChild();
check(person, "TargetLangOrphanChild");
clear person;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.