Daniel@0: function varargout = processArgs(userArgs, varargin) Daniel@0: % Process function arguments, allowing args to be passed by Daniel@0: % the user either as name/value pairs, or positionally, or both. Daniel@0: % Daniel@0: % This function also provides optional enforcement of required inputs, and Daniel@0: % optional type checking. Argument names must start with the '-' Daniel@0: % character and not precede any positional arguments. Daniel@0: % Daniel@0: % Matthew Dunham Daniel@0: % University of British Columbia Daniel@0: % Last updated January 14th, 2010 Daniel@0: % Daniel@0: %% USAGE: Daniel@0: % Daniel@0: % [out1,out2,...,outN] = processArgs(userArgs ,... Daniel@0: % '-name1' , default1 ,... Daniel@0: % '-name2' , default2 ,... Daniel@0: % '-nameN' , defaultN ); Daniel@0: % Daniel@0: % The 'userArgs' input is a cell array and in normal usage is simply the Daniel@0: % varargin cell array from the calling function. It contains 0 to N values Daniel@0: % or 0 to N name/value pairs. It may also contain a combination of Daniel@0: % positional and named arguments as long as no named argument precedes a Daniel@0: % positional one. Daniel@0: % Daniel@0: % Note, this function is CASE INSENSITIVE. Daniel@0: % Daniel@0: %% ENFORCING REQUIRED ARGUMENTS Daniel@0: % Daniel@0: % To ensure that certain arguments are passed in, (and error if not), add a Daniel@0: % '*' character to the corresponding name as in Daniel@0: % Daniel@0: % [out1,...] = processArgs(userArgs,'*-name1',default1,... Daniel@0: % Daniel@0: % Daniel@0: % Providing empty values, (e.g. {},[],'') for required arguments also Daniel@0: % errors unless these were explicitly passed as named arguments. Daniel@0: %% TYPE CHECKING Daniel@0: % Daniel@0: % To enforce that the input type, (class) is the same type as the default Daniel@0: % value, add a '+' character to the corresponding name as in Daniel@0: % Daniel@0: % [out1,...] = processArgs(userArgs,'+-name1',default1,... Daniel@0: % Daniel@0: % '+' and '*' can be combined as in Daniel@0: % Daniel@0: % [out1,...] = processArgs(userArgs,'*+-name1',default1,... Daniel@0: % Daniel@0: % or equivalently Daniel@0: % Daniel@0: % [out1,...] = processArgs(userArgs,'+*-name1',default1,... Daniel@0: %% OTHER CONSIDERATIONS Daniel@0: % Daniel@0: % If the user passes in arguments in positional mode, and uses [], {}, or Daniel@0: % '' as place holders, the default values are used in their place. When the Daniel@0: % user passes in values via name/value pairs, this behavior does not Daniel@0: % occur; the explicit value the user specified, (even if [], {}, '') is Daniel@0: % always used. Daniel@0: % Daniel@0: %% ADVANCED Daniel@0: % The programmer must specify the same number of output arguments as Daniel@0: % possible input arguments, OR exactly one output. If exactly one output Daniel@0: % is used, the outputs are all bundled into a single cell array and Daniel@0: % returned with each arg value preceded by its name. This can be useful for Daniel@0: % relaying some or all of the arguments to subsequent functions as is done Daniel@0: % with the extractArgs function. Daniel@0: % Daniel@0: %% DEPENDENCIES Daniel@0: % Daniel@0: % None Daniel@0: % Daniel@0: %% EXAMPLES Daniel@0: % These are all valid usages. Note that here the first and second arguments Daniel@0: % are required and the types of the second and fourth arguments are Daniel@0: % checked. Daniel@0: % Daniel@0: % outerFunction(obj,... Daniel@0: % '-first' , 1 ,... Daniel@0: % '-second' , MvnDist() ,... Daniel@0: % '-third' , 22 ,... Daniel@0: % '-fourth' , 10 ); Daniel@0: % Daniel@0: % outerFunction(obj,'-fourth',3,'-second',MvnDist(),'-first',12); Daniel@0: % outerFunction(obj,1,MvnDist(),3); Daniel@0: % outerFunction(obj,1,MvnDist(),3,[]); Daniel@0: % outerFunction(obj,'-first',1,'-second',DiscreteDist(),'-third',[]); Daniel@0: % outerFunction(obj,1,MvnDist(),'-fourth',10); Daniel@0: % Daniel@0: % Daniel@0: % function [a,b,c,d] = outerFunction(obj,varargin) Daniel@0: % [a,b,c,d] = processArgs(varargin ,... Daniel@0: % '*-first' , [] ,... Daniel@0: % '*+-second' , MvnDist() ,... Daniel@0: % '-third' , 18 ,... Daniel@0: % '+-fourth' , 23 ); Daniel@0: % end Daniel@0: %% CONSTANTS Daniel@0: PREFIX = '-'; % prefix that must precede the names of arguments. Daniel@0: REQ = '*'; % require the argument Daniel@0: TYPE = '+'; % check the type of the arg against the default type Daniel@0: Daniel@0: % set to true for more exhaustive error checking or false for faster Daniel@0: % execution. Daniel@0: FULL_ERROR_CHECK = true; Daniel@0: Daniel@0: %% PROCESS VARARGIN - PASSED BY PROGRAMMER Daniel@0: Daniel@0: %% Check Initial Inputs Daniel@0: if ~iscell(userArgs) ,throwAsCaller(MException('PROCESSARGS:noUserArgs','PROGRAMMER ERROR - you must pass in the user''s arguments in a cell array as in processArgs(varargin,''-name'',val,...)'));end Daniel@0: if isempty(varargin) ,throwAsCaller(MException('PROCESSARGS:emptyVarargin','PROGRAMMER ERROR - you have not passed in any name/default pairs to processArgs')); end Daniel@0: %% Extract Programmer Argument Names and Markers Daniel@0: progArgNames = varargin(1:2:end); Daniel@0: maxNargs = numel(progArgNames); Daniel@0: required = cellfun(@(c)any(REQ==c(1:min(3,end))),progArgNames); Daniel@0: typecheck = cellfun(@(c)any(TYPE==c(1:min(3,end))),progArgNames); Daniel@0: if ~iscellstr(progArgNames) ,throwAsCaller(MException('PROCESSARGS:notCellStr ',sprintf('PROGRAMMER ERROR - you must pass to processArgs name/default pairs'))); end Daniel@0: %% Remove * and + Markers Daniel@0: try Daniel@0: progArgNames(required | typecheck) = ... Daniel@0: cellfuncell(@(c)c(c~=REQ & c~=TYPE) ,... Daniel@0: progArgNames(required | typecheck)); Daniel@0: catch ME Daniel@0: if strcmp(ME.identifier,'MATLAB:UndefinedFunction') Daniel@0: err = MException('PROCESSARGS:missingExternalFunctions','ProcessArgs requires the following external functions available in PMTK2: catString, cellfuncell, interweave, isprefix. Please add these to your MATLAB path.'); Daniel@0: throw(addCause(err,ME)); Daniel@0: else Daniel@0: rethrow(ME); Daniel@0: end Daniel@0: end Daniel@0: %% Set Default Values Daniel@0: defaults = varargin(2:2:end); Daniel@0: varargout = defaults; Daniel@0: %% Check Programmer Supplied Arguments Daniel@0: if mod(numel(varargin),2) ,throwAsCaller(MException('PROCESSARGS:oddNumArgs',sprintf('PROGRAMMER ERROR - you have passed in an odd number of arguments to processArgs, which requires name/default pairs'))); end Daniel@0: if any(cellfun(@isempty,progArgNames)) ,throwAsCaller(MException('PROCESSARGS:emptyStrName ',sprintf('PROGRAMMER ERROR - empty-string names are not allowed')));end Daniel@0: if nargout ~= 1 && nargout ~= maxNargs ,throwAsCaller(MException('PROCESSARGS:wrongNumOutputs',sprintf('PROGRAMMER ERROR - processArgs requires the same number of output arguments as named/default input pairs'))); end Daniel@0: if ~isempty(PREFIX) && ... Daniel@0: ~all(cellfun(@(c)~isempty(c) &&... Daniel@0: c(1)==PREFIX,progArgNames)) Daniel@0: throwAsCaller(MException('PROCESSARGS:missingPrefix',sprintf('PROGRAMMER ERROR - processArgs requires that each argument name begin with the prefix %s',PREFIX))); Daniel@0: end Daniel@0: if FULL_ERROR_CHECK && ... Daniel@0: numel(unique(progArgNames)) ~= numel(progArgNames) ,throwAsCaller(MException('PROCESSARGS:duplicateName',sprintf('PROGRAMMER ERROR - you can not use the same argument name twice')));end Daniel@0: %% PROCESS USERARGS Daniel@0: Daniel@0: %% Error Check User Args Daniel@0: if numel(userArgs) == 0 && nargout > 1 Daniel@0: if any(required) ,throwAsCaller(MException('PROCESSARGS:missingReqArgs',sprintf('The following required arguments were not specified:\n%s',catString(progArgNames(required))))); Daniel@0: else return; Daniel@0: end Daniel@0: end Daniel@0: if FULL_ERROR_CHECK Daniel@0: % slow, but helpful in transition from process_options to processArgs Daniel@0: % checks for missing '-' Daniel@0: if ~isempty(PREFIX) Daniel@0: userstrings = lower(... Daniel@0: userArgs(cellfun(@(c)ischar(c) && size(c,1)==1,userArgs))); Daniel@0: problem = ismember(... Daniel@0: userstrings,cellfuncell(@(c)c(2:end),progArgNames)); Daniel@0: if any(problem) Daniel@0: if sum(problem) == 1, warning('processArgs:missingPrefix','The specified value ''%s'', matches an argument name, except for a missing prefix %s. It will be interpreted as a value, not a name.',userstrings{problem},PREFIX) Daniel@0: else warning('processArgs:missingPrefix','The following values match an argument name, except for missing prefixes %s:\n\n%s\n\nThey will be interpreted as values, not names.',PREFIX,catString(userstrings(problem))); Daniel@0: end Daniel@0: end Daniel@0: end Daniel@0: end Daniel@0: %% Find User Arg Names Daniel@0: userArgNamesNDX = find(cellfun(@(c)ischar(c) &&... Daniel@0: ~isempty(c) &&... Daniel@0: c(1)==PREFIX,userArgs)); Daniel@0: %% Check User Arg Names Daniel@0: if ~isempty(userArgNamesNDX) && ... Daniel@0: ~isequal(userArgNamesNDX,userArgNamesNDX(1):2:numel(userArgs)-1) Daniel@0: if isempty(PREFIX), throwAsCaller(MException('PROCESSARGS:missingVal',sprintf('\n(1) every named argument must be followed by its value\n(2) no positional argument may be used after the first named argument\n'))); Daniel@0: else throwAsCaller(MException('PROCESSARGS:posArgAfterNamedArg',sprintf('\n(1) every named argument must be followed by its value\n(2) no positional argument may be used after the first named argument\n(3) every argument name must begin with the ''%s'' character\n(4) values cannot be strings beginning with the %s character\n',PREFIX,PREFIX))); Daniel@0: end Daniel@0: end Daniel@0: if FULL_ERROR_CHECK && ... Daniel@0: ~isempty(userArgNamesNDX) && ... Daniel@0: numel(unique(userArgs(userArgNamesNDX))) ~= numel(userArgNamesNDX) Daniel@0: throwAsCaller(MException('PROCESSARGS:duplicateUserArg',sprintf('You have specified the same argument name twice'))); Daniel@0: end Daniel@0: %% Extract Positional Args Daniel@0: argsProvided = false(1,maxNargs); Daniel@0: if isempty(userArgNamesNDX) Daniel@0: positionalArgs = userArgs; Daniel@0: elseif userArgNamesNDX(1) == 1 Daniel@0: positionalArgs = {}; Daniel@0: else Daniel@0: positionalArgs = userArgs(1:userArgNamesNDX(1)-1); Daniel@0: end Daniel@0: %% Check For Too Many Inputs Daniel@0: if numel(positionalArgs) + numel(userArgNamesNDX) > maxNargs ,throwAsCaller(MException('PROCESSARGS:tooManyInputs',sprintf('You have specified %d too many arguments to the function',numel(positionalArgs)+numel(userArgNamesNDX)- maxNargs)));end Daniel@0: %% Process Positional Args Daniel@0: for i=1:numel(positionalArgs) Daniel@0: % don't overwrite default value if positional arg is Daniel@0: % empty, i.e. '',{},[] Daniel@0: if ~isempty(userArgs{i}) Daniel@0: argsProvided(i) = true; Daniel@0: if typecheck(i) && ~isa(userArgs{i},class(defaults{i})) ,throwAsCaller(MException('PROCESSARGS:argWrongType',sprintf('Argument %d must be of type %s',i,class(defaults{i})))); end Daniel@0: varargout{i} = userArgs{i}; Daniel@0: end Daniel@0: end Daniel@0: %% Process Named Args Daniel@0: userArgNames = userArgs(userArgNamesNDX); Daniel@0: userProgMap = zeros(1,numel(userArgNames)); Daniel@0: usedProgArgNames = false(1,numel(progArgNames)); Daniel@0: for i=1:numel(userArgNames) Daniel@0: for j=1:numel(progArgNames) Daniel@0: if ~usedProgArgNames(j) && strcmpi(userArgNames{i},progArgNames{j}) Daniel@0: userProgMap(i) = j; Daniel@0: usedProgArgNames(j) = true; Daniel@0: break; Daniel@0: end Daniel@0: end Daniel@0: end Daniel@0: %% Error Check User Args Daniel@0: if any(~userProgMap) ,throwAsCaller(MException('PROCESSARGS:invalidArgNames',sprintf('The following argument names are invalid: %s',catString(userArgNames(userProgMap == 0),' , ')))); end Daniel@0: if any(userProgMap <= numel(positionalArgs)) ,throwAsCaller(MException('PROCESSARGS:bothPosAndName' ,sprintf('You cannot specify an argument positionally, and by name in the same function call.')));end Daniel@0: %% Extract User Values Daniel@0: userValues = userArgs(userArgNamesNDX + 1); Daniel@0: %% Type Check User Args Daniel@0: if any(typecheck) Daniel@0: for i=1:numel(userArgNamesNDX) Daniel@0: if typecheck(userProgMap(i)) && ... Daniel@0: ~isa(userArgs{userArgNamesNDX(i)+1},... Daniel@0: class(defaults{userProgMap(i)})) Daniel@0: throwAsCaller(MException('PROCESSARGS:wrongType',sprintf('Argument %s must be of type %s',userArgs{userArgNamesNDX(i)},class(defaults{userProgMap(i)})))); Daniel@0: end Daniel@0: end Daniel@0: end Daniel@0: varargout(userProgMap) = userValues; Daniel@0: %% Check Required Args Daniel@0: argsProvided(userProgMap) = true; Daniel@0: if any(~argsProvided & required) ,throwAsCaller(MException('PROCESSARGS:emptyVals',sprintf('The following required arguments were either not specified, or were given empty values:\n%s',catString(progArgNames(~argsProvided & required))))); end Daniel@0: %% Relay Mode Daniel@0: if nargout == 1 && (numel(varargin) > 2 || (numel(varargin) == 1 && isprefix('-',varargin{1}))) Daniel@0: varargout = {interweave(progArgNames,varargout)}; Daniel@0: end Daniel@0: Daniel@0: end Daniel@0: Daniel@0: Daniel@0: function s = catString(c,delim) Daniel@0: % Converts a cell array of strings to a single string, (i.e. single-row Daniel@0: % character array). The specified delimiter, delim, is added between each Daniel@0: % entry. Include any spaces you want in delim. If delim is not specified, Daniel@0: % ', ' is used instead. If c is already a string, it is just returned. If c Daniel@0: % is empty, s = ''. Daniel@0: % Daniel@0: % EXAMPLE: Daniel@0: % Daniel@0: % s = catString({'touch /tmp/foo';'touch /tmp foo2';'mkdir /tmp/test'},' && ') Daniel@0: % s = Daniel@0: % touch /tmp/foo && touch /tmp foo2 && mkdir /tmp/test Daniel@0: Daniel@0: if nargin == 0; s = ''; return; end Daniel@0: if ischar(c), s=c; Daniel@0: if strcmp(s,','),s = '';end Daniel@0: return; Daniel@0: end Daniel@0: if isempty(c),s=''; return;end Daniel@0: if nargin < 2, delim = ', '; end Daniel@0: s = ''; Daniel@0: for i=1:numel(c) Daniel@0: s = [s, rowvec(c{i}),rowvec(delim)]; %#ok Daniel@0: end Daniel@0: s(end-numel(delim)+1:end) = []; Daniel@0: if strcmp(s,','),s = '';end Daniel@0: end Daniel@0: Daniel@0: Daniel@0: function out = cellfuncell(fun, C, varargin) Daniel@0: out = cellfun(fun, C, varargin{:},'UniformOutput',false); Daniel@0: end Daniel@0: Daniel@0: function C = interweave(A,B) Daniel@0: % If A, B are two cell arrays of length N1, N2, C is a cell array of length Daniel@0: % N1 + N2 where where C(1) = A(1), C(2) = B(1), C(3) = A(2), C(4) = B(2), ... etc Daniel@0: % Note, C is always a row vector. If one cell array is longer than the Daniel@0: % other the remaining elements of the longer cell array are added to the Daniel@0: % end of C. A and B are first converted to column vectors. Daniel@0: A = A(:); B = B(:); Daniel@0: C = cell(length(A)+length(B),1); Daniel@0: counter = 1; Daniel@0: while true Daniel@0: if ~isempty(A) Daniel@0: C(counter) = A(1); A(1) = []; Daniel@0: counter = counter + 1; Daniel@0: end Daniel@0: if ~isempty(B) Daniel@0: C(counter) = B(1); B(1) = []; Daniel@0: counter = counter + 1; Daniel@0: end Daniel@0: if isempty(A) && isempty(B) Daniel@0: break; Daniel@0: end Daniel@0: end Daniel@0: C = C'; Daniel@0: end Daniel@0: Daniel@0: function p = isprefix(short,long) Daniel@0: % ISPREFIX Tests if the first arg is a prefix of the second. Daniel@0: % The second arg may also be a cell array of strings, in which case, each Daniel@0: % is tested. CASE SENSITIVE! Daniel@0: % Daniel@0: % If the second argument is not a string, p = false, it does not error. Daniel@0: % Daniel@0: % EXAMPLES: Daniel@0: % Daniel@0: % isprefix('foo','foobar') Daniel@0: % ans = Daniel@0: % 1 Daniel@0: % Daniel@0: %isprefix('test_',{'test_MvnDist','test_DiscreteDist','UnitTest'}) Daniel@0: %ans = Daniel@0: % 1 1 0 Daniel@0: error(nargchk(2,2,nargin)); Daniel@0: if ischar(long) Daniel@0: p = strncmp(long,short,length(short)); Daniel@0: elseif iscell(long) Daniel@0: p = cellfun(@(c)isprefix(short,c),long); Daniel@0: else Daniel@0: p = false; Daniel@0: end Daniel@0: end Daniel@0: Daniel@0: Daniel@0: function x = rowvec(x) Daniel@0: x = x(:)'; Daniel@0: end Daniel@0: Daniel@0: function x = colvec(x) Daniel@0: x = x(:); Daniel@0: end Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: Daniel@0: