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
thejihuijin/VideoDilation-master
saveDilatedFrames.m
.m
VideoDilation-master/videoDilation/saveDilatedFrames.m
1,787
utf_8
2a95aa094940d0d029caf2812879e314
% SAVEDILATEDFRAMES saves the frames as designated by the vector of % indices, frameIndices, at a constant framerate. % % INPUTS % vidMat : 3D or 4D video matrix % frameIndices : Vector of indices into vidMat to be played sequentially % fr : Constant framerate at which to play frames % dilated_fr : Variable framerate at which each frame from vidMat is played % outputName : Path to output video % % OUTPUTS % None - saves dilated video function [] = playDilatedFrames( vidMat, frameIndices, fr, dilated_fr, outputName ) % ECE6258: Digital image processing % School of Electrical and Computer Engineering % Georgia Instiute of Technology % Date Modified : 11/28/17 % By Erik Jorgensen ([email protected]), Jihui Jin ([email protected]) % Grab number of frames if length(size(vidMat)) == 4 [~, ~, ~, frames] = size(vidMat); else [~, ~, frames] = size(vidMat); end % Check outputName if ~exist('outputName','var') outputName = 'test.mp4'; end % Catch off-by-one error and correct if frames < frameIndices(end) disp(['Frame index (' num2str(frameIndices(end)) ') greater than '... ' total number of frames (' num2str(frames) ')' ]) frameIndices(end) = frames; disp(['Changed last frame index to ' num2str(frames)]) end % Play video frames sequentially by repeating calls to imagesc outputWriter = VideoWriter(outputName,'MPEG-4'); outputWriter.FrameRate = fr; open(outputWriter); if length(size(vidMat)) == 4 for i = 1:length(frameIndices) writeVideo(outputWriter, vidMat(:,:,:,frameIndices(i))); end else for i = 1:length(frameIndices) writeVideo(outputWriter, vidMat(:,:,frameIndices(i))); end end fprintf('Video saved to %s\n',outputName); end
github
thejihuijin/VideoDilation-master
fr2playback.m
.m
VideoDilation-master/videoDilation/fr2playback.m
2,019
utf_8
4f79daf7cb3e621808fbb58f5b6096a2
% FR2PLAYBACK Takes a variable framerate vector and finds the frames to be % played at a constant framerate that best simulate the variable framerate. % % INPUTS % frameRates : Vector of variable framerate per frame % playback_fr : Constant framerate at which frames will be played % % OUTPUT % playbackFrames : Vector of frame indices into the video matrix to be % played sequentially at a constant FR, simulating a variable FR function playbackFrames = fr2playback( frameRates, playback_fr ) % ECE6258: Digital image processing % School of Electrical and Computer Engineering % Georgia Instiute of Technology % Date Modified : 11/28/17 % By Erik Jorgensen ([email protected]), Jihui Jin ([email protected]) % Delays between consecutive frames at variable framerate dilated_delays = 1 ./ frameRates; % Cumulative time until each frame at variable framerate dilated_times = [0 cumsum(dilated_delays(1:end))]; % Cumulative time until each frame at constant framerate plybk_times = 0 : 1/playback_fr : dilated_times(end); % Find each frame from the variable framerate delays vector that occurs % closest to each frame in the constant framerate delay vector. playbackFrames = zeros(1,length(plybk_times)); frame_ptr = 1; for i = 1:length(plybk_times) min_dist = inf; while 1 if frame_ptr + 1 > length(dilated_times) if frame_ptr > length(playbackFrames) frame_ptr = length(playbackFrames); end playbackFrames(i) = frame_ptr; break end curr_dist = abs( dilated_times(frame_ptr) - plybk_times(i) ); next_dist = abs( dilated_times(frame_ptr + 1) - plybk_times(i) ); if curr_dist < min_dist min_dist = curr_dist; end if next_dist > curr_dist playbackFrames(i) = frame_ptr; break end frame_ptr = frame_ptr + 1; end end end
github
thejihuijin/VideoDilation-master
check_video.m
.m
VideoDilation-master/videoDilation/check_video.m
1,404
utf_8
226375c8ccb6c737cef8b8a496c1f16b
% CHECK_VIDEO Checks the dimension of the input video. The input video must % be divisibl by 'dim', or the saliency algorithm will throw an error. % If the dimensions don't fit the criteria, a resized video is generated % % input_video_path : path to input video % dim : Dimension of video must be divisible by dim % % output_video_path : path to output video meeting size criteria function [output_video_path] = check_video(input_video_path,dim) % ECE6258: Digital image processing % School of Electrical and Computer Engineering % Georgia Instiute of Technology % Date Modified : 11/28/17 % By Erik Jorgensen ([email protected]), Jihui Jin ([email protected]) % Check if video exists if ~exist(input_video_path,'file') fprintf('Video does not exist'); return; end % Read in video inputReader = VideoReader(input_video_path); rows = inputReader.Height; cols = inputReader.Width; % Check size if mod(rows, dim) == 0 && mod(cols, dim) == 0 output_video_path = input_video_path; return; end % Check if resized video exists [filepath, name, ext] = fileparts(input_video_path); output_video_path = strcat(filepath,'/rs_',name,ext); if ~exist(output_video_path,'file') newrows = dim*round(rows/dim); newcols = dim*round(cols/dim); fprintf('Resizing video to [%i %i]\n',newrows,newcols); resize_vid(input_video_path, output_video_path, newrows, newcols); end end
github
thejihuijin/VideoDilation-master
sliceVid.m
.m
VideoDilation-master/videoDilation/sliceVid.m
1,492
utf_8
b880e0a14f35fa703f1079bd010de575
% SLICEVID Convert a video file to a 4D matrix % Assume input video is RGB % Dimensions = (rows, cols, 3, frames) % % INPUTS % filename : String filename % startTime : Time in video to start, in seconds % endTime : Time in video to end, in seconds % ds : Downsampling factor % % OUTPUTS % vidMatrix : 4D matrix of video % fr : framerate at which the video was taken (trunacted to an integer) function [vidMatrix, fr] = sliceVid( filename, startTime, endTime, ds ) % ECE6258: Digital image processing % School of Electrical and Computer Engineering % Georgia Instiute of Technology % Date Modified : 11/28/17 % By Erik Jorgensen ([email protected]), Jihui Jin ([email protected]) v = VideoReader(filename); rows = v.Height; cols = v.Width; fr = v.FrameRate; fr = floor(fr); total_frames = floor(v.Duration) * fr; % Convert start and end times to frame numbers start_frame = floor(startTime*fr)+1; end_frame = floor(endTime*fr); if end_frame > total_frames end_frame = total_frames; end num_frames = end_frame - start_frame; % Downsampled vid size rows_ds = floor(rows/ds); cols_ds = floor(cols/ds); vidMatrix = zeros(rows_ds, cols_ds, 3, num_frames); % Throw away frames before start frame for i = 1:start_frame-1 readFrame(v); end % Read num_frames number of frames from the video for i = 1:num_frames frame = readFrame(v); vidMatrix(:,:,:,i) = im2double(imresize(frame, [rows_ds cols_ds])); end end
github
thejihuijin/VideoDilation-master
smooth_normalize.m
.m
VideoDilation-master/videoDilation/smooth_normalize.m
1,061
utf_8
5734eade58221fbba4e6055711456374
% SMOOTH_NORMALIZE filter and normalize a 1D array between 0 and 1 % % energy : 1D energy function % mov_avg_window : size of moving average window for moving mean filter % mov_med_window : size of window for moving median filter % % smoothed_energy : filtered and normalized energy function % std_dev : standard deviation of unfiltered energy function function [smoothed_energy, std_dev] = smooth_normalize(energy, mov_avg_window,mov_med_window) % ECE6258: Digital image processing % School of Electrical and Computer Engineering % Georgia Instiute of Technology % Date Modified : 11/28/17 % By Erik Jorgensen ([email protected]), Jihui Jin ([email protected]) %SMOOTH_NORMALIZE if ~exist('mov_avg_window','var') mov_avg_window=15; end if ~exist('mov_med_window','var') mov_med_window=5; end std_dev = std(energy); smoothed_energy=movmedian(energy,mov_med_window); smoothed_energy=movmean(smoothed_energy,mov_avg_window); smoothed_energy = smoothed_energy-min(smoothed_energy); smoothed_energy = smoothed_energy/max(smoothed_energy); end
github
happylun/StyleSimilarity-master
randfold.m
.m
StyleSimilarity-master/Learning/randfold.m
1,046
utf_8
f6513a869a9935da136abcbdea59f3ea
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function idx = randfold(n, k) l = randperm(n); p = int16(linspace(0, n, k+1)); for i = 1:k idx(l(p(i)+1:p(i+1))) = i; end end
github
happylun/StyleSimilarity-master
loadArray.m
.m
StyleSimilarity-master/Learning/loadArray.m
1,081
utf_8
b3b0093cdfecd1e2d10256b751510393
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function A = loadArray(name) file = fopen(name); len = fread(file, [1,1], 'int'); A = fread(file, len, 'int'); fclose(file); A = A+1; % convert 0-indexed to 1-indexed
github
happylun/StyleSimilarity-master
sigmoid.m
.m
StyleSimilarity-master/Learning/sigmoid.m
1,022
utf_8
4bff04b1be3597b8f174c4e852fea727
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function s = sigmoid(x) s = 1 ./ (1 + exp(-x)); s = max( s, 1e-6 ); s = min( s, 1-1e-6 ); end
github
happylun/StyleSimilarity-master
loadMatrix.m
.m
StyleSimilarity-master/Learning/loadMatrix.m
1,386
utf_8
dfc0c268e4ca724e78ca597a8230e794
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function M = loadMatrix(name) file = fopen(name); size = fread(file, [2,1], 'int'); M = fread(file, [size(2), size(1)], 'double')'; fclose(file); if nnz(isnan(M))>0 [r,c] = find(isnan(M)); fprintf('\nWarning: NaN in file "%s"\n', name); fprintf('row %d, col %d\n', [r'; c']); end if nnz(isinf(M))>0 [r,c] = find(isinf(M)); fprintf('\nWarning: Inf in file "%s"\n', name); fprintf('row %d, col %d\n', [r'; c']); end M(isnan(M)) = 0; M(isinf(M)) = 0;
github
happylun/StyleSimilarity-master
loadCellArray.m
.m
StyleSimilarity-master/Learning/loadCellArray.m
1,179
utf_8
71efd0a10ef103c422653eb3851d9522
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function C = loadCellArray(name) file = fopen(name); rows = fread(file, [1,1], 'int'); C = cell(rows, 1); for r = 1:rows len = fread(file, [1,1], 'int'); C{r} = fread(file, len, 'int'); C{r} = C{r}+1; % convert 0-indexed to 1-indexed end fclose(file);
github
happylun/StyleSimilarity-master
loadVector.m
.m
StyleSimilarity-master/Learning/loadVector.m
1,338
utf_8
64418f6444a828ee1a5ba1acc228d527
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function V = loadVector(name) file = fopen(name); size = fread(file, [1,1], 'int'); V = fread(file, size, 'double')'; fclose(file); if nnz(isnan(V))>0 i = find(isnan(V)); fprintf('\nWarning: NaN in file "%s"\n', name); fprintf('index %d\n', i); end if nnz(isinf(V))>0 i = find(isinf(V)); fprintf('\nWarning: Inf in file "%s"\n', name); fprintf('index %d\n', i); end V(isnan(V)) = 0; V(isinf(V)) = 0;
github
happylun/StyleSimilarity-master
sliceTriplets.m
.m
StyleSimilarity-master/Learning/sliceTriplets.m
1,059
utf_8
7251bea7579ce7d421b343f50e6b14fb
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function slice = sliceTriplets( n, k ) slice = cell(k, 1); p = 1; for i = 1:k q = floor(i*n/k); slice{i} = p:q; p = q+1; end end
github
happylun/StyleSimilarity-master
slice2flags.m
.m
StyleSimilarity-master/Learning/slice2flags.m
1,096
utf_8
ef9453c6d21abbccb04c8bdfc6253c12
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function flags = slice2flags( slice, len ) flags = zeros(max(1,size(slice,1)), len); for k = 1:size(slice,1) flags(k,slice{k}) = flags(k,slice{k}) + 1; end end
github
happylun/StyleSimilarity-master
MAPObjective.m
.m
StyleSimilarity-master/Learning/MAPObjective.m
2,439
utf_8
4a6499879dd7d7739b756000811a08dc
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function [E, G] = MAPObjective( X, data, trainSet, lambda, param ) % X: weights to be learned (dimX * 1) % data: learning data (triplets, distances, saliencies, ...) % trainSet: triplets slice for training set % lambda: regularization weight % param: global parameters [distance, gradient] = computeDistance(data, X, trainSet, param); confidence = data.tw(:, 1:2); % # of triplets * 2 % swap B and C if answer is C swapIndex = data.ta == 2; distance(swapIndex, :) = distance(swapIndex, [2 1]); gradient(:, swapIndex, :) = gradient(:, swapIndex, [2 1]); confidence(swapIndex, :) = confidence(swapIndex, [2 1]); % L1 regularization R = abs(X)'*lambda; dRdX = sign(X) .* lambda; % L2 regularization %R = (X.^2)'*lambda; %dRdX = X .* lambda * 2; deltaCost = distance(trainSet, 2) - distance(trainSet, 1); % # of triplets * 1 deltaGradient = gradient(:, trainSet, 2) - gradient(:, trainSet, 1); % dimX * # of triplets confidence = confidence(trainSet, :); pBC = sigmoid(deltaCost); pCB = 1 - pBC; E = confidence(:,1)' * ( -log(pBC) ) + confidence(:,2)' * ( -log(pCB) ) + R; G = deltaGradient * (confidence(:,1).*(pBC-1) + confidence(:,2).*pBC) + dRdX; %{ pX = -deltaCost; pY = -log(1./(1+exp(pX))); figure(1); scatter(pX, pY, '.'); line([0, 0], [0, 1.5], 'LineStyle', '--', 'Color', 'red'); axis([-1.5, 1.5, 0, 1.5]); fprintf('%d\t', nnz(pX<0)); %} end
github
happylun/StyleSimilarity-master
computeDistance.m
.m
StyleSimilarity-master/Learning/computeDistance.m
6,784
utf_8
149c5e119e4e207dbf6bb653e569432e
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function [distance, gradient] = computeDistance( data, weights, tripletSlice, param ) % distance: # of triplets * 2 % gradient: total weights dimension (dimX) * # of triplets * 2 numShapes = size(data.s, 1); numTriplets = size(data.ti, 1); dimPD = size(data.pd{1,1},2); dimSD = size(data.sd{1,1},2); dimS = size(data.s{1,1},2); dimX = dimSD + dimS + 3; Wpd = weights(1:dimPD); Wsd = weights(1:dimSD); Ws = weights(dimSD+1:dimSD+dimS); Wu = weights(dimSD+dimS+1); Wdb = weights(dimSD+dimS+2); Wsb = weights(dimSD+dimS+3); % compute saliencies & gradients on points pointS = cell(numShapes, 1); % # of points * 1 gPointS = cell(numShapes, 1); % # of points * dimS+1 shapeS = cell(numShapes, 1); % 1 * 1 gShapeS = cell(numShapes, 1); % 1 * dimS+1 for k = 1:numShapes if ~param.skipSaliencyTerm if ~param.useSigmoidsSaliency pointS{k} = data.s{k}*Ws; gPointS{k} = [data.s{k} zeros(size(data.s{k},1),1)]; else pointS{k} = sigmoid( data.s{k}*Ws + Wsb ); gPointS{k} = bsxfun(@times, [data.s{k} ones(size(data.s{k},1),1)], pointS{k}.*(1-pointS{k})); end else pointS{k} = ones(size(data.s{k},1),1); gPointS{k} = zeros(size(data.s{k},1), dimS+1); end shapeS{k} = sum(pointS{k}); gShapeS{k} = sum(gPointS{k}, 1); end % compute distances & gradients on patches distance = zeros(numTriplets, 2); gradient = zeros(dimX, numTriplets, 2); for k = tripletSlice(:)' for j = 1:2 %%%% distance %%%% if ~param.useSigmoidsDistance patchD = data.pd{k,j}*Wpd; % # of elements * 1 gPatchD = [data.pd{k,j} zeros(size(data.pd{k,j},1))]; % # of elements * dimPD+1 shapeD = data.sd{k,j}*Wsd; % 1 * 1 gShapeD = [data.sd{k,j} 0]; % 1 * dimSD+1 else patchD = sigmoid( (data.pd{k,j}*Wpd + Wdb) ); % # of elements * 1 gPatchD = bsxfun(@times, [data.pd{k,j} ones(size(data.pd{k,j},1))], patchD.*(1-patchD)); % # of elements * dimPD+1 shapeD = sigmoid( (data.sd{k,j}*Wsd + Wdb) ); % 1 * 1 gShapeD = shapeD * (1-shapeD) * [data.sd{k,j} 1]; % 1 * dimSD+1 end %%%% saliency %%%% % slice data ss = pointS{data.ti(k,1)}; % point saliencies of first shape (A) st = pointS{data.ti(k,1+j)}; % point saliencies of second shape (B or C) zs = shapeS{data.ti(k,1)}; % shape saliency zt = shapeS{data.ti(k,1+j)}; gss = gPointS{data.ti(k,1)}; % gradients of terms above gst = gPointS{data.ti(k,1+j)}; gzs = gShapeS{data.ti(k,1)}; gzt = gShapeS{data.ti(k,1+j)}; ms = max(1, data.ms{k,j}); % 1 * # of points mt = max(1, data.mt{k,j}); % compute saliency ss = ss ./ ms'; % normalize by # of elements (unchanged for unmatched points) st = st ./ mt'; nss = ss / zs; % normalized point saliency: # of points * 1 nst = st / zt; patchS = ( data.as{k,j}*nss + data.at{k,j}*nst ) / 2; % # of elements * 1 unmatchS = ( data.us{k,j}*nss + data.ut{k,j}*nst ) / 2; % 1 * 1 % compute gradient of saliency pds = patchD'*data.as{k,j}; % pre-compute this term first: 1 * # of points pdt = patchD'*data.at{k,j}; gms = (pds./ms)*gss / zs - pds*ss*gzs / (zs*zs); % 1 * dimS+1 gmt = (pdt./mt)*gst / zt - pdt*st*gzt / (zt*zt); gMatchS = ( gms + gmt ) / 2; % 1 * dimS(+1) gus = (data.us{k,j}./ms)*gss / zs - data.us{k,j}*ss*gzs / (zs*zs); % 1 * dimS+1 gut = (data.ut{k,j}./mt)*gst / zt - data.ut{k,j}*st*gzt / (zt*zt); gUnmatchS = ( gus + gut ) / 2; % 1 * dimS+1 %%%% put everything together %%%% dMatch = 0; if ~param.skipGlobalDistance dMatch = dMatch + shapeD; end if ~param.skipElementDistance dMatch = dMatch + patchS'*patchD; end dUnmatch = Wu * unmatchS; dAll = 0; if ~param.skipMatchedTerm dAll = dAll + dMatch; end if ~param.skipUnmatchedTerm dAll = dAll + dUnmatch; end distance(k, j) = dAll; if ~param.skipMatchedTerm gWpd = patchS'*gPatchD; % 1 * dimPD+1 gWsd = gShapeD; % 1 * dimSD+1 gWd = zeros(1, dimSD+1); if ~param.skipGlobalDistance gWd = gWd + gWsd; end if ~param.skipElementDistance gWd = gWd + [gWpd(1:dimPD) zeros(1, dimSD-dimPD) gWpd(end)]; end else gWd = zeros(1, dimSD+1); gMatchS = zeros(1, dimS+1); end if ~param.skipUnmatchedTerm gWu = unmatchS; % 1 * 1 else gUnmatchS = zeros(1, dimS+1); gWu = 0; end gWs = gMatchS + Wu*gUnmatchS; % 1 * dimS+1 gAll = zeros(dimX, 1); gAll(1:dimSD) = gWd(1:dimSD)'; gAll(dimSD+1:dimSD+dimS) = gWs(1:dimS)'; gAll(dimSD+dimS+1) = gWu; gAll(dimSD+dimS+2) = gWd(end); gAll(dimSD+dimS+3) = gWs(end); gradient(:,k,j) = gAll; end end end
github
happylun/StyleSimilarity-master
LMNNObjective.m
.m
StyleSimilarity-master/Learning/LMNNObjective.m
2,520
utf_8
72546b7bf7d2afc9b94493ec2a97e5be
%========================================================================= % % This file is part of the Style Similarity project. % % Copyright (c) 2015 - Zhaoliang Lun (author of the code) / UMass-Amherst % % This 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 software is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this software. If not, see <http://www.gnu.org/licenses/>. % %========================================================================= function [E, G] = LMNNObjective( X, data, trainSet, lambda, param ) % X: weights to be learned (dimX * 1) % data: learning data (triplets, distances, saliencies, ...) % trainSet: triplets slice for training set % lambda: regularization weight % param: global parameters % params mu = 1.0; [distance, gradient] = computeDistance(data, X, trainSet, param); % swap B and C if answer is C swapIndex = data.ta == 2; distance(swapIndex, :) = distance(swapIndex, [2 1]); gradient(:, swapIndex, :) = gradient(:, swapIndex, [2 1]); % L1 regularization R = abs(X)'*lambda; dRdX = sign(X) .* lambda; costAB = distance(trainSet,1); % # of triplets * 1 costAC = distance(trainSet,2); % # of triplets * 1 gradientAB = gradient(:, trainSet, 1); % dimX * # of triplets gradientAC = gradient(:, trainSet, 2); % dimX * # of triplets confidence = data.tw(trainSet); N = ( 1+costAB-costAC >= 0 ); % triplets which trigger the hinge lost E = (1-mu) * confidence' * costAB + mu * confidence' * max(0, 1+costAB-costAC) + R; G = (1-mu) * gradientAB * confidence + mu * (gradientAB(:,N)-gradientAC(:,N)) * confidence(N) + dRdX; %{ pX = costAB - costAC; pY = max(0, 1+pX); figure(1); scatter(pX, pY, '.'); line([0, 0], [0, 4], 'LineStyle', '--', 'Color', 'red'); axis([-4, 4, 0, 4]); fprintf('%d\t', nnz(N)); %} %{ figure(1); clf; plot(costAB, 'g'); hold on; plot(costAC, 'r'); axis([0, 140, 0, 6]); fprintf('%d\t', nnz(N)); %} end
github
mathieubray/Tensor-master
parCube.m
.m
Tensor-master/reference/parCube/v2.0/parCube.m
2,826
utf_8
d520d484f6214569ff0345721963f46f
%Vagelis Papalexakis, 2012 %School of Computer Science, Carnegie Mellon University %Implementation of ParCube Non-negative PARAFAC decomposition for %memory-resident tensors function [A B C lambda] = parCube(X,F,sample_factor,times,nonneg) if nargin == 4 nonneg = 0; end mypath = pwd; p = 0.55; s = size(X); I = s(1); J = s(2); K = s(3); A = sparse(I,F); B = sparse(J,F);C = sparse(K,F); for i = 1:times if i == 1 [Xs idx_i idx_j idx_k] = parCube_core(X,sample_factor); fixed_i = idx_i(1:ceil(p*length(idx_i))); fixed_j = idx_j(1:ceil(p*length(idx_j))); fixed_k = idx_k(1:ceil(p*length(idx_k))); fixed{1} = fixed_i; fixed{2} = fixed_j; fixed{3}=fixed_k; else [Xs idx_i idx_j idx_k] = parCube_core(X,sample_factor,fixed); end if nnz(Xs)>0 if nonneg factors = cp_nmu(Xs,F); else factors = cp_als(Xs,F); end As=sparse(factors.U{1});Bs=sparse(factors.U{2});Cs=sparse(factors.U{3});%lambda = factors.lambda;As = As*diag(lambda); lambda(:,i) = factors.lambda; As = As*diag(lambda(:,i).^(1/3)); Bs = Bs*diag(lambda(:,i).^(1/3)); Cs = Cs*diag(lambda(:,i).^(1/3)); else As = 0; Bs = 0; Cs = 0; end Atemp = sparse(I,F); Btemp = sparse(J,F);Ctemp = sparse(K,F); Atemp(idx_i,:) = As; Btemp(idx_j,:) = Bs; Ctemp(idx_k,:) = Cs; %now, normalize the common part of every column for f = 1:F norm_a = norm(Atemp(fixed_i,f),2);Atemp(:,f) = Atemp(:,f)/norm_a; lambda(f,i) = norm_a; norm_b = norm(Btemp(fixed_j,f),2);Btemp(:,f) = Btemp(:,f)/norm_b; lambda(f,i) = lambda(f,i)*norm_b; norm_c = norm(Ctemp(fixed_k,f),2);Ctemp(:,f) = Ctemp(:,f)/norm_c; lambda(f,i) = lambda(f,i)*norm_c; end %Do the merge if i ==1 A = Atemp; B = Btemp; C = Ctemp; else valA=zeros(F,1);valB=zeros(F,1);valC=zeros(F,1); for f1 = 1:F for f2 = 1:F valA(f2) = Atemp(fixed_i,f1)'* A(fixed_i,f2); valB(f2) = Btemp(fixed_j,f1)'* B(fixed_j,f2); valC(f2) = Ctemp(fixed_k,f1)'* C(fixed_k,f2); end [junk idx] = max(valA); mask2 = find(A(:,idx)==0); A(mask2,idx) = A(mask2,idx) + Atemp(mask2,f1);%Update ONLY the zero values [junk idx] = max(valB); mask2 = find(B(:,idx)==0); B(mask2,idx) = B(mask2,idx) + Btemp(mask2,f1);%Update ONLY the zero values [junk idx] = max(valC); mask2 = find(C(:,idx)==0); C(mask2,idx) = C(mask2,idx) + Ctemp(mask2,f1);%Update ONLY the zero values end end end lambda = mean(lambda,2); A = sparse(A*diag(lambda)); A(A<10^-8) = 0; B(B<10^-8) = 0; C(C<10^-8) = 0;
github
mathieubray/Tensor-master
parCube_core.m
.m
Tensor-master/reference/parCube/v2.0/parCube_core.m
1,344
utf_8
4a710d302a7a04cbbaad2fa885c81692
%Vagelis Papalexakis, 2012 %School of Computer Science, Carnegie Mellon University %Core sampling function for the ParCube algorithm, for memory resident %tensors. function [Xs idx_i idx_j idx_k Xma Xmb Xmc] = parCube_core(X,sample_factor,fixed_set) if numel(sample_factor)>1 s1 = sample_factor(1); s2 = sample_factor(2); s3 = sample_factor(3); else s1 = sample_factor; s2 = sample_factor; s3 = sample_factor; end if nargin == 3 fixed_i = fixed_set{1}; fixed_j = fixed_set{2}; fixed_k = fixed_set{3}; else fixed_i = []; fixed_j = []; fixed_k = []; end negative_values = find(X<0); if ~isempty(negative_values) X_abs = double(X); X_abs = abs(X_abs); X_abs = sptensor(X_abs); else X_abs = X; end s = size(X); I = s(1); J = s(2); K = s(3); Xma = collapse(X_abs,[2 3]); Xmb = collapse(X_abs,[1 3]); Xmc = collapse(X_abs,[1 2]); idx_i = find(Xma~=0); idx_i = randsample_weighted(idx_i,I/s1,full(Xma(idx_i))); if ~isempty(fixed_i) idx_i = union(idx_i,fixed_i); end idx_j = find(Xmb~=0); idx_j = randsample_weighted(idx_j,J/s2,full(Xmb(idx_j))); if ~isempty(fixed_j) idx_j = union(idx_j,fixed_j); end idx_k = find(Xmc~=0); idx_k = randsample_weighted(idx_k,K/s3,full(Xmc(idx_k))); if ~isempty(fixed_k) idx_k = union(idx_k,fixed_k); end Xs = X(idx_i,idx_j,idx_k);
github
mathieubray/Tensor-master
efficient_corcondia_kl.m
.m
Tensor-master/reference/AutoTen/v1.0/efficient_corcondia_kl.m
2,612
utf_8
464cef7ce959c0bf1d0853906795c199
function [c,time] = efficient_corcondia_kl(X,Fac) %Vagelis Papalexakis - Carnegie Mellon University, School of Computer %Science (2014-2015) s = size(X); I = s(1); J = s(2); K = s(3); C = Fac.U{3}; B = Fac.U{2}; A = Fac.U{1}; A = A*diag(Fac.lambda); F = size(A,2); tic Z2 = reshape(X,[I*J*K 1]);%Z2 is x disp('Computed Z2') vecG = regression_kl_efficient(Z2,A,B,C); disp('Computed vecG') G = sptensor(reshape(sptensor(vecG), [F F F])); disp('Computed G') T = sptensor([F F F]); for i = 1:F; T(i,i,i) =1; end c = 100* (1 - sum(sum(sum(double(G-T).^2)))/F); time = toc; end function x = regression_kl_efficient(y,A,B,C) im_iter = 30; %iterations for the iterative majorization x = tenrand([size(A,2) size(B,2) size(C,2)]); if (size(A,2) == 1) %rank one is more expensive because kron_mat_vec requires in that case the "full" version y_approx = kron_mat_vec({full(A) full(B) full(C)},x); else y_approx = kron_mat_vec({A B C},x); end y_approx = sparse(double(reshape(y_approx,size(y)))); x = reshape(x, [size(A,2)*size(B,2)*size(C,2) 1]); % norm_const = kron_mat_vec({A' B' C'},reshape(tensor(ones(size(y))), [size(A,1) size(B,1) size(C,1)] )); % norm_const = double(reshape(norm_const,[1 size(A,2)*size(B,2)*size(C,2)])); norm_const = kron(kron(sum(A,1),sum(B,1)),sum(C,1)); normalization = repmat(norm_const',1,size(y,2)); for it = 1:im_iter part1 = sptensor(double(y)./double(y_approx + eps)); if(size(A,2) == 1) %rank one is more expensive because kron_mat_vec requires in that case the "full" version part2 = kron_mat_vec({full(A') full(B') full(C')},reshape(part1,[size(A,1) size(B,1) size(C,1)]));%kron(A,B,C)' * part1 else part2 = kron_mat_vec({A' B' C'},reshape(part1,[size(A,1) size(B,1) size(C,1)])); end % part2 = tensor(reshape(part2,size(x)));%this might not be sparse actually part2 = reshape(part2,size(x));%this might not be sparse actually x = x .* part2; if(size(A,2) == 1)%rank one is more expensive because kron_mat_vec requires in that case the "full" version y_approx = kron_mat_vec({full(A) full(B) full(C)},reshape(x,[size(A,2) size(B,2) size(C,2)])); else y_approx = kron_mat_vec({A B C},reshape(x,[size(A,2) size(B,2) size(C,2)])); end y_approx = sptensor(reshape(y_approx,size(y)));%this is usually indeed sparse disp(sprintf('Iterative Majorization iter %d',it)) end x = x./normalization; end function C = kron_mat_vec(Alist,X) K = length(Alist); for k = K:-1:1 A = Alist{k}; Y = ttm(X,A,k); X = Y; X = permute(X,[3 2 1]); end C = Y; end
github
mathieubray/Tensor-master
AutoTen.m
.m
Tensor-master/reference/AutoTen/v1.0/AutoTen.m
2,286
utf_8
179098e6512684b7e951cc3e73622c12
function [Fac, c, F_est,loss] = AutoTen(X,Fmax,strategy) %Vagelis Papalexakis - Carnegie Mellon University, School of Computer %Science (2015-2016) %strategy = 1--> choose the loss that gives maximum c, among the "best" %points %strategy = 2--> choose the loss that gives maximum F, among the "best" %points allF = 2:Fmax; all_Fac_fro = {}; all_Fac_kl = {}; thresh = 20; all_c_fro = zeros(length(allF),1); all_c_kl = zeros(length(allF),1); for f = allF Fac_fro = cp_als(X,f,'tol',10^-6,'maxiters',10^2); c_fro = efficient_corcondia(X,Fac_fro); all_c_fro(find(f == allF)) = c_fro; all_Fac_fro{find(f == allF)} = Fac_fro; Fac_kl = cp_apr(X,f); c_kl = efficient_corcondia_kl(X,Fac_kl); all_c_kl(find(f == allF)) = c_kl; all_Fac_kl{find(f == allF)} = Fac_kl; end all_c_fro(all_c_fro<thresh) = 0; all_c_kl(all_c_kl<thresh) = 0; % figure;bar(allF,all_c_fro); % figure;bar(allF,all_c_kl); [F_fro, c_fro] = multi_objective_optim(allF,all_c_fro); [F_kl, c_kl] = multi_objective_optim(allF,all_c_kl); %force change the strategy, if either one of the "c" is zero if(c_fro == 0 || c_kl == 0) strategy = 1; end if(strategy == 1) [c, ~] = max([c_fro c_kl]);%%%%% [~,max_idx] = max([sum(all_c_fro) sum(all_c_kl)]);%this gives us confidence on which one has better estimates else [F_est, max_idx] = max([F_fro F_kl]); end if(max_idx == 1)%Fro is better Fac = all_Fac_fro{find(F_fro == allF)}; best_c = all_c_fro; loss = 'fro'; else %KL is better Fac = all_Fac_kl{find(F_kl == allF)}; best_c = all_c_kl; loss = 'kl'; end if(strategy == 1) F_est = size(Fac.U{1},2); else c = best_c(find(F_est == allF)); end end function [x_best, y_best] = multi_objective_optim(x,y) %clustering heuristic method try clusters = kmeans(y,2,'Distance','cityblock'); catch %if an error is thrown, then an empty cluster is formed, so then we just assign all elements to cluster 1 disp('Empty cluster!!') clusters = ones(size(y)); clusters(y>0)=2; end cent1 = mean(y(clusters == 1)); cent2 = mean(y(clusters == 2)); [maxval, cent_idx] = max([cent1 cent2]); x_to_choose = x(clusters == cent_idx); [x_best,x_idx] = max(x_to_choose); y_best = y(x == x_best); end
github
mathieubray/Tensor-master
efficient_corcondia.m
.m
Tensor-master/reference/AutoTen/v1.0/efficient_corcondia.m
1,746
utf_8
4c95c716a9d7cd229809965a4bf607d0
function [c,time] = efficient_corcondia(X,Fac,sparse_flag) %Vagelis Papalexakis - Carnegie Mellon University, School of Computer %Science (2014) %This is an efficient algorithm for computing the CORCONDIA diagnostic for %the PARAFAC decomposition (Bro and Kiers, "A new %efficient method for determining the number of components in PARAFAC %models", Journal of Chemometrics, 2003) %This algorithm is an implementation of the algorithm introduced in % E.E. Papalexakis and C. Faloutsos, % ?Fast efficient and scalable core consistency diagnostic for the parafac decomposition for big sparse tensors,? % in IEEE ICASSP 2015 if nargin == 2 sparse_flag = 2; end C = Fac.U{3}; B = Fac.U{2}; A = Fac.U{1}; A = A*diag(Fac.lambda); if sparse_flag A = sparse(A); end F = size(A,2); tic try if(sparse_flag) [Ua Sa Va] = svds(A,F);disp('Calculated SVD of A'); [Ub Sb Vb] = svds(B,F);disp('Calculated SVD of B'); [Uc Sc Vc] = svds(C,F);disp('Calculated SVD of C'); else [Ua Sa Va] = svd(A,'econ');disp('Calculated SVD of A'); [Ub Sb Vb] = svd(B,'econ');disp('Calculated SVD of B'); [Uc Sc Vc] = svd(C,'econ');disp('Calculated SVD of C'); end catch exception warning('Factors are really bad! Returning zero'); c = 0; return; end part1 = kron_mat_vec({Ua' Ub' Uc'},X); part2 = kron_mat_vec({pinv(Sa) pinv(Sb) pinv(Sc)},part1); G = kron_mat_vec({Va Vb Vc},part2);disp('Computed G'); T = sptensor([F F F]); for i = 1:F; T(i,i,i) =1; end c = 100* (1 - sum(sum(sum(double(G-T).^2)))/F); time = toc; end function C = kron_mat_vec(Alist,X) K = length(Alist); for k = K:-1:1 A = Alist{k}; Y = ttm(X,A,k); X = Y; X = permute(X,[3 2 1]); end C = Y; end
github
mathieubray/Tensor-master
generateData.m
.m
Tensor-master/reference/onlineCP/onlineCP/generateData.m
962
utf_8
cd038997acc8745910c5476b9940500b
%% Shuo Zhou, Xuan Vinh Nguyen, James Bailey, Yunzhe Jia, Ian Davidson, % "Accelerating Online CP Decompositions for Higher Order Tensors", % (C) 2016 Shuo Zhou % Email: [email protected] % To run the code, Tensor Toolbox is required. % Brett W. Bader, Tamara G. Kolda and others. MATLAB Tensor Toolbox % Version 2.6, Available online, February 2015. % URL: http://www.sandia.gov/~tgkolda/TensorToolbox/ %% Generate a data tensor % input: I, a vector contains the dimensionality of the data tensor % R, rank of data tensor % SNR, Noise level in dB, inf for noiseless tensor % ouputs: X, the output data tensor function [ X ] = generateData( I, R, SNR ) if ~exist('SNR') SNR = 30; end A = arrayfun(@(x) randn(x, R), I, 'uni', 0); X = ktensor(A(:)); % add noise normX = norm(X); if ~isinf(SNR) noise = randn(I); sigma = (10^(-SNR/20))*(norm(X))/norm(tensor(noise)); X = double(full(X))+sigma*noise; end end
github
mathieubray/Tensor-master
getKhatriRaoList.m
.m
Tensor-master/reference/onlineCP/onlineCP/getKhatriRaoList.m
1,037
utf_8
9379fd931f636060ed8711934cfa3cd9
%% Shuo Zhou, Xuan Vinh Nguyen, James Bailey, Yunzhe Jia, Ian Davidson, % "Accelerating Online CP Decompositions for Higher Order Tensors", % (C) 2016 Shuo Zhou % Email: [email protected] % To run the code, Tensor Toolbox is required. % Brett W. Bader, Tamara G. Kolda and others. MATLAB Tensor Toolbox % Version 2.6, Available online, February 2015. % URL: http://www.sandia.gov/~tgkolda/TensorToolbox/ %% Get a list of Khatri-Rao products % input: As, a cell array contains N-1 matrices, {A(1), A(2), ..., A(N-1)} % ouputs: Ks, a list of khatri-rao products, the i-th elment of it is % khatriRao(A(N), ..., A(i+1), A(i-1), ..., A(1)) function [ Ks ] = getKhatriRaoList( As ) N = length(As)+1; lefts = {As{N-1}}; rights = {As{1}}; if N>3 for n=2:N-2 lefts{n} = khatrirao(lefts{n-1}, As{N-n}); rights{n} = khatrirao(As{n}, rights{n-1}); end end Ks{1} = lefts{N-2}; Ks{N-1} = rights{N-2}; if N>3 for n=2:N-2 Ks{n} = khatrirao(lefts{N-n-1}, rights{n-1}); end end end
github
mathieubray/Tensor-master
getHadamard.m
.m
Tensor-master/reference/onlineCP/onlineCP/getHadamard.m
772
utf_8
764d87900b7d60b67b055a78434e615d
%% Shuo Zhou, Xuan Vinh Nguyen, James Bailey, Yunzhe Jia, Ian Davidson, % "Accelerating Online CP Decompositions for Higher Order Tensors", % (C) 2016 Shuo Zhou % Email: [email protected] % To run the code, Tensor Toolbox is required. % Brett W. Bader, Tamara G. Kolda and others. MATLAB Tensor Toolbox % Version 2.6, Available online, February 2015. % URL: http://www.sandia.gov/~tgkolda/TensorToolbox/ %% calculate the Hadamard product of a list of matrices % input: As, a cell array contains N-1 matrices, {A(1), A(2), ..., A(N-1)} % ouputs: Had, the Hadard product of As function [ Had ] = getHadamard( As ) Had = []; for n=1:length(As) if isempty(Had) Had = As{n}'*As{n}; else Had = Had.*(As{n}'*As{n}); end end end
github
mathieubray/Tensor-master
onlineCP_initial.m
.m
Tensor-master/reference/onlineCP/onlineCP/onlineCP_initial.m
1,305
utf_8
42d77d8f1bbdbfd392978ab2f93e2c16
%% Shuo Zhou, Xuan Vinh Nguyen, James Bailey, Yunzhe Jia, Ian Davidson, % "Accelerating Online CP Decompositions for Higher Order Tensors", % (C) 2016 Shuo Zhou % Email: [email protected] % To run the code, Tensor Toolbox is required. % Brett W. Bader, Tamara G. Kolda and others. MATLAB Tensor Toolbox % Version 2.6, Available online, February 2015. % URL: http://www.sandia.gov/~tgkolda/TensorToolbox/ %% Initialization stage of OnlineCP % input: initX, data tensor used for initialization % As, a cell array contains the loading matrices of initX % R, tensor rank % ouputs: Ps, Qs, cell arrays contain the complementary matrices function [ Ps, Qs ] = onlineCP_initial( initX, As, R ) % if As is not given, calculate the CP decomposition of the initial data if ~exist('As') estInitX = cp_als(tensor(initX), R, 'tol', 1e-8); As = estInitX.U; % absorb lambda into the last dimension As{end} = As{end}*diag(estInitX.lambda); end dims = size(initX); N = length(dims); % for the first N-1 modes, calculte their assistant matrices P and Q H = getHadamard(As); Ks = getKhatriRaoList((As(1:N-1))); for n=1:N-1 Xn = reshape(permute(initX, [n, 1:n-1, n+1:N]), dims(n), []); Ps{n} = Xn*khatrirao(As{N}, Ks{n}); Qs{n} = H./(As{n}'*As{n}); end end
github
mathieubray/Tensor-master
onlineCP_update.m
.m
Tensor-master/reference/onlineCP/onlineCP/onlineCP_update.m
1,827
utf_8
5f2e07646e8e5c365a28545d3cdeff21
%% Shuo Zhou, Xuan Vinh Nguyen, James Bailey, Yunzhe Jia, Ian Davidson, % "Accelerating Online CP Decompositions for Higher Order Tensors", % (C) 2016 Shuo Zhou % Email: [email protected] % To run the code, Tensor Toolbox is required. % Brett W. Bader, Tamara G. Kolda and others. MATLAB Tensor Toolbox % Version 2.6, Available online, February 2015. % URL: http://www.sandia.gov/~tgkolda/TensorToolbox/ %% Update stage of OnlineCP % input: newX, the new incoming data tensor % As, a cell array contains the previous loading matrices of initX % Ps, Qs, cell arrays contain the previous complementary matrices % ouputs: As, a cell array contains the updated loading matrices of initX. % To save time, As(N) is not modified, instead, projection of % newX on time mode (alpha) is given in the output % Ps, Qs, cell arrays contain the updated complementary matrices % alpha, coefficient on time mode of newX function [ As, Ps, Qs, alpha ] = onlineCP_update( newX, As, Ps, Qs ) N = length(As)+1; R = size(As{1},2); dims = size(newX); if length(dims)==N-1 dims(end+1) = 1; end batchSize = dims(end); Ks = getKhatriRaoList((As(1:N-1))); H = getHadamard(As(1:N-1)); % update mode-N KN = khatrirao(Ks{1}, As{1}); newXN = reshape(permute(newX, [N, 1:N-1]), batchSize, []); alpha = newXN*KN/H; % update mode 1 to N-1 for n=1:N-1 newXn = reshape(permute(newX, [n, 1:n-1, n+1:N]), dims(n), []); Ps{n} = Ps{n}+newXn*khatrirao(alpha, Ks{n}); Hn = H./(As{n}'*As{n}); Qs{n} = Qs{n}+(alpha'*alpha).*Hn; As{n} = Ps{n}/Qs{n}; % newXn = reshape(permute(newX, [n, 1:n-1, n+1:N]), dims(n), []); % delta = khatrirao(alpha, Ks{n}); % Ps{n} = Ps{n}+newXn*delta; % Qs{n} = Qs{n}+delta'*delta; % As{n} = Ps{n}/Qs{n}; end end
github
caomw/arc-robot-vision-master
fill_depth_cross_bf.m
.m
arc-robot-vision-master/suction-based-grasping/external/bxf/fill_depth_cross_bf.m
1,990
utf_8
b7e5bbcb1bedcb7426978f7df1777af9
% In-paints the depth image using a cross-bilateral filter. The operation % is implemented via several filterings at various scales. The number of % scales is determined by the number of spacial and range sigmas provided. % 3 spacial/range sigmas translated into filtering at 3 scales. % % Args: % imgRgb - the RGB image, a uint8 HxWx3 matrix % imgDepthAbs - the absolute depth map, a HxW double matrix whose values % indicate depth in meters. % spaceSigmas - (optional) sigmas for the spacial gaussian term. % rangeSigmas - (optional) sigmas for the intensity gaussian term. % % Returns: % imgDepthAbs - the inpainted depth image. function imgDepthAbs = fill_depth_cross_bf(imgRgb, imgDepthAbs, ... spaceSigmas, rangeSigmas) error(nargchk(2,4,nargin)); assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8'); assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double'); if nargin < 3 %spaceSigmas = [ 12]; spaceSigmas = [12 5 8]; end if nargin < 4 % rangeSigmas = [0.2]; rangeSigmas = [0.2 0.08 0.02]; end assert(numel(spaceSigmas) == numel(rangeSigmas)); assert(isa(rangeSigmas, 'double')); assert(isa(spaceSigmas, 'double')); % Create the 'noise' image and get the maximum observed depth. imgIsNoise = imgDepthAbs == 0 | imgDepthAbs == 10; maxDepthObs = max(imgDepthAbs(~imgIsNoise)); % If depth map is empty, exit function if isempty(maxDepthObs) return; end % Convert the depth image to uint8. imgDepth = imgDepthAbs ./ maxDepthObs; imgDepth(imgDepth > 1) = 1; imgDepth = uint8(imgDepth * 255); % Run the cross-bilateral filter. if ispc imgDepthAbs = mex_cbf_windows(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:)); else imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:)); end % Convert back to absolute depth (meters). imgDepthAbs = im2double(imgDepthAbs) .* maxDepthObs; end
github
caomw/arc-robot-vision-master
sub2ind2d.m
.m
arc-robot-vision-master/parallel-jaw-grasping/baseline/sub2ind2d.m
135
utf_8
4970286e0c7d89b91364ca0d54668cff
% A faster version of sub2ind for 2D case function linIndex = sub2ind2d(sz, rowSub, colSub) linIndex = (colSub-1) * sz(1) + rowSub;
github
skiamu/Thesis-master
ConstantMix.m
.m
Thesis-master/MatlabCode/ConstantMix.m
2,067
utf_8
c3d95b1f095c2c17d5dda0fca8f331e2
function [U] = ConstantMix(param,model,VaR,M,N,alpha) %UNTITLED2 Summary of this function goes here % Detailed explanation goes here %% 1) Compute mu and Sigma switch model case 'Gaussian' mu = param.mu; Sigma = param.S; case 'Mixture' Sigma = 0; mu = 0; for i = 1 : length(param) mu = mu + param(i).lambda * param(i).mu; Sigma = Sigma + param(i).lambda * param(i).S; for j = 1 : i-1 Sigma = Sigma + param(i).lambda * param(j).lambda * ... (param(i).mu - param(j).mu) * (param(i).mu - param(j).mu)'; end end case {'GH','H','NIG','t'} if strcmp(model,'t') % 0) extract parameters nu = param.nu; lambda = param.lambda; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' Chi = nu - 2; wMean = 0.5 * Chi / (-lambda - 1); wVar = 0.25 * Chi^2 / ((-lambda-1)^2 * (-lambda-2)); else % 0) extract parameters lambda = param.lambda; Chi = param.Chi; Psi = param.Psi; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' wMean = (Chi/Psi)^0.5 * besselk(lambda+1,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wMoment2 = (Chi/Psi) * besselk(lambda+2,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wVar = wMoment2 - wMean^2; end Sigma = wMean * Sigma + wVar * (gamma * gamma'); mu = param.mu + wMean * gamma; end %% 2) Optimization options = optimoptions(@fmincon,'Algorithm','sqp',... 'SpecifyConstraintGradient',false); Nsim = 50; u0 = rand([Nsim M]); Aeq = ones([1 M]); beq = 1; ub = ones([M 1]); lb = zeros([M 1]); u = zeros([Nsim M]);f = zeros([Nsim 1]); for i = 1 : Nsim [u(i,:),f(i)] = fmincon(@(u)-u' * mu,u0(i,:)',[],[],Aeq,beq,lb,ub,... @(u)nonlcon(u,Sigma,VaR,alpha),options); end [~,idx] = min(f); u_star = u(idx,:); U = cell([N 1]); for i = 1 : N U{i} = u_star; end end % ConstantMix %% 3) non-linear constraint function [c,ceq] = nonlcon(u,Sigma,VaR,alpha) sigmaMax = VaR / norminv(1-alpha); c = sqrt(u' * Sigma * u) - sigmaMax; ceq = []; end
github
skiamu/Thesis-master
SimulationReturns.m
.m
Thesis-master/MatlabCode/SimulationReturns.m
2,284
utf_8
44d3a786d073e9f0d307c8f70056ed02
function [ w ] = SimulationReturns(param,Nsim,M,Nstep,model) %SimulationReturns is a function for simulating asset class returns %according to the model specified in input % INPUT: % param = cell array or struct of model parameters % Nsim = number of MC simulations % M = asset class dimension % Nstep = number of time intervals % SimulationMethod = % model = 'Gaussian', 'Mixture', 'GH' % OUTPUT: % w = % REMARK : gestire l'input GM switch model case 'Gaussian' [ w ] = SimulationG(param,Nsim,Nstep,M); case 'Mixture' [ w ] = SimulationGM(param,Nsim,Nstep,M); case {'GH','NIG','t'} [ w ] = SimulationGH(param,Nsim,Nstep,M); otherwise error('invalid model %s',model); end end function [ w ] = SimulationG(param,Nsim,Nstep,M) mu = param.mu; Sigma = param.S; w = zeros([Nsim M Nstep]); %initialization for k = 1 : Nstep w(:,:,k) = mvnrnd(mu,Sigma,Nsim); end end % SimulationG function [ w ] = SimulationGM(param,Nsim,Nstep,M) %SimulationGM is a function for simulating asset class returns over a %finite time grid % INPUT: % GM = fitgmdist's output, it contains all the information about the % fitted gaussian mixture distribution % param = cell array with distrubution's paraeters % Nsim = numer of MC simulation % M = asset allocation dimension % Nstep = number of time intervals % simulationMethod = 'built-in', 'Normal' % OUTPUT: % w = w = zeros([Nsim M Nstep]); %initialization for k = 1 : Nstep X = []; for i = 1 : length(param) X = [X; mvnrnd(param(i).mu,param(i).S, round(Nsim * param(i).lambda))]; end X = X(randperm(end),:); w(:,:,k) = X; end end % SimulationGM function [ w ] = SimulationGH(param,Nsim,Nstep,M) %UNTITLED Summary of this function goes here % Detailed explanation goes here % extract parameters lambda = param.lambda; Chi = param.Chi; Psi = param.Psi; mu = param.mu; Sigma = param.sigma; gamma = param.gamma; w = zeros([Nsim M Nstep]); %initialization Z = randn([Nsim M Nstep]); % normal gaussian for k = 1 : Nstep W = gigrnd(lambda, Psi, Chi, Nsim); % simulate GIG W = W * ones([1 M]); % triplicate the column w(:,:,k) = repmat(mu',[Nsim 1]) + W .* repmat(gamma',[Nsim 1]) + sqrt(W) .* ... (Z(:,:,k) * chol(Sigma)); end end % SimulationGH
github
skiamu/Thesis-master
PortfolioStatistics.m
.m
Thesis-master/MatlabCode/PortfolioStatistics.m
2,382
utf_8
4bece873bfca11d969ba7d9af9a9621b
function Statistics = PortfolioStatistics(Returns,freq,policy,r,N) %PortfolioStatistic computes several statistics on return data obtained by %a given portfolio strategy % % INPUT: % Returns = matrix of asset class returns in the desired frequency % freq = desired return frequency, freq must be one of the following % string {'d','wk','m','q','s','y'} [string] % policy = {'ODAA','CPPI','ConstantMix'} % r = annualized cash return (for the Sharpe index computation) % N = number of portfolio rebalancings % OUTPUT: % Statistics.ExpReturnsAnn = expected returns annualized % Statistics.VolatilityAnn = volatility annualized % Statistics.Skew = Skewness % Statistics.Kurt = Kurtosis % Statistics.VaR = monthly value-at-risk (alpha = 5%) % Statistics.MaxDrawdown = maximum drawdown % Statistics.MeanDrawdown = mean drawdown % Statistics.Corr = Correlationmatrix %% 1) asset class statistics % 1.1) drawdowns CumReturns = cumprod(1+Returns)-1; % cumulative return AD = cummax(CumReturns) - CumReturns; % drawdown MaxAD = max(AD); % maximum drawdown MeanAD = mean(AD); % mean drawdown % 1.2) expected returns and volatility, annualized switch freq case 'd' t = N / 252; t_VaR = 20; case 'wk' t = N / 52; t_VaR = 4; case 'm' t = N / 12; t_VaR = 1; case 'q' t = N / 4; t_VaR = 1 / 3; case 's' t = N / 2; t_VaR = 1 / 6; case 'y' t = N / 1; t_VaR = 1 / 12; end InvestmentReturns = CumReturns(end,:); % the path are along the coluns ExpReturnsAnn = (1 + mean(InvestmentReturns)).^(1/t) - 1; VolatilityAnn = std(InvestmentReturns) * sqrt(1/t); Median = (1 + median(InvestmentReturns)).^(1/t) - 1; Sharpe = (ExpReturnsAnn - r) ./ VolatilityAnn; % 1.3) ex-post V@R, historical simulation VaR = (1 + quantile(-Returns,0.95)).^ t_VaR - 1; % 95 percent quantile loss distribution % 1.4) Skweness and Kurtosis Skew = skewness(Returns); Kurt = kurtosis(Returns); %% 2) plot results % ksdensity(InvestmentReturns); % hold on % title([policy,' empirical investment return density']) %% 5) return results Statistics.ExpReturnsAnn = ExpReturnsAnn; Statistics.VolatilityAnn = VolatilityAnn; Statistics.Median = Median; Statistics.Skew = Skew; Statistics.Kurt = Kurt; Statistics.VaR = VaR; Statistics.MaxDrawdown = MaxAD; Statistics.MeanDrawdown = MeanAD; Statistics.Sharpe = Sharpe; end % PortfolioStatistics
github
skiamu/Thesis-master
GMcalibrationMM.m
.m
Thesis-master/MatlabCode/GMcalibrationMM.m
5,345
utf_8
386610fed4b3fd997198aa6b4dac1c50
function [param,CalibrationData] = GMcalibrationMM(Returns,k,M ) %GMcalibrationMM calibrates a gaussian mixture model by using the method of %moments % INPUT: % Returns = asset class returns [matrix] % k = number of mixture components % M = asset allocation dimension % OUTPUT: % param = struct array of parameters, each component of the array is a % struct with the following fields: mu, S, lambda % CalibrationData = struct with calibration information % REMARKS: % 1) this function is not general. It works only with mixtures of 2 % components and in dimension 3 % 2) by using a rolling initial condition in lsqnonlin we get better results. Try % to use both methods and see the differences in term of allocation % maps %% 1) compute sample statistics Sample = zeros([4 M]); % each column will contain mean, std, skwe and kurtosis Sample(1,:) = mean(Returns); Sample(2,:) = std(Returns); Sample(3,:) = skewness(Returns); Sample(4,:) = kurtosis(Returns); Corr = corr(Returns); % sample correlation matrix SampleCorr = [Corr(1,2); Corr(1,3); Corr(2,3)]; clear Corr; debug = false; % set to true if debug Sample = [0.0324;0.00;0;3; 0.0546;0.0445;-0.46;4.25; 0.1062;0.1477;-0.34;5.51]; Sample([1 5 9]) = (1 + Sample([1 5 9])).^(1/52) - 1; Sample([2 6 10]) = Sample([2 6 10]) / sqrt(52); Sample = reshape(Sample, [4 3]); SampleCorr = [0;0;0.0342]; end %% 2) least squares optimization eta = 0.01; lambda = 0:eta:1; N = length(lambda); error = zeros([N 1]); % initialization x = zeros([15 N]); % initialization lb = [-ones([k*M 1]); zeros([k*M 1]); -ones([3 1])]; % lower bound ub = ones([15 1]); % upper bound R = corr(Returns); x0 = [repmat(mean(Returns)',[2 1]) + (1e-2 * randn([6 1])); repmat(sqrt(diag(cov(Returns))),[2 1]) + (1e-2 * randn([6 1])); R(1,2);R(1,3);R(2,3)]; clear R; % d = rand(6); % x0 = [rand([6 1]); sqrt(diag(d'*d));-1 + (2).*rand([3 1])]; % smart initial point % x0 = rand([15 1]); options = optimoptions(@lsqnonlin); for i = 1 : N i [x(:,i), error(i)] = lsqnonlin(@(x) obj(x,Sample,SampleCorr,k,M,lambda(i)),... x0,lb,ub,options); % x0 = x(:,i); % rolling initial point end %% 3) choose best lambda % we select tha lambda which minimizes the residual error [minError,idxMin] = min(error); x_star = x(:,idxMin); % vector of optimal parameters lambda = lambda(idxMin); CalibrationData.error = minError; % return calibration information %% 4) assemble the struct param param = MakeParam(x_star,k,lambda); %% 5) compute LogL CalibrationData.LogL = sum(log(GMdensity(Returns,param,k))); end % GMcalibrationMM function F = obj(x,Sample,SampleCorr,k,M,lambda) %obj if the objective function for the least squares problem, it's a system %of moment equations. % INPUT: % x = vector of parameters(1:6 means 7:12 stdev 13:15 correlations) % Sample = matrix of sample moments (each colums contains mean,std,skw and kurtosis) % SampleCorr = vector of sample cross correlation (rho12,rho13,rho23) % k = number of gaussian components % M = asset allocation dimension % lambda = proportion % OUTPUT: % F = vector objective function %% 1) extract parameters % for readability purposes with extract the parameters from the column % vector x. Mean is a matrix whose columns are mean vectors of gaussian % component and Std collects standard deviation of each gaussian component Mean = reshape(x(1:k*M), [M k]); Std = reshape(x(k*M+1:2*k*M), [M k]); Rho = x(2*k*M+1:end); lambda = [lambda; 1-lambda]; %% 2) compute theoretical moments F = []; for i = 1 : M marginalMean = Mean(i,:); % means of the i-th marginal marginalStd = Std(i,:); % std of the i-th marginal [muX,sigmaX,gammaX,kappaX] = ComputeMomentsGM(marginalMean,marginalStd,lambda); F = [F; [muX;sigmaX;gammaX;kappaX] - Sample(:,i)]; end %% 3) compute theoretical correlations SampleCorrMatrix = [1 SampleCorr(1) SampleCorr(2); SampleCorr(1) 1 SampleCorr(3); SampleCorr(2) SampleCorr(3) 1]; SampleCovMatrix = corr2cov(Sample(2,:),SampleCorrMatrix); k = 13; for i = 1 : 3 for j = 1 : i-1 F(k) = lambda(1)*Rho(k-12)*Std(i,1)*Std(j,1) + ... lambda(2)*Rho(k-12)*Std(i,2)*Std(j,2) + ... lambda(1)*lambda(2)*(Mean(i,1)-Mean(i,2))*(Mean(j,1)-Mean(j,2)) -... SampleCovMatrix(i,j); k = k + 1; end end %% 4) check for positive-defitness and unimodality F = SetConstraints(F,Std,Rho,x,lambda); end % obj function F = SetConstraints(F,Std,Rho,x,lambda) RhoM = [1 Rho(1) Rho(2); Rho(1) 1 Rho(3); Rho(2) Rho(3) 1]; S1 = corr2cov(Std(:,1),RhoM); S2 = corr2cov(Std(:,2),RhoM); [~,p1] = chol(S1); [~,p2] = chol(S2); param = MakeParam(x,2,lambda); unimodality = zeros([3 1]); for i = 1 : 3 unimodality(i) = (param(2).mu(i) - param(1).mu(i))^2 < 27 * param(1).S(i,i) * ... param(2).S(i,i) / (4*(param(1).S(i,i) + param(2).S(i,i))); % q(i) = abs(param(1).mu(i)-param(2).mu(i)) - min(param(1).S(i,i),param(2).S(i,i)); end if any([p1 p2] ~= 0) || any(~unimodality) F = F .* 1e+10; end end function param = MakeParam(x,k,lambda) mu = [x(1:3) x(4:6)]; sigma = [x(7:9) x(10:12)]; Rho = x(13:15); lambda = [lambda; 1 - lambda]; RhoM = [1 Rho(1) Rho(2); Rho(1) 1 Rho(3); Rho(2) Rho(3) 1]; param(k) = struct(); for i = 1 : k param(i).mu = mu(:,i); param(i).S = corr2cov(sigma(:,i),RhoM); param(i).lambda = lambda(i); end end
github
skiamu/Thesis-master
SetODAAparameters.m
.m
Thesis-master/MatlabCode/SetODAAparameters.m
920
utf_8
c5b387e6f9b9c0049f8512023b540a99
% this file set the parameters for the ODAA algorithm VaR = 0.07; % monthly alpha = 0.01; % confidence level VaR switch freq % number of time step for a 2-year investment case 'wk' N = 104; NstepPlot = 26; VaR = VaR / 2; case 'm' N = 24; NstepPlot = 6; case 'q' N = 8; NstepPlot = 3; VaR = VaR * sqrt(3); end theta = 0.07; % yearly target return eta = 1e-3; % target set discretization [ X ] = makeTargetSet(N,theta,eta); function [ X ] = makeTargetSet(N,theta,eta) %makeTargetSet creates the discretized target sets used in the DPalgorithm % INPUT: % N = nuber of time step % theta = yearly target return % eta = discretization step % OUTPUT: % X = cell array of target sets X = cell([N+1 1]); % initialization LB = 0.5; % lober bound approximation UB = 1.9; % upper bound approximation for i = 2 : N X{i} = (LB:eta:UB)'; end X{1} = 1; X{end} = ((1+theta)^2:eta:UB)'; end
github
skiamu/Thesis-master
GMcalibrationML.m
.m
Thesis-master/MatlabCode/GMcalibrationML.m
2,824
utf_8
ce5d46253ca0ea08f399e425f895107f
function [param,CalibrationData] = GMcalibrationML(Returns,k,M) %GMcalibrationML calibrate a gaussian mixture model using the maximum %likelihood method % INPUT: % Returns = asset class returns [matrix] % k = number of mixture components [scalar] % M = asset allocation dimension [scalar] % OUTPUT: % param = struct array of parameters, each component of the array is a % struct with the following fields: mu, S, lambda % CalibrationData = struct with calibration information % REMARKS : % 1) problems for i = N (hence i = 1 : N -1) eta = 0.01; % discretization step grid for lambda lambda = eta:eta:1; N = length(lambda); R = corr(Returns); x0 = [repmat(mean(Returns)',[2 1]) + (1e-2 * randn([6 1])); repmat(sqrt(diag(cov(Returns))),[2 1]) + (1e-2 * randn([6 1])); R(1,2);R(1,3);R(2,3)]; clear R; % the initial condition must be fealible (matrixes positive definite) % d = rand(6); % x0 = [rand([6 1]); sqrt(diag(d'*d));-1 + (2).*rand([3 1])]; % smart initial point % x0 = rand([15 1]); % naive initial point x = zeros([15 N]); f = zeros([N 1]); lb = [-ones([k*M 1]); zeros([k*M 1]); -ones([3 1])]; % lower bound ub = ones([15 1]); % upper bound options = optimoptions(@fmincon,'Algorithm','interior-point'); for i = 1 : N-1 i [x(:,i),f(i)] = fmincon(@(x)-obj(x,Returns,k,lambda(i)),x0,[],[],[],[],lb,ub,... @(x)nonlinconst(x,k,lambda(i)),options); x0 = x(:,i); end f = -f; [~,idxMax] = max(f); x_star = x(:,idxMax); param = MakeParam(x_star,k,lambda(idxMax)); CalibrationData.LogL = f(idxMax); end function f = obj(x,X,k,lambda) % 1) compute LogL param = MakeParam(x,k,lambda); % convert vector x into the struct of parameters try f = sum(log(GMdensity(X,param,k))); % compute LogL, it cannot be written more explicitly than this catch % matrix not positive definite f = -1e7; end end function [c, ceq] = nonlinconst(x,k,lambda) %nonlinconst set the positive-definitness and unimodality constraint % INPUT: % x = % k = % lambda = % OUTPUT: % c = % ceq = param = MakeParam(x,k,lambda); % 1) positive-definite constraint p = zeros([k 1]); for i = 1 : k [~, p(i)] = chol(param(i).S); end % 2) unimodality constraint q = zeros([3 1]); for i = 1 : 3 q(i) = (param(2).mu(i) - param(1).mu(i))^2 - 27 * param(1).S(i,i) * ... param(2).S(i,i) / (4*(param(1).S(i,i) + param(2).S(i,i))); end % 3) set the constraints ceq = p; c = q; end function param = MakeParam(x,k,lambda) % function for converting the parameter varctor into a struct mu = [x(1:3) x(4:6)]; sigma = [x(7:9) x(10:12)]; Rho = x(13:15); lambda = [lambda; 1 - lambda]; RhoM = [1 Rho(1) Rho(2); Rho(1) 1 Rho(3); Rho(2) Rho(3) 1]; param(k) = struct(); for i = 1 : k param(i).mu = mu(:,i); param(i).S = corr2cov(sigma(:,i),RhoM); param(i).lambda = lambda(i); end end
github
skiamu/Thesis-master
ODAAalgorithm.m
.m
Thesis-master/MatlabCode/ODAAalgorithm.m
4,761
utf_8
e5d44aa45086e795a2913d20392f65c0
function [U,J] = ODAAalgorithm(N,M,X,param,model,VaR,alpha) %DPalgorithm implements a Dynamic Programming algorithm to solve a %stochastic reachability problem % INPUT: % N = number of time steps % M = dimension asset allocation (e.g. 3) % X = cell array of discretized target sets, to access the i-th % element use X{i} % param = density parameters [struct array] % VaR = value at risk (horizon according to the returns) % alpha = confidence level % OUTPUT: % U = cell array of asset allocations % J = cell array of optial value functions %% initialization U = cell([N 1]); % asset allocation cell array J = cell([N+1 1]); % optimal value function cell array J{end} = ones([length(X{end}) 1]); % indicator function target set X_N options = optimoptions(@fmincon,'Algorithm','sqp',... 'SpecifyConstraintGradient',false,'Display','off'); Aeq = ones([1 M]); beq = 1; % equality constraint lb = zeros([M 1]); ub = ones([M 1]); % upper and lower bound eta = 1e-4 / 5; % integretion interval discretization step % compute covariance matrix %% optimization for k = N : -1 : 1 k % print current iteration u0 = [1; 0; 0]; % initial condition dimXk = length(X{k}); % number of single optimizations Uk = zeros([dimXk M]); Jk = zeros([dimXk 1]); int_domain = (X{k+1}(1):eta:X{k+1}(end))'; % integretion domain with more points Jinterp = interp1(X{k+1},J{k+1},int_domain); for j = dimXk : -1 : 1 [Uk(j,:),Jk(j)] = fmincon(@(u) -objfun(u,X{k}(j),int_domain,Jinterp,param,model,k),... u0,[],[],Aeq,beq,lb,ub,@(u)confuneq(u,param,model,VaR,alpha),options); u0 = Uk(j,:)'; end U{k} = Uk; J{k} = -Jk; % print allocation maps % if k ~= 1 % idx = find(X{k} <= 1.8 & X{k} >= 0.6); % figure % area(X{k}(idx),U{k}(idx,:)) % title(strcat('k = ',num2str(k-1))) % ylim([0 1]) % end end end function f = objfun(u,x,int_domain,J,param,model,k) %objfun defines the problem's objective function that will be maximized % INPUT: % u = asset allocation vector % x = realization portfolio value [scalar] % int_domain = integration domain, k+1 target set discretized % J = k+1-th optimal value function % param = density parameters % OUTPUT: % f = objective function f = trapz(int_domain, J .* pf(int_domain,x,u,param,model)); end % objfun function [c,ceq, D, Deq] = confuneq(u,param,model,VaR,alpha) %confuneq states the max problem's constraints % INPUT: % u = asset allocation vector % param = density parameters % model = 'Gaussian','Mixture','GH' % VaR = value at risk % alpha = confidence level % OUTPUT: % c = inequality constraints % ceq = equality constraints switch model case 'Gaussian' c = -u' * param.mu + norminv(1-alpha) * sqrt(u' * param.S * u) - VaR; ceq = []; case 'Mixture' n = length(param); method = ''; if strcmp(method,'analitic') % analitic method Phi = 0; for i = 1 : n mu = -u' * param(i).mu; sigma = sqrt(u' * param(i).S * u); Phi = Phi + param(i).lambda * normcdf(-(VaR - mu) / sigma); end c = Phi - alpha; ceq = []; else % quadratic method W = 0; for i = 1 : length(param) W = W + param(i).lambda * param(i).S; for j = 1 : i-1 W = W + param(i).lambda * param(j).lambda * ... (param(i).mu - param(j).mu) * (param(i).mu - param(j).mu)'; end end sigmaMax = VaR / norminv(1-alpha); c = sqrt(u' * W * u) - sigmaMax; ceq = []; if nargout > 2 D = (W * u) / sqrt(u' * W * u); Deq = []; end end case {'GH','H','NIG','t'} if strcmp(model,'t') % 0) extract parameters nu = param.nu; lambda = param.lambda; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' Chi = nu - 2; wMean = 0.5 * Chi / (-lambda - 1); wVar = 0.25 * Chi^2 / ((-lambda-1)^2 * (-lambda-2)); else % 0) extract parameters lambda = param.lambda; Chi = param.Chi; Psi = param.Psi; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' wMean = (Chi/Psi)^0.5 * besselk(lambda+1,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wMoment2 = (Chi/Psi) * besselk(lambda+2,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wVar = wMoment2 - wMean^2; end wCov = wMean * Sigma + wVar * (gamma * gamma'); % 2) set up the constraints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); ceq = []; c = u' * wCov * u - sigma_max^2; % variance constraint if nargout > 2 D = 2 * wCov * u; Deq = []; end otherwise error('Invalid model : %s', model); end end % confuneq
github
skiamu/Thesis-master
CPPI.m
.m
Thesis-master/MatlabCode/CPPI.m
3,816
utf_8
0b3671a59bd94c7827f14d284259fe5c
function[U,Floor,Cushion] = CPPI(u0,X,r,m,N,param,model,VaR,alpha) %CPPI is a function for implementing the CPPI strategy. It computed the %allocation maps according to the CPPI policy for different realization of %the portfolio value % INPUT: % u0 = initial portfolio allocation [column vector] % X = cell array of discretized target sets % r = expected cash return (in the right frequency) % m = CPPI multiplier % N = number of time steps % param = cell array or struct of parameters % model = % VaR = % alpha = % OUTPUT: % U = asset allocation maps [cell array] % Floor = vector of portfolio floors, one at each time step % Cushion = cell array of portfolio cushions % REMARKS: %% CPPI synthesis M = length(u0); % asset class dimension x0 = X{1}; % initial portfolio value idxRiskyBasket = [2 3]; A = zeros([1 M]); A(idxRiskyBasket) = 1; beta = .9; % percentage guaranteed capital Floor = zeros([N 1]); % Floor(1) = x0 * (1 - A * u0 / m); % floor that guarantees exposure E0 Floor(1) = beta * x0 / (1 + r)^N; U = cell([N 1]); U{1} = u0'; Cushion = cell([N 1]); Cushion{1} = max(x0 - Floor(1),0); Aeq = ones([1 M]); beq = 1; ub = ones([M 1]); lb = zeros([M 1]); options = optimoptions(@fmincon,'Algorithm','sqp','Display','off'); for k = 2 : N k Floor(k) = Floor(k-1) * (1 + r); % floor grows deterministically at cash rate dimXk = length(X{k}); Uk = zeros([dimXk M]); for j = 1 : dimXk Cushion{k}(j) = max(X{k}(j) - Floor(k),0); % define portoflio cushion [Uk(j,:), ~] = fmincon(@(u)-objfun(u,A),u0,[],[],Aeq,beq,... lb,ub,@(u)confuneq(u,param,model,VaR,alpha,X{k}(j),Cushion{k}(j),m,A),options); u0 = Uk(j,:)'; end U{k} = Uk; end end % CPPI function f = objfun(u,A) % the goal is to invest as much as possible in the risk asset (Equity asset % class) f = A * u; end % objfun function [c, ceq] = confuneq(u,param,model,VaR,alpha,x,Cushion,m,A) %confuneq states the max problem's constraints % INPUT: % u = asset allocation vector % param = density parameters % OUTPUT: % c = inequality constraints % ceq = equality constraints switch model case 'Gaussian' S = param.S; mu = param.mu; ceq = []; mu_p = -u' * mu; sigma_p = sqrt(u' * S * u); c = [-VaR + (mu_p + norminv(1-alpha) * sigma_p); % variance constraint A*u*x - m*Cushion]; case 'Mixture' % 1) compute covariance matrix of asset return w(k+1) W = 0; for i = 1 : length(param) W = W + param(i).lambda * param(i).S; for j = 1 : i-1 W = W + param(i).lambda * param(j).lambda * ... (param(i).mu - param(j).mu) * (param(i).mu - param(j).mu)'; end end % 2) setup the constrints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); ceq = []; c = [u' * W * u - sigma_max^2; % variance constraint A*u*x - m*Cushion]; % exposure bounded by m*Cuschion case 'GH' % scrivere vincolo var in forma analitica lambda = param.lambda; Chi = param.Chi; Psi = param.Psi; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' wMean = (Chi/Psi) * besselk(lambda+1,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wMoment2 = (Chi/Psi)^2 * besselk(lambda+2,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wVar = wMoment2 - wMean^2; wCov = wMean * Sigma + wVar * (gamma * gamma'); W = wCov; % 2) setup the constrints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); ceq = []; c = [u' * W * u - sigma_max^2; % variance constraint A*u*x - m*Cushion]; % exposure bounded by m*Cuschion otherwise error('invalid model %s',model); end end
github
skiamu/Thesis-master
AssetClassStatistics.m
.m
Thesis-master/MatlabCode/AssetClassStatistics.m
3,272
utf_8
d2611314f6e00d6e2d3bc106bcfd05e6
function Statistics = AssetClassStatistics(Returns,freq,Flag) %AssetClassStatistics given a multivariate returns times-eries computes %several statistics % % INPUT: % Returns = Returns = matrix of asset class returns in the desired frequency % freq = desired return frequency, freq must be one of the following % string {'d','wk','m','q','s','y'} [string] % Flag = 1 for printing results % OUTPUT: % Statistics.ExpReturnsAnn = expected returns annualized % Statistics.VolatilityAnn = volatility annualized % Statistics.Skew = Skewness % Statistics.Kurt = Kurtosis % Statistics.VaR = monthly value-at-risk (alpha = 5%) % Statistics.MaxDrawdown = maximum drawdown % Statistics.MeanDrawdown = mean drawdown % Statistics.Corr = Correlationmatrix %% 1) introductory plot % return distribution histogram % nbins = 15; % figure % hist(Returns,nbins); % check return's distribution % if n > 1 % legend('Money','Bond','Equity') % title('asset class returns histogram') % xlabel('weekly returns') % % saveas(gcf,'/home/andrea/Thesis/Latex/final/Images/ReturnsHist.jpeg'); % print('/home/andrea/Thesis/Latex/final/Images/ReturnsHist', '-dpng', '-r900'); % end % returns plot % figure % for i = 1 : n % subplot(n,1,i) % plot(Returns(:,i)) % title(['returns time series',num2str(i)]) % end %% 2) asset class statistics % 2.1) drawdowns CumReturns = cumprod(1+Returns)-1; % cumulative return AD = cummax(CumReturns) - CumReturns; % drawdown MaxAD = max(AD); % maximum drawdown MeanAD = mean(AD); % mean drawdown % figure % area(AD(:,3)) % hold on % plot(Returns(:,3)) % 2.2) expected returns and volatility, annualized switch freq case 'd' t = 252; t_VaR = 20; case 'wk' t = 52; t_VaR = 4; case 'm' t = 12; t_VaR = 1; case 'q' t = 4; t_VaR = 1 / 3; case 's' t = 2; t_VaR = 1 / 6; case 'y' t = 1; t_VaR = 1 / 12; end ExpReturnsAnn = (1 + mean(Returns)).^t - 1; VolatilityAnn = std(Returns) * sqrt(t); Median = (1 + median(Returns)).^t - 1; Sharpe = (ExpReturnsAnn - ExpReturnsAnn(1)) ./ VolatilityAnn; % 2.2) ex-post V@R, historical simulation VaR = (1 + quantile(-Returns,0.95)).^ t_VaR - 1; % 95 percent quantile loss distribution % 2.4) Skweness and Kurtosis Skew = skewness(Returns); Kurt = kurtosis(Returns); % 2.5) correlations Corr = corr(Returns); %% 3) normality test HZmvntest(Returns); % multivariate normality test %% 4) print results if Flag disp('%%%%%%%%%%%%% Sample Statistics %%%%%%%%%%%%%') disp(['Means (ann) : ',num2str(ExpReturnsAnn)]) disp(['StDevs (ann) : ',num2str(VolatilityAnn)]) disp(['Median (ann) : ',num2str(Median)]) disp(['Skeweness : ',num2str(Skew)]) disp(['Kurtosis : ',num2str(Kurt)]) disp('Correlation matrix: ') Corr disp(['Monthly VaR_0.95: ', num2str(VaR)]) disp(['Max Drawdown: ', num2str(MaxAD)]) disp(['Mean Drawdown: ', num2str(MeanAD)]) disp(['Sharpe Ratio: ', num2str(Sharpe)]) end %% 5) return results Statistics.ExpReturnsAnn = ExpReturnsAnn; Statistics.VolatilityAnn = VolatilityAnn; Statistics.Median = Median; Statistics.Skew = Skew; Statistics.Kurt = Kurt; Statistics.VaR = VaR; Statistics.MaxDrawdown = MaxAD; Statistics.MeanDrawdown = MeanAD; Statistics.Sharpe = Sharpe; Statistics.Corr = Corr; end % PortfolioStatistics
github
skiamu/Thesis-master
GMdensity.m
.m
Thesis-master/MatlabCode/GMdensity.m
496
utf_8
3b5f1b55dc9b6fb60a972661e2a19d4d
function f = GMdensity(z,param,k) %GMdensity is the density of a random vector that follows a gaussian %mixture distribution % INPUT: % z = point where to compute the density, if z is a matrix the density % is computed at each row [array or matrix] % param = struct array or parameters % k = number of gaussian components % OUTPUT: % f = density value at z f = 0; for i = 1 : k f = f + param(i).lambda * mvnpdf(z,param(i).mu',param(i).S); end end % GMdensity
github
skiamu/Thesis-master
nigcdfSmall.m
.m
Thesis-master/MatlabCode/nig/nigcdfSmall.m
1,413
utf_8
c01bead4a056c7ee7b5f56418931aa9d
function y = nigcdfSmall(x, alpha, beta, mu, delta) %NIGCDFSMALL Normal-Inverse-Gaussian cumulative distribution function (cdf). % % This version is called by nigcdf and should not be used on its own. % This version is optimized for small vectors x (numel(x) < 100). % ------------------------------------------------------------------------- % % Allianz, Group Risk Controlling % Risk Methodology % Koeniginstr. 28 % D-80802 Muenchen % Germany % Internet: www.allianz.de % email: [email protected] % % Implementation Date: 2006 - 05 - 01 % Author: Dr. Ralf Werner % % ------------------------------------------------------------------------- % define accuracy of procedure eps = 1.0e-008; %% numerical integration of the NIG density % uses logarithmic transformation function z = helpfunction(u) z = zeros(size(u)); iPos = (u > 0); v = u(iPos); z(iPos) = nigpdf(log(v), alpha, beta, mu, delta) ./ v; end % abbreviation for NIG density function z = nigdens(u) z = nigpdf(u, alpha, beta, mu, delta); end y = zeros(size(x)); % sort values ascending [sortx, isortx] = sort(x(:)); y(isortx(1)) = quadl(@helpfunction, 0, exp(sortx(1)), eps); % successive integration of NIG density for k = 2:numel(x); y(isortx(k)) = quadl(@nigdens, sortx(k-1), sortx(k), eps) + y(isortx(k-1)); end end
github
skiamu/Thesis-master
quadcc.m
.m
Thesis-master/MatlabCode/quadcc/quadcc.m
16,056
utf_8
e7ad237cd4c4f4b6d84ad0f71a3b8f20
function [ int , err , nr_points ] = quadcc ( f , a , b , tol ) %QUADCC evaluates an integral using adaptive quadrature. The % algorithm uses Clenshaw-Curtis quadrature rules of increasing % degree in each interval and bisects the interval if either the % function does not appear to be smooth or a rule of maximum % degree has been reached. The error estimate is computed from the % L2-norm of the difference between two successive interpolations % of the integrand over the nodes of the respective quadrature rules. % % INT = QUADCC ( F , A , B , TOL ) approximates the integral % of F in the interval [A,B] up to the relative tolerance TOL. The % integrand F should accept a vector argument and return a vector % result containing the integrand evaluated at each element of the % argument. % % [INT,ERR,NPOINTS] = QUADCC ( F , A , B , TOL ) returns % ERR, an estimate of the absolute integration error as well as % NPOINTS, the number of function values for which the integrand % was evaluated. The value of ERR may be larger than the requested % tolerance, indicating that the integration may have failed. % % QUADCC halts with a warning if the integral is or appears % to be divergent. % % Reference: "Increasing the Reliability of Adaptive Quadrature % Using Explicit Interpolants", P. Gonnet, ACM Transactions on % Mathematical Software, 37 (3), art. no. 26, 2010. % Copyright (C) 2012 Pedro Gonnet % declare persistent variables persistent n xi_1 xi_2 xi_3 xi_4 b_1_def b_2_def b_3_def b_4_def ... V_1 V_2 V_3 V_4 V_1_inv V_2_inv V_3_inv V_4_inv xx Vcond T_left T_right w U % have the persistent variables been declared already? if ~exist('U') || isempty(U) % the nodes and newton polynomials n = [4,8,16,32]; xi_1 = -cos([0:n(1)]/n(1)*pi)'; xi_2 = -cos([0:n(2)]/n(2)*pi)'; xi_3 = -cos([0:n(3)]/n(3)*pi)'; xi_4 = -cos([0:n(4)]/n(4)*pi)'; b_1_def = [0., .233284737407921723637836578544e-1, 0., -.831479419283098085685277496071e-1, 0.,0.0541462136776153483932540272848 ]'; b_2_def = [0., .883654308363339862264532494396e-4, 0., .238811521522368331303214066075e-3, 0., .135365534194038370983135068211e-2, 0., -.520710690438660595086839959882e-2, 0.,0.00341659266223572272892690737979 ]'; b_3_def = [0., .379785635776247894184454273159e-7, 0., .655473977795402040043020497901e-7, 0., .103479954638984842226816620692e-6, 0., .173700624961660596894381303819e-6, 0., .337719613424065357737699682062e-6, 0., .877423283550614343733565759649e-6, 0., .515657204371051131603503471028e-5, 0.,-.203244736027387801432055290742e-4, 0.,0.0000134265158311651777460545854542 ]'; b_4_def = [0., .703046511513775683031092069125e-13, 0., .110617117381148770138566741591e-12, 0., .146334657087392356024202217074e-12, 0., .184948444492681259461791759092e-12, 0., .231429962470609662207589449428e-12, 0., .291520062115989014852816512412e-12, 0., .373653379768759953435020783965e-12, 0., .491840460397998449461993671859e-12, 0., .671514395653454630785723660045e-12, 0., .963162916392726862525650710866e-12, 0., .147853378943890691325323722031e-11, 0., .250420145651013003355273649380e-11, 0., .495516257435784759806147914867e-11, 0., .130927034711760871648068641267e-10, 0., .779528640561654357271364483150e-10, 0., -.309866395328070487426324760520e-9, 0., .205572320292667201732878773151e-9]'; % compute the coefficients V_1 = [ ones(size(xi_1)) xi_1 ]; V_2 = [ ones(size(xi_2)) xi_2 ]; V_3 = [ ones(size(xi_3)) xi_3 ]; V_4 = [ ones(size(xi_4)) xi_4 ]; xil = (xi_4 - 1) / 2; xir = (xi_4 + 1) / 2; Vl = [ ones(size(xil)) xil ]; Vr = [ ones(size(xir)) xir ]; xx = linspace(-1,1,500)'; Vx = [ ones(size(xx)) xx ]; for i=3:n(1)+1 V_1 = [ V_1 , ((2*i-3) / (i-1) * xi_1 .* V_1(:,i-1) - (i-2) / (i-1) * V_1(:,i-2)) ]; end; for i=3:n(2)+1 V_2 = [ V_2 , ((2*i-3) / (i-1) * xi_2 .* V_2(:,i-1) - (i-2) / (i-1) * V_2(:,i-2)) ]; end; for i=3:n(3)+1 V_3 = [ V_3 , ((2*i-3) / (i-1) * xi_3 .* V_3(:,i-1) - (i-2) / (i-1) * V_3(:,i-2)) ]; end; for i=3:n(4)+1 V_4 = [ V_4 , ((2*i-3) / (i-1) * xi_4 .* V_4(:,i-1) - (i-2) / (i-1) * V_4(:,i-2)) ]; Vx = [ Vx , ((2*i-3) / (i-1) * xx .* Vx(:,i-1) - (i-2) / (i-1) * Vx(:,i-2)) ]; Vl = [ Vl , ((2*i-3) / (i-1) * xil .* Vl(:,i-1) - (i-2) / (i-1) * Vl(:,i-2)) ]; Vr = [ Vr , ((2*i-3) / (i-1) * xir .* Vr(:,i-1) - (i-2) / (i-1) * Vr(:,i-2)) ]; end; for i=1:n(1)+1, V_1(:,i) = V_1(:,i) * sqrt(4*i-2)/2; end; for i=1:n(2)+1, V_2(:,i) = V_2(:,i) * sqrt(4*i-2)/2; end; for i=1:n(3)+1, V_3(:,i) = V_3(:,i) * sqrt(4*i-2)/2; end; for i=1:n(4)+1 V_4(:,i) = V_4(:,i) * sqrt(4*i-2)/2; Vx(:,i) = Vx(:,i) * sqrt(4*i-2)/2; Vl(:,i) = Vl(:,i) * sqrt(4*i-2)/2; Vr(:,i) = Vr(:,i) * sqrt(4*i-2)/2; end; V_1_inv = inv(V_1); V_2_inv = inv(V_2); V_3_inv = inv(V_3); V_4_inv = inv(V_4); Vcond = [ cond(V_1) , cond(V_2) , cond(V_3) , cond(V_4) ]; % shift matrix T_left = V_4_inv * Vl; T_right = V_4_inv * Vr; % compute the integral w = [ sqrt(2) , zeros(1,n(4)) ] / 2; % legendre % set-up the downdate matrix k = [0:n(4)]'; U = diag(sqrt((k+1).^2 ./ (2*k+1) ./ (2*k+3))) + diag(sqrt(k(3:end).^2 ./ (4*k(3:end).^2-1)),2); end; % if exist('n') % create the original datatype ivals = struct( ... 'a', [], 'b',[], ... 'c', [], 'c_old', [], ... 'fx', [], ... 'int', [], ... 'err', [], ... 'tol', [], ... 'depth', [], ... 'rdepth', [], ... 'ndiv', [] ); % compute the first interval points = (a+b)/2 + (b-a) * xi_4 / 2; fx = f(points); nans = []; for i=1:length(fx), if ~isfinite(fx(i)), nans = [ i , nans ]; fx(i) = 0.0; end; end; ivals(1).c = zeros(n(4)+1,4); ivals(1).c(1:n(4)+1,4) = V_4_inv * fx; ivals(1).c(1:n(3)+1,3) = V_3_inv * fx([1:2:n(4)+1]); for i=nans, fx(i) = NaN; end; ivals(1).fx = fx; ivals(1).c_old = zeros(size(fx)); ivals(1).a = a; ivals(1).b = b; ivals(1).int = (b-a) * w * ivals(1).c(:,4); c_diff = norm(ivals(1).c(:,4) - ivals(1).c(:,3)); ivals(1).err = (b-a) * c_diff; if c_diff / norm(ivals(1).c(:,4)) > 0.1 ivals(1).err = max( ivals(1).err , (b-a) * norm(ivals(1).c(:,4)) ); end; ivals(1).tol = tol; ivals(1).depth = 4; ivals(1).ndiv = 0; ivals(1).rdepth = 1; % init some globals int = ivals(1).int; err = ivals(1).err; nr_ivals = 1; int_final = 0; err_final = 0; err_excess = 0; i_max = 1; nr_points = n(4)+1; ndiv_max = 20; % do we even need to go this way? if err < int * tol, return; end; % main loop while true % get some global data a = ivals(i_max).a; b = ivals(i_max).b; depth = ivals(i_max).depth; split = 0; % depth of the old interval if depth == 1 points = (a+b)/2 + (b-a)*xi_2/2; fx(1:2:n(2)+1) = ivals(i_max).fx; fx(2:2:n(2)) = f(points(2:2:n(2))); fx = fx(1:n(2)+1); nans = []; for i=1:length(fx), if ~isfinite(fx(i)), fx(i) = 0.0; nans = [ i , nans ]; end; end; c_new = V_2_inv * fx; if length(nans) > 0 b_new = b_2_def; n_new = n(2); for i=nans b_new(1:end-1) = (U(1:n(2)+1,1:n(2)+1) - diag(ones(n(2),1)*xi_2(i),1)) \ b_new(2:end); b_new(end) = 0; c_new = c_new - c_new(n_new+1) / b_new(n_new+1) * b_new(1:end-1); n_new = n_new - 1; fx(i) = NaN; end; end; ivals(i_max).fx = fx; nc = norm(c_new); nr_points = nr_points + n(2)-n(1); ivals(i_max).c(1:n(2)+1,2) = c_new; c_diff = norm(ivals(i_max).c(:,1) - ivals(i_max).c(:,2)); ivals(i_max).err = (b-a) * c_diff; int_old = ivals(i_max).int; ivals(i_max).int = (b-a) * w(1) * c_new(1); if nc > 0 && c_diff / nc > 0.1 split = 1; else ivals(i_max).depth = 2; end; elseif depth == 2 points = (a+b)/2 + (b-a)*xi_3/2; fx(1:2:n(3)+1) = ivals(i_max).fx; fx(2:2:n(3)) = f(points(2:2:n(3))); fx = fx(1:n(3)+1); nans = []; for i=1:length(fx), if ~isfinite(fx(i)), fx(i) = 0.0; nans = [ i , nans ]; end; end; c_new = V_3_inv * fx; if length(nans) > 0 b_new = b_3_def; n_new = n(3); for i=nans b_new(1:end-1) = (U(1:n(3)+1,1:n(3)+1) - diag(ones(n(3),1)*xi_3(i),1)) \ b_new(2:end); b_new(end) = 0; c_new = c_new - c_new(n_new+1) / b_new(n_new+1) * b_new(1:end-1); n_new = n_new - 1; fx(i) = NaN; end; end; ivals(i_max).fx = fx; nc = norm(c_new); nr_points = nr_points + n(3)-n(2); ivals(i_max).c(1:n(3)+1,3) = c_new; c_diff = norm(ivals(i_max).c(:,2) - ivals(i_max).c(:,3)); ivals(i_max).err = (b-a) * c_diff; int_old = ivals(i_max).int; ivals(i_max).int = (b-a) * w(1) * c_new(1); if nc > 0 && c_diff / nc > 0.1 split = 1; else ivals(i_max).depth = 3; end; elseif depth == 3 points = (a+b)/2 + (b-a)*xi_4/2; fx(1:2:n(4)+1) = ivals(i_max).fx; fx(2:2:n(4)) = f(points(2:2:n(4))); fx = fx(1:n(4)+1); nans = []; for i=1:length(fx), if ~isfinite(fx(i)), fx(i) = 0.0; nans = [ i , nans ]; end; end; c_new = V_4_inv * fx; if length(nans) > 0 b_new = b_4_def; n_new = n(4); for i=nans b_new(1:end-1) = (U(1:n(4)+1,1:n(4)+1) - diag(ones(n(4),1)*xi_4(i),1)) \ b_new(2:end); b_new(end) = 0; c_new = c_new - c_new(n_new+1) / b_new(n_new+1) * b_new(1:end-1); n_new = n_new - 1; fx(i) = NaN; end; end; ivals(i_max).fx = fx; nc = norm(c_new); nr_points = nr_points + n(4)-n(3); ivals(i_max).c(:,4) = c_new; c_diff = norm(ivals(i_max).c(:,3) - ivals(i_max).c(:,4)); ivals(i_max).err = (b-a) * c_diff; int_old = ivals(i_max).int; ivals(i_max).int = (b-a) * w(1) * c_new(1); if nc > 0 && c_diff / nc > 0.1 split = 1; else ivals(i_max).depth = 4; end; else split = 1; end; % can we safely ignore this interval? if points(2) <= points(1) || points(end) <= points(end-1) || ... ivals(i_max).err < abs(ivals(i_max).int) * eps * Vcond(ivals(i_max).depth) err_final = err_final + ivals(i_max).err; int_final = int_final + ivals(i_max).int; ivals(i_max) = ivals(nr_ivals); nr_ivals = nr_ivals - 1; elseif split m = (a + b) / 2; nr_ivals = nr_ivals + 1; ivals(nr_ivals).a = a; ivals(nr_ivals).b = m; ivals(nr_ivals).tol = ivals(i_max).tol / sqrt(2); ivals(nr_ivals).depth = 1; ivals(nr_ivals).rdepth = ivals(i_max).rdepth + 1; ivals(nr_ivals).c = zeros(n(4)+1,4); fx = [ ivals(i_max).fx(1) ; f((a+m)/2+(m-a)*xi_1(2:end-1)/2) ; ivals(i_max).fx((end+1)/2) ]; nr_points = nr_points + n(1)-1; nans = []; for i=1:length(fx), if ~isfinite(fx(i)), fx(i) = 0.0; nans = [ i , nans ]; end; end; c_new = V_1_inv * fx; if length(nans) > 0 b_new = b_1_def; n_new = n(1); for i=nans b_new(1:end-1) = (U(1:n(1)+1,1:n(1)+1) - diag(ones(n(1),1)*xi_1(i),1)) \ b_new(2:end); b_new(end) = 0; c_new = c_new - c_new(n_new+1) / b_new(n_new+1) * b_new(1:end-1); n_new = n_new - 1; fx(i) = NaN; end; end; ivals(nr_ivals).fx = fx; ivals(nr_ivals).c(1:n(1)+1,1) = c_new; nc = norm(c_new); ivals(nr_ivals).c_old = T_left * ivals(i_max).c(:,depth); c_diff = norm(ivals(nr_ivals).c(:,1) - ivals(nr_ivals).c_old); ivals(nr_ivals).err = (m - a) * c_diff; ivals(nr_ivals).int = (m - a) * ivals(nr_ivals).c(1,1) * w(1); ivals(nr_ivals).ndiv = ivals(i_max).ndiv + (abs(ivals(i_max).c(1,1)) > 0 && ivals(nr_ivals).c(1,1) / ivals(i_max).c(1,1) > 2); if ivals(nr_ivals).ndiv > ndiv_max && 2*ivals(nr_ivals).ndiv > ivals(nr_ivals).rdepth, warning(sprintf('possibly divergent integral in the interval [%e,%e]! (h=%e)',a,m,m-a)); int = sign(int) * Inf; return; end; nr_ivals = nr_ivals + 1; ivals(nr_ivals).a = m; ivals(nr_ivals).b = b; ivals(nr_ivals).tol = ivals(i_max).tol / sqrt(2); ivals(nr_ivals).depth = 1; ivals(nr_ivals).rdepth = ivals(i_max).rdepth + 1; ivals(nr_ivals).c = zeros(n(4)+1,4); fx = [ ivals(i_max).fx((end+1)/2) ; f((m+b)/2+(b-m)*xi_1(2:end-1)/2) ; ivals(i_max).fx(end) ]; nr_points = nr_points + n(1)-1; nans = []; for i=1:length(fx), if ~isfinite(fx(i)), fx(i) = 0.0; nans = [ i , nans ]; end; end; c_new = V_1_inv * fx; if length(nans) > 0 b_new = b_1_def; n_new = n(1); for i=nans b_new(1:end-1) = (U(1:n(1)+1,1:n(1)+1) - diag(ones(n(1),1)*xi_1(i),1)) \ b_new(2:end); b_new(end) = 0; c_new = c_new - c_new(n_new+1) / b_new(n_new+1) * b_new(1:end-1); n_new = n_new - 1; fx(i) = NaN; end; end; ivals(nr_ivals).fx = fx; ivals(nr_ivals).c(1:n(1)+1,1) = c_new; nc = norm(c_new); ivals(nr_ivals).c_old = T_right * ivals(i_max).c(:,depth); c_diff = norm(ivals(nr_ivals).c(:,1) - ivals(nr_ivals).c_old); ivals(nr_ivals).err = (b - m) * c_diff; ivals(nr_ivals).int = (b - m) * ivals(nr_ivals).c(1,1) * w(1); ivals(nr_ivals).ndiv = ivals(i_max).ndiv + (abs(ivals(i_max).c(1,1)) > 0 && ivals(nr_ivals).c(1,1) / ivals(i_max).c(1,1) > 2); if ivals(nr_ivals).ndiv > ndiv_max && 2*ivals(nr_ivals).ndiv > ivals(nr_ivals).rdepth, warning(sprintf('possibly divergent integral in the interval [%e,%e]! (h=%e)',m,b,b-m)); int = sign(int) * Inf; return; end; ivals(i_max) = ivals(nr_ivals); nr_ivals = nr_ivals - 1; end; % compute the running err and new max i_max = 1; i_min = 1; err = err_final; int = int_final; for i=1:nr_ivals if ivals(i).err > ivals(i_max).err, i_max = i; elseif ivals(i).err < ivals(i_min).err, i_min = i; end; err = err + ivals(i).err; int = int + ivals(i).int; end; % nuke smallest element if stack is larger than 200 if nr_ivals > 200 err_final = err_final + ivals(i_min).err; int_final = int_final + ivals(i_min).int; ivals(i_min) = ivals(nr_ivals); if i_max == nr_ivals, i_max = i_min; end; nr_ivals = nr_ivals - 1; end; % get up and leave? if err == 0 || err < abs(int) * tol || (err_final > abs(int) * tol && err - err_final < abs(int) * tol) || nr_ivals == 0 break; end; end; % main loop % clean-up and tabulate err = err + err_excess; end
github
skiamu/Thesis-master
SetODAAParamED.m
.m
Thesis-master/MatlabCode/DiscreteEvent/SetODAAParamED.m
676
utf_8
66eb9f2fd4f734695b219acb02828d66
% set ODAA parameters in the event-driven case N = 10; % number of events theta = 0.07; % yearly target return eta = 1e-3/5; % target set discretization n = 3; [ X ] = makeTargetSet(N,theta,eta,n); function [ X ] = makeTargetSet(N,theta,eta,n) %makeTargetSet creates the discretized target sets used in the DPalgorithm % INPUT: % N = nuber of time step % theta = yearly target return % eta = discretization step % OUTPUT: % X = cell array of target sets X = cell([N+1 1]); % initialization LB = 0.8; % lober bound approximation UB = 2; % upper bound approximation for i = 2 : N X{i} = (LB:eta:UB)'; end X{1} = 1; X{end} = ((1+theta)^n:eta:UB)'; end
github
skiamu/Thesis-master
pfDESext3.m
.m
Thesis-master/MatlabCode/DiscreteEvent/pfDESext3.m
1,445
utf_8
224ebf751a15ada2820f8049f61b15ed
function [ f ] = pfDESext3(z,x,u,J_jump,param) %pfDESext2 computes the density function of the random variable x(k+1) %(portdolio value at event number k+1) % INPUT: % z = indipendent variable % x = portfolio value last event % u = cash weigth % J_jump = jump treshold % param = struct of model parameters % OUTPUT: % f = density computed in z % 1) extract parameters a = param.a; b = param.b; sigma = param.sigma; % vasicek parameters p = param.p; lambda = param.lambda; % basic parameters r0 = 0.05; % initial point % 2) define mean and std for Integrated O-U r.v. mu_tilde = @(y) ((r0 - b) * (1 - y.^(a/lambda)) - a * b / lambda * log(y)) / a; sigma_tilde = @(y) sqrt(sigma^2 / (2 * a^3) * (-2 * a / lambda * log(y) + 4 * y.^(a/lambda) - ... y.^(2*a/lambda) - 3)); f1 = zeros(size(z)); f2 = f1; csi = x * J_jump * u; idx1 = z >= x + csi; idx2 = z >= x - csi; t = (1e-10:0.0001:1-1e-3)'; % 4) compute t-integrals if ~isempty(z(idx1)) f1(idx1) = p ./ (z(idx1) - csi) .* trapz(t,Integrand2(t,z(idx1),-1,... mu_tilde,sigma_tilde,csi,x)); end if ~isempty(z(idx2)) f2(idx2) = (1-p) ./ (z(idx2) + csi) .* trapz(t,Integrand2(t,z(idx2),1,... mu_tilde,sigma_tilde,csi,x)); end f = f1 + f2; end % pfDES function I = Integrand2(t,z,sign,mu_tilde,sigma_tilde,csi,x) assert(iscolumn(t) & isrow(z),'dimension of t or z invalid'); I = normpdf(log((z + sign * csi) / x), mu_tilde(t),... sigma_tilde(t)) ; end
github
skiamu/Thesis-master
SimulationED.m
.m
Thesis-master/MatlabCode/DiscreteEvent/SimulationED.m
2,275
utf_8
ca5f6eec7bc32cb48465a17278c5eec7
function [Binomial, tau] = SimulationED(param,Nsim, Nstep,J_jump,model) %SimulationED simulated the random variables ih the event-driven dynamics %for the basic model and extension1 % INPUT: % param = model parameters [struct] % Nsim = number of MC simulation [scalar] % Nstep = number of time steps [scalar] % J_jump = jump size [scalar] % model = {'basic','ext1'} % OUTPUT: % Binomial = jump sign [matrix Nsim x Nstep] % tau = holding times [matrix Nsim x Nstep] p = param.p; %% simulation tau if strcmp(model,'basic') lambda = param.lambda; tau = exprnd(1 / lambda, [Nsim Nstep]); else % model ext1 mu = param.mu; sigma = param.sigma; mu_tilde = mu-sigma^2/2; F_tau = @(t)1-(2 * cosh(mu_tilde * J_jump / sigma^2) * Kappa(t,mu_tilde,sigma,J_jump)); t = (1e-4:1e-5:4)'; [u,idxUnique] = unique(F_tau(t)); % some value may repete themselves. interp1 raises an error u_tilde = rand([Nsim Nstep]); tau = interp1(u,t(idxUnique),u_tilde); end %% simulation Binomial Binomial = -ones([Nsim Nstep]); Binomial(rand([Nsim Nstep]) < p) = 1; %Binomial = Binomial(randperm(Nsim),randperm(Nstep)); end % SimulationED function [f] = Kappa(y,mu_tilde,sigma,J_jump) % INPUT: % y = (z+-csi) / x (column vector) % x = ptf value % mu_tilde = mu - 0.5 * sigma^2; % sigma = volatility % r = cash yearly return % J_jump = jump size epsilon = 1e-8; % series truncation tolerance n = length(y); t = min(y); NN = sqrt(max(1, -8 * J_jump^2 ./ (pi^2 * sigma^2 * t) .* ... (log((pi^3 * sigma^2 * t * epsilon) / (16 * J_jump^2))... - J_jump * mu_tilde / sigma^2))); % number of series terms global freeMemory if 8 * NN * n * 1e-6 >= freeMemory % check if there's enogh memory f = [0; Kappa(y(2:end),mu_tilde,sigma,J_jump)]; else N = 1:NN; % y is a column vector, N must be a row vector. In this case the operation % y.^N gives a matrix [lenght(y) length(N)]. To get the sum of the partial % sum we need to sum by rows (e.g. sum(,2)) f = sigma^2 * pi / (4 * J_jump^2) * (sum(N .* (-1).^(N+1) ./ ... (mu_tilde^2 / (2 * sigma^2) + (sigma^2 * N.^2 * pi^2) / (8 * J_jump^2)) .* ... exp(-(mu_tilde^2 / (2 * sigma^2) + (sigma^2 * N.^2 * pi^2) / (8 * J_jump^2)) .* y)... .* sin(pi * N / 2),2)); end end % Gamma
github
skiamu/Thesis-master
fminsearchbnd.m
.m
Thesis-master/MatlabCode/DiscreteEvent/fminsearchbnd.m
8,139
utf_8
1316d7f9d69771e92ecc70425e0f9853
function [x,fval,exitflag,output] = fminsearchbnd(fun,x0,LB,UB,options,varargin) % FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation % usage: x=FMINSEARCHBND(fun,x0) % usage: x=FMINSEARCHBND(fun,x0,LB) % usage: x=FMINSEARCHBND(fun,x0,LB,UB) % usage: x=FMINSEARCHBND(fun,x0,LB,UB,options) % usage: x=FMINSEARCHBND(fun,x0,LB,UB,options,p1,p2,...) % usage: [x,fval,exitflag,output]=FMINSEARCHBND(fun,x0,...) % % arguments: % fun, x0, options - see the help for FMINSEARCH % % LB - lower bound vector or array, must be the same size as x0 % % If no lower bounds exist for one of the variables, then % supply -inf for that variable. % % If no lower bounds at all, then LB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % UB - upper bound vector or array, must be the same size as x0 % % If no upper bounds exist for one of the variables, then % supply +inf for that variable. % % If no upper bounds at all, then UB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % Notes: % % If options is supplied, then TolX will apply to the transformed % variables. All other FMINSEARCH parameters should be unaffected. % % Variables which are constrained by both a lower and an upper % bound will use a sin transformation. Those constrained by % only a lower or an upper bound will use a quadratic % transformation, and unconstrained variables will be left alone. % % Variables may be fixed by setting their respective bounds equal. % In this case, the problem will be reduced in size for FMINSEARCH. % % The bounds are inclusive inequalities, which admit the % boundary values themselves, but will not permit ANY function % evaluations outside the bounds. These constraints are strictly % followed. % % If your problem has an EXCLUSIVE (strict) constraint which will % not admit evaluation at the bound itself, then you must provide % a slightly offset bound. An example of this is a function which % contains the log of one of its parameters. If you constrain the % variable to have a lower bound of zero, then FMINSEARCHBND may % try to evaluate the function exactly at zero. % % % Example usage: % rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2; % % fminsearch(rosen,[3 3]) % unconstrained % ans = % 1.0000 1.0000 % % fminsearchbnd(rosen,[3 3],[2 2],[]) % constrained % ans = % 2.0000 4.0000 % % See test_main.m for other examples of use. % % % See also: fminsearch, fminspleas % % % Author: John D'Errico % E-mail: [email protected] % Release: 4 % Release date: 7/23/06 % size checks xsize = size(x0); x0 = x0(:); n=length(x0); if (nargin<3) || isempty(LB) LB = repmat(-inf,n,1); else LB = LB(:); end if (nargin<4) || isempty(UB) UB = repmat(inf,n,1); else UB = UB(:); end if (n~=length(LB)) || (n~=length(UB)) error 'x0 is incompatible in size with either LB or UB.' end % set default options if necessary if (nargin<5) || isempty(options) options = optimset('fminsearch'); end % stuff into a struct to pass around params.args = varargin; params.LB = LB; params.UB = UB; params.fun = fun; params.n = n; % note that the number of parameters may actually vary if % a user has chosen to fix one or more parameters params.xsize = xsize; params.OutputFcn = []; % 0 --> unconstrained variable % 1 --> lower bound only % 2 --> upper bound only % 3 --> dual finite bounds % 4 --> fixed variable params.BoundClass = zeros(n,1); for i=1:n k = isfinite(LB(i)) + 2*isfinite(UB(i)); params.BoundClass(i) = k; if (k==3) && (LB(i)==UB(i)) params.BoundClass(i) = 4; end end % transform starting values into their unconstrained % surrogates. Check for infeasible starting guesses. x0u = x0; k=1; for i = 1:n switch params.BoundClass(i) case 1 % lower bound only if x0(i)<=LB(i) % infeasible starting value. Use bound. x0u(k) = 0; else x0u(k) = sqrt(x0(i) - LB(i)); end % increment k k=k+1; case 2 % upper bound only if x0(i)>=UB(i) % infeasible starting value. use bound. x0u(k) = 0; else x0u(k) = sqrt(UB(i) - x0(i)); end % increment k k=k+1; case 3 % lower and upper bounds if x0(i)<=LB(i) % infeasible starting value x0u(k) = -pi/2; elseif x0(i)>=UB(i) % infeasible starting value x0u(k) = pi/2; else x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1; % shift by 2*pi to avoid problems at zero in fminsearch % otherwise, the initial simplex is vanishingly small x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k)))); end % increment k k=k+1; case 0 % unconstrained variable. x0u(i) is set. x0u(k) = x0(i); % increment k k=k+1; case 4 % fixed variable. drop it before fminsearch sees it. % k is not incremented for this variable. end end % if any of the unknowns were fixed, then we need to shorten % x0u now. if k<=n x0u(k:n) = []; end % were all the variables fixed? if isempty(x0u) % All variables were fixed. quit immediately, setting the % appropriate parameters, then return. % undo the variable transformations into the original space x = xtransform(x0u,params); % final reshape x = reshape(x,xsize); % stuff fval with the final value fval = feval(params.fun,x,params.args{:}); % fminsearchbnd was not called exitflag = 0; output.iterations = 0; output.funcCount = 1; output.algorithm = 'fminsearch'; output.message = 'All variables were held fixed by the applied bounds'; % return with no call at all to fminsearch return end % Check for an outputfcn. If there is any, then substitute my % own wrapper function. if ~isempty(options.OutputFcn) params.OutputFcn = options.OutputFcn; options.OutputFcn = @outfun_wrapper; end % now we can call fminsearch, but with our own % intra-objective function. [xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params); % undo the variable transformations into the original space x = xtransform(xu,params); % final reshape to make sure the result has the proper shape x = reshape(x,xsize); % Use a nested function as the OutputFcn wrapper function stop = outfun_wrapper(x,varargin); % we need to transform x first xtrans = xtransform(x,params); % then call the user supplied OutputFcn stop = params.OutputFcn(xtrans,varargin{1:(end-1)}); end end % mainline end % ====================================== % ========= begin subfunctions ========= % ====================================== function fval = intrafun(x,params) % transform variables, then call original function % transform xtrans = xtransform(x,params); % and call fun fval = feval(params.fun,reshape(xtrans,params.xsize),params.args{:}); end % sub function intrafun end % ====================================== function xtrans = xtransform(x,params) % converts unconstrained variables into their original domains xtrans = zeros(params.xsize); % k allows some variables to be fixed, thus dropped from the % optimization. k=1; for i = 1:params.n switch params.BoundClass(i) case 1 % lower bound only xtrans(i) = params.LB(i) + x(k).^2; k=k+1; case 2 % upper bound only xtrans(i) = params.UB(i) - x(k).^2; k=k+1; case 3 % lower and upper bounds xtrans(i) = (sin(x(k))+1)/2; xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i); % just in case of any floating point problems xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i))); k=k+1; case 4 % fixed variable, bounds are equal, set it at either bound xtrans(i) = params.LB(i); case 0 % unconstrained variable. xtrans(i) = x(k); k=k+1; end end end % sub function xtransform end
github
skiamu/Thesis-master
DPalgorithmDES2.m
.m
Thesis-master/MatlabCode/DiscreteEvent/DPalgorithmDES2.m
2,887
utf_8
920d385e67a0207b40729686c466d1d2
function [U,J] = DPalgorithmDES2(N,X,p,lambda,r,J_jump,VaR,alpha) %DPalgorithm implements a Dynamic Programming algorithm to solve a %stochastic reachability problem % INPUT: % N = number of time steps % M = dimension asset allocation (e.g. 3) % X = cell array of discretized target sets, to access the i-th % element use X{i} % param = density parameters [struct array] % VaR = value at risk (horizon according to the returns) % alpha = confidence level % OUTPUT: % U = cell array of asset allocations % J = cell array of optial value functions %% initialization U = cell([N 1]); % asset allocation cell array J = cell([N+1 1]); % optimal value function cell array J{end} = ones([length(X{end}) 1]); % indicator function target set X_N options = optimoptions(@fmincon,'Algorithm','interior-point','Display','off'); lb = 0; ub = 1; % upper and lower bound weigth cash eta = 1e-4 / 3; % integretion interval discretization step %% optimization for k = N : -1 : 1 k % print current iteration u0 = 0.5; % initial condition dimXk = length(X{k}); % number of single optimizations Uk = zeros([dimXk 1]); Jk = zeros([dimXk 1]); int_domain = (X{k+1}(1):eta:X{k+1}(end))'; % integretion domain with more points Jinterp = interp1(X{k+1},J{k+1},int_domain); for j = dimXk : -1 : 1 [Uk(j),Jk(j)] = fmincon(@(u) -objfun(u,X{k}(j),int_domain,Jinterp,p,lambda,r,J_jump),... u0,[],[],[],[],lb,ub,@(u)confuneq(u,p,lambda,r,J_jump,VaR,alpha),options); u0 = Uk(j); end U{k} = Uk; J{k} = -Jk; % print allocation maps if k ~= 1 idx = find(X{k} <= 1.4 & X{k} >= 0.6); figure plot(X{k}(idx),U{k}(idx),'b.--') title(strcat('k = ',num2str(k-1))) legend('cash','stock') % saveas(gcf,[pwd strcat('/Latex/secondWIP/k',num2str(k-1),model,'.png')]); end end end function f = objfun(u,x,int_domain,J,p,lambda,r,J_jump) %objfun defines the problem's objective function that will be maximized % INPUT: % u = asset allocation vector % x = realization portfolio value [scalar] % int_domain = integration domain, k+1 target set discretized % J = k+1-th optimal value function % param = density parameters % OUTPUT: % f = objective function f = trapz(int_domain, J .* pfDES(int_domain,x,u,J_jump,p,lambda,r)); end % objfun function [c,ceq] = confuneq(u,p,lambda,r,J_jump,VaR,alpha) %confuneq states the max problem's constraints % INPUT: % u = asset allocation vector % p = % lambda = % r = % J_jump = % VaR = value at risk % alpha = confidence level % OUTPUT: % c = inequality constraints % ceq = equality constraints Var_w = u^2 * lambda * r^2 / ((lambda - 2*r) * (lambda - r)^2) + ... ((1-u)*J_jump)^2 * 4 * p * (1-p); sigmaMax = VaR * sqrt(12) / (sqrt(lambda) * norminv(1-alpha)); c = Var_w - sigmaMax^2; ceq = []; end % confuneq
github
skiamu/Thesis-master
pfDESext2.m
.m
Thesis-master/MatlabCode/DiscreteEvent/pfDESext2.m
1,739
utf_8
2212bf7c1a32658397bcba96b5044092
function [ f ] = pfDESext2(z,x,u,J_jump,param) %pfDESext2 computes the density function of the random variable x(k+1) %(portdolio value at event number k+1) % INPUT: % z = indipendent variable % x = portfolio value last event % u = cash weigth % J_jump = jump treshold % param = struct of model parameters % OUTPUT: % f = density computed in z % 1) extract parameters a = param.a; b = param.b; sigma = param.sigma; % vasicek parameters p = param.p; lambda = param.lambda; % basic parameters r0 = 0.055; % initial point % 2) define mean and std for Integrated O-U r.v. mu_tilde = @(t) ((r0 - b) * (1 - exp(-a * t)) + a * b * t) / a; sigma_tilde = @(t) sqrt(sigma^2 / (2 * a^3) * (2 * a * t + 4 * exp(-a * t) - ... exp(-2 * a * t) - 3)); % 3) tau density f_tau = @(t) lambda * exp(-lambda * t); f = zeros(size(z)); csi = x * J_jump * u; idx1 = z >= x + csi; idx2 = z >= x - csi; t = (-2:0.001/2:2)'; % 4) compute t-integrals if ~isempty(z(idx1)) psi = @(t,z) Integrand(exp(t - exp(-t)),z,f_tau,-1,mu_tilde,sigma_tilde,csi,x) .* ... exp(t - exp(-t)) .* (1+exp(-t)); f(idx1) = p ./ (z(idx1) - csi) .* trapz(t,psi(t,z(idx1))); end if ~isempty(z(idx2)) psi = @(t,z) Integrand(exp(t - exp(-t)),z,f_tau,1,mu_tilde,sigma_tilde,csi,x) .* ... exp(t - exp(-t)) .* (1+exp(-t)); f(idx2) = f(idx2) + (1-p) ./ (z(idx2) + csi) .* trapz(t,psi(t,z(idx2))); end end % pfDES function I = Integrand(t,z,f_tau,sign,mu_tilde,sigma_tilde,csi,x) sigma_tilde = sigma_tilde(t); t = t(sigma_tilde>0); % keep only times where sigma_tilde is not zero I = sparse((exp(-0.5 * ((log((z + sign * csi) / x) - mu_tilde(t)) ./ sigma_tilde).^2 )... ./ (sqrt(2*pi) * sigma_tilde) ) .* (f_tau(t))); end % * ones([1 length(z)]))
github
skiamu/Thesis-master
hHistoricalVaRES.m
.m
Thesis-master/MatlabCode/DiscreteEvent/hHistoricalVaRES.m
999
utf_8
491ba88c820baf2bac94ad3f383c547a
function [VaR,ES] = hHistoricalVaRES(Sample,VaRLevel) % Compute historical VaR and ES % See [4] for technical details % Convert to losses Sample = -Sample; N = length(Sample); k = ceil(N*VaRLevel); z = sort(Sample); VaR = z(k); if k < N ES = ((k - N*VaRLevel)*z(k) + sum(z(k+1:N)))/(N*(1 - VaRLevel)); else ES = z(k); end end function [VaR,ES] = hNormalVaRES(Mu,Sigma,VaRLevel) % Compute VaR and ES for normal distribution % See [3] for technical details VaR = -1*(Mu-Sigma*norminv(VaRLevel)); ES = -1*(Mu-Sigma*normpdf(norminv(VaRLevel))./(1-VaRLevel)); end function [VaR,ES] = hTVaRES(DoF,Mu,Sigma,VaRLevel) % Compute VaR and ES for t location-scale distribution % See [3] for technical details VaR = -1*(Mu-Sigma*tinv(VaRLevel,DoF)); ES_StandardT = (tpdf(tinv(VaRLevel,DoF),DoF).*(DoF+tinv(VaRLevel,DoF).^2)./((1-VaRLevel).*(DoF-1))); ES = -1*(Mu-Sigma*ES_StandardT); end
github
skiamu/Thesis-master
ODAAalgorithmDES.m
.m
Thesis-master/MatlabCode/DiscreteEvent/ODAAalgorithmDES.m
3,678
utf_8
6feb0598ee92c683c985d764210dc47a
function [U,J] = ODAAalgorithmDES(N,X,J_jump,param,model) %DPalgorithm implements a Dynamic Programming algorithm to solve a %stochastic reachability problem % INPUT: % N = number of events % M = dimension asset allocation (e.g. ) % X = cell array of discretized target sets, to access the i-th % element use X{i} % J_jump = jump size % param = struct of parameters % OUTPUT: % U = cell array of asset allocations % J = cell array of optial value functions %% initialization U = cell([N 1]); % asset allocation cell array J = cell([N+1 1]); % optimal value function cell array J{end} = ones([length(X{end}) 1]); % indicator function target set X_N options = optimoptions(@fmincon,'Algorithm','active-set','Display','off'); lb = -1; ub = 1; % short positions on the risky asset are allowed eta = 1e-4/3; % integretion interval discretization step (1e-4/2 for ext1) if strcmp(model,'ext1') % risk constraint ext1 global VarTau ExpValue_tau; mu = param.mu; sigma=param.sigma;mu_tilde = mu-0.5*sigma^2; a = @(n) 0.5 * mu_tilde^2 / sigma^2 + sigma^2 * n.^2 * pi^2 / (8 * J_jump^2); epsilon = 1e-8; N1 = ceil(((8*J_jump^2/(sigma^2*pi^2))^3/(epsilon*4))^(1/4)); NN1 = 1:N1; N2 = ceil(((8*J_jump^2/(sigma^2*pi^2))^2/(epsilon*2))^(1/2)); NN2 = 1:N2; ExpValue_tau2 = 2*cosh(mu_tilde*J_jump/sigma^2)*sigma^2*pi/(4*J_jump^2)*... sum(2*NN1.*(-1).^(NN1+1)./a(NN1).^3 .*sin(NN1*pi/2)); ExpValue_tau = 2*cosh(mu_tilde*J_jump/sigma^2)*sigma^2*pi/(4*J_jump^2)*... sum(NN2.*(-1).^(NN2+1)./a(NN2).^2 .*sin(NN2*pi/2)); VarTau = ExpValue_tau2 - ExpValue_tau^2; end %% optimization for k = N : -1 : 1 k % print current iteration dimXk = length(X{k}); % number of single optimizations Uk = zeros([dimXk 1]); Jk = zeros([dimXk 1]); int_domain = (X{k+1}(1):eta:X{k+1}(end))'; % integretion domain with more points Jinterp = interp1(X{k+1},J{k+1},int_domain); if k ~= 1 u0 = -1; % initial condition else u0 = 1; end for j = dimXk:-1:1 j % print current iteration [Uk(j),Jk(j)] = fmincon(@(u) -objfun(u,X{k}(j),int_domain,Jinterp,param,J_jump,model),... u0,[],[],[],[],lb,ub,[],options); u0 = Uk(j) end U{k} = Uk; J{k} = -Jk; % print allocation maps if k ~= 1 idx = find(X{k} <= 3 & X{k} >= 0.1); figure area(X{k}(idx),U{k}(idx)) title(strcat('k = ',num2str(k-1))) % saveas(gcf,[pwd strcat('/Latex/secondWIP/k',num2str(k-1),model,'.png')]); end end end function f = objfun(u,x,int_domain,J,param,J_jump,model) %objfun defines the problem's objective function that will be maximized % INPUT: % u = asset allocation vector % x = realization portfolio value [scalar] % int_domain = integration domain, k+1 target set discretized % J = k+1-th optimal value function % J_jump = jump size % param = struct of parameters % OUTPUT: % f = objective function switch model case 'basic' f = trapz(int_domain, J .* pfDES(int_domain,x,u,J_jump,param)); case 'ext1' f = trapz(int_domain, J .* pfDESext1(int_domain,x,u,J_jump,param)); case 'ext2' f = trapz(int_domain', J' .* pfDESext2(int_domain',x,u,J_jump,param)); end end % objfun function [c, ceq] = constr(u,param,J_jump,model) alpha = 0.01; VaR_m = 0.07; if strcmp(model,'basic') r = param.r; lambda = param.lambda; p = param.p; sigma_max = sqrt(12) * VaR_m / (sqrt(lambda) * norminv(1-alpha)); c = lambda * r^2 / ((lambda-2*r)*(lambda-r)^2) + (u*J_jump)^2 *... 4*p*(1-p) - sigma_max^2; else % ext1 model global VarTau ExpValue_tau; r = param.r; p = param.p; sigma_max = VaR_m * sqrt(12*ExpValue_tau) / norminv(1-alpha); c = r^2*VarTau + u^2*4*J_jump^2*p*(1-p) - sigma_max^2; end ceq = []; end
github
skiamu/Thesis-master
pfDESext1.m
.m
Thesis-master/MatlabCode/DiscreteEvent/pfDESext1.m
1,739
utf_8
e693a64f401f789398c751eb4c541064
function [ f ] = pfDESext1(z,x,u,J_jump,param) %pfDES computes the density function of the random variable x(k+1) %(portdolio value at event number k+1) % INPUT: % z = indipendent variable [column vector] % x = portfolio value last event [scalar] % u = cash weigth [scalar] % J_jump = jump treshold % param = struct of model parameters (mu, sigma, r and p) % OUTPUT: % f = density function computed in z f = zeros(size(z)); csi = x * J_jump * u; idx1 = z > x + csi; idx2 = z > x - csi; mu = param.mu; sigma = param.sigma; r = param.r; % extract parameters p = param.p; mu_tilde = mu - 0.5 * sigma^2; if ~isempty(z(idx1)) f(idx1) = p * Gamma((z(idx1) - csi) / x,mu_tilde,sigma,r,J_jump); end if ~isempty(z(idx2)) f(idx2) = f(idx2) + (1-p) * Gamma((z(idx2) + csi) / x,mu_tilde,sigma,r,J_jump); end f = 2 * cosh(mu_tilde * J_jump / sigma^2) / (r * x) * f; end % pfDES function [f] = Gamma(y,mu_tilde,sigma,r,J_jump) % INPUT: % y = (z+-csi) / x (column vector) % x = ptf value % mu_tilde = mu - 0.5 * sigma^2; % sigma = volatility % r = cash yearly return % J_jump = jump size epsilon = 1e-8; arg = epsilon * pi * min(y) * log(min(y)) / r; logArg = log(arg)/log(min(y)); NN = max(1,sqrt(-r*8*J_jump^2/(sigma^2*pi^2)*(mu_tilde^2/(2*r*sigma^2) + logArg))); % N = (1:90); % truncate the series at the 100-th terms global freeMemory if 8 * NN * length(y) * 1e-6 >= freeMemory % check if there's enogh memory f = [0; Gamma(y(2:end),mu_tilde,sigma,r,J_jump)]; else N = 1:NN; f = sigma^2 * pi / (4 * J_jump^2) * (sum(N .* (-1).^(N+1) .* ... y.^(-(mu_tilde^2 / (2 * sigma^2) + (sigma^2 * N.^2 * pi^2) /... (8 * J_jump^2)) / r - 1).* sin(pi * N / 2),2)); end end % Gamma
github
skiamu/Thesis-master
gigrnd.m
.m
Thesis-master/MatlabCode/gigrnd/gigrnd.m
2,979
utf_8
8a1c710aeca0a8b24678eab7c8cdc6fa
%% Implementation of the Devroye (2014) algorithm for sampling from % the generalized inverse Gaussian (GIG) distribution % % function X = gigrnd(p, a, b, sampleSize) % % The generalized inverse Gaussian (GIG) distribution is a continuous % probability distribution with probability density function: % % p(x | p,a,b) = (a/b)^(p/2)/2/besselk(p,sqrt(a*b))*x^(p-1)*exp(-(a*x + b/x)/2) % % Parameters: % p \in Real, a > 0, b > 0 % % See Wikipedia page for properties: % https://en.wikipedia.org/wiki/Generalized_inverse_Gaussian_distribution % % This is an implementation of the Devroye (2014) algorithm for GIG sampling. % % Returns: % X = random variates [sampleSize x 1] from the GIG(p, a, b) % % References: % L. Devroye % Random variate generation for the generalized inverse Gaussian distribution % Statistics and Computing, Vol. 24, pp. 239-246, 2014. % % (c) Copyright Enes Makalic and Daniel F. Schmidt, 2015 function X = gigrnd(P, a, b, sampleSize) %% Setup -- we sample from the two parameter version of the GIG(alpha,omega) lambda = P; omega = sqrt(a*b); alpha = sqrt(omega^2 + lambda^2) - lambda; %% Find t x = -psi(1, alpha, lambda); if((x >= 0.5) && (x <= 2)) t = 1; elseif(x > 2) t = sqrt(2 / (alpha + lambda)); elseif(x < 0.5) t = log(4/(alpha + 2*lambda)); end %% Find s x = -psi(-1, alpha, lambda); if((x >= 0.5) && (x <= 2)) s = 1; elseif(x > 2) s = sqrt(4/(alpha*cosh(1) + lambda)); elseif(x < 0.5) s = min(1/lambda, log(1 + 1/alpha + sqrt(1/alpha^2+2/alpha))); end %% Generation eta = -psi(t, alpha, lambda); zeta = -dpsi(t, alpha, lambda); theta = -psi(-s, alpha, lambda); xi = dpsi(-s, alpha, lambda); p = 1/xi; r = 1/zeta; td = t - r*eta; sd = s - p*theta; q = td + sd; X = zeros(sampleSize, 1); for sample = 1:sampleSize done = false; while(~done) U = rand(1); V = rand(1); W = rand(1); if(U < (q / (p + q + r))) X(sample) = -sd + q*V; elseif(U < ((q + r) / (p + q + r))) X(sample) = td - r*log(V); else X(sample) = -sd + p*log(V); end %% Are we done? f1 = exp(-eta - zeta*(X(sample)-t)); f2 = exp(-theta + xi*(X(sample)+s)); if((W*g(X(sample), sd, td, f1, f2)) <= exp(psi(X(sample), alpha, lambda))) done = true; end end end %% Transform X back to the three parameter GIG(p,a,b) X = exp(X) * (lambda / omega + sqrt(1 + (lambda/omega)^2)); X = X ./ sqrt(a/b); end function f = psi(x, alpha, lambda) f = -alpha*(cosh(x) - 1) - lambda*(exp(x) - x - 1); end function f = dpsi(x, alpha, lambda) f = -alpha*sinh(x) - lambda*(exp(x) - 1); end function f = g(x, sd, td, f1, f2) a = 0; b = 0; c = 0; if((x >= -sd) && (x <= td)) a = 1; elseif(x > td) b = f1; elseif(x < -sd) c = f2; end; f = a + b + c; end
github
skiamu/Thesis-master
VaRGM.m
.m
Thesis-master/MatlabCode/testScript/VaRGM.m
444
utf_8
688c230e304f3d7862d4124134651552
function y = VaRGM(param,u,alpha) y0 = 0.02; y = zeros([1 length(alpha)]); options = optimset('Display','off'); for i = 1 : length(alpha); y(i) = fsolve(@(z) Phi(param,u,z,alpha(i)),y0,options); y0 = y(i); end end % ValueAtRisk function y = Phi(param,u,z,alpha) Phi = 0; for i = 1 : length(param) mu = -u' * param(i).mu; sigma = sqrt(u' * param(i).S * u); Phi = Phi + param(i).lambda * normcdf(-(z - mu) / sigma); end y = Phi - alpha; end
github
skiamu/Thesis-master
MCECMalgorithm.m
.m
Thesis-master/MatlabCode/GHcalibration/MCECMalgorithm.m
5,200
utf_8
068e4519b02786566c98b824c8274b25
function [param,CalibrationData] = MCECMalgorithm(toll,maxiter,X,GHmodel) %MCECMalgorithm implements a modified version of the EM algorithm for %fitting a Generalized Hyperbolic Distribution % INPUT: % toll = stopping tolerance % maxiter = maximum number of iterations % X = returns data % GHmodel = 'GH', 'H', 'NIG' % OUTPUT: % param = % CalibrationData = % REMARKS: scrivere la funzione obiettivo Q2 anke per gli altri modelli exitFlag = 'maxiter'; % 1) set initial conditions [N, d] = size(X); [mu,Sigma,gamma,lambda,alpha_bar] = InitialConditions(X,d); X_bar = mean(X); theta = cell([maxiter 1]); theta{1} = {lambda,alpha_bar,mu,Sigma,gamma}; Q2 = zeros([maxiter 1]); for k = 2 : maxiter k % 2) Compute delta, eta [delta,eta] = ComputeWeight(lambda,alpha_bar,d,X,mu,Sigma,gamma); deltaMean = sum(delta) / N; etaMean = sum(eta) / N; % 3) update gamma gamma = (sum(delta * ones([1 d]) .* (repmat(X_bar,[N 1]) - X))' / N) / ... (deltaMean * etaMean - 1); % 4) update mu and Sigma mu = (sum(delta * ones([1 d]) .* X)' / N - gamma) / deltaMean; D = 0; for i = 1 : N D = D + delta(i) * (X(i,:)' - mu) * (X(i,:)' - mu)'; end D = D/N - etaMean * (gamma * gamma'); Sigma = D; % 5) update the weights with new mu,sigma and gamma [delta,eta,csi] = ComputeWeight(lambda,alpha_bar,d,X,mu,Sigma,gamma); % 6) maximize Q2(lambda,Chi,Psi) options = optimoptions(@fmincon,'Algorithm','sqp','Display','off'); x0 = [lambda;alpha_bar]; [A,b,Aeq,beq] = confuneq(GHmodel,d); [x_star,f_star] = fmincon(@(x)objfun(x,delta,eta,csi,GHmodel), ... x0,A,b,Aeq,beq,[],[],[],options); Q2(k) = -f_star; lambda = x_star(1); alpha_bar = x_star(2); % go the to the first parametrization Psi = alpha_bar * besselk(lambda+1,alpha_bar) / besselk(lambda,alpha_bar); Chi = alpha_bar^2 / Psi; % 7) check conditions theta{k} = {lambda,alpha_bar,mu,Sigma,gamma}; if checkCondition(toll,theta,k,Q2) exitFlag = 'condition'; numIter = k; LogL = LogLikelihood(X,lambda,Chi,Psi,mu,Sigma,gamma); theta{k}{end+1} = Chi; theta{k}{end+1} = Psi; break end numIter = k; LogL = LogLikelihood(X,lambda,Chi,Psi,mu,Sigma,gamma); theta{k}{end+1} = Chi; theta{k}{end+1} = Psi; end % 8) build the param struct param.lambda = theta{numIter}{1}; param.alpha = theta{numIter}{2}; param.mu = theta{numIter}{3}; param.sigma = theta{numIter}{4}; param.gamma = theta{numIter}{5}; param.Chi = theta{numIter}{6}; param.Psi = theta{numIter}{7}; if strcmp(GHmodel,{'NIG','H'}) nParam = 1 + d + d*(d+1) / 2 + d; %NIG else nParam = 1 + 1 + d + d*(d+1) / 2 + d; end AIC = -2 * LogL + 2 * nParam; % 9) return calibration information CalibrationData.LogL = LogL; CalibrationData.ExitFlag = exitFlag; CalibrationData.numIter = numIter; CalibrationData.AIC = AIC; end % MCECMalgorithm function [delta,eta,csi] = ComputeWeight(lambda,alpha_bar,d,X,mu,Sigma,gamma) %ComputeWeight is a function for computing the weigths delta, eta and csi. %See formulas in the theory for analitic expression % INPUT: % OUTPUT: % % recover Chi and Psi from alpha_bar Psi = alpha_bar * besselk(lambda+1,alpha_bar) / besselk(lambda,alpha_bar); Chi = alpha_bar^2 / Psi; [N,~] = size(X); % 1) compute lambda_bar, Psi_bar and Chi_bar according to the model NIG, % generelized hyperbolic and hyperbolic lambda_bar = lambda - 0.5 * d; invSigma = inv(Sigma); Psi_bar = gamma' * invSigma * gamma + Psi; Chi_bar = zeros([N 1]); for i = 1 : N % check if Sigma is the right matrix Chi_bar(i) = (X(i,:)' - mu)' * invSigma * (X(i,:)' - mu); end Chi_bar = Chi_bar + Chi; % 2) compute weights delta = (Chi_bar / Psi_bar).^(-0.5) .* besselk(lambda_bar-1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); eta = (Chi_bar / Psi_bar).^(0.5) .* besselk(lambda_bar+1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); if nargout > 2 h = 0.001; csi = ((Chi_bar / Psi_bar).^(h/2) .* besselk(lambda_bar+h,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)) - 1) / h; end end %ComputeWeight function condition = checkCondition(toll,theta,k,Q2) % REMARK: set different tollerance [N,~] = size(theta{k}); diff = zeros([N 1]); for i = 1 : N diff(i) = norm(theta{k}{i}-theta{k-1}{i}); end if (all(diff) < toll && norm(Q2(k) - Q2(k-1)) < toll) condition = true; else condition = false; end end % checkCondition function f = LogLikelihood(X,lambda,Chi,Psi,mu,Sigma,Gamma) %LogLikelihood computed the loglikelihood function at maximum % INPUT: % OUTPUT: [N, d] = size(X); f = 0; invSigma = inv(Sigma); c = sqrt(Chi*Psi)^(-lambda) * Psi^lambda * (Psi+Gamma'*invSigma*Gamma)^(0.5*d - lambda) / ... ((2*pi)^(d/2) * sqrt(det(Sigma)) * besselk(lambda,sqrt(Chi*Psi))); for i = 1 : N x = X(i,:)'; factor = sqrt((Chi + (x - mu)'*invSigma*(x - mu)) * (Psi + Gamma'*invSigma*Gamma)); density = c * besselk(lambda-d/2,factor) .* exp((x-mu)'*invSigma*Gamma) ./ ... (factor).^(d/2 - lambda); f = f + log(density); end end % density function [mu,Sigma,gamma,lambda,alpha_bar] = InitialConditions(X,d) X_bar = mean(X); mu = X_bar'; Sigma = cov(X); lambda = 1; alpha_bar = 1; gamma = zeros([d 1]); end % initial conditions
github
skiamu/Thesis-master
MCECMalgorithm_t.m
.m
Thesis-master/MatlabCode/GHcalibration/MCECMalgorithm_t.m
4,701
utf_8
e4b1bcecdb92c3542591525f7c306250
function [param, CalibrationData] = MCECMalgorithm_t(toll,maxiter,X,GHmodel) %MCECMalgorithm implements a modified version of the EM algorithm for %fitting a Generalized Hyperbolic Distribution % INPUT: % toll = stopping tolerance % maxiter = maximum number of iterations % X = returns data % GHmodel = 't', 'VG', 'NIG' % OUTPUT: % param = % CalibrationData = % REMARKS: scrivere la funzione obiettivo Q2 anke per gli altri modelli exitFlag = 'maxiter'; % 1) set initial conditions [N, d] = size(X); [mu,Sigma,gamma,lambda] = InitialConditions(X,d); X_bar = mean(X); theta = cell([maxiter 1]); theta{1} = {lambda,mu,Sigma,gamma}; Q2 = zeros([maxiter 1]); for k = 2 : maxiter k % 2) Compute delta, eta [delta,eta] = ComputeWeight(lambda,d,X,mu,Sigma,gamma); deltaMean = sum(delta) / N; etaMean = sum(eta) / N; % 3) update gamma gamma = (sum(delta * ones([1 d]) .* (repmat(X_bar,[N 1]) - X))' / N) / ... (deltaMean * etaMean - 1); % 4) update mu and Sigma mu = (sum(delta * ones([1 d]) .* X)' / N - gamma) / deltaMean; D = 0; for i = 1 : N D = D + delta(i) * (X(i,:)' - mu) * (X(i,:)' - mu)'; end D = D/N - etaMean * (gamma * gamma'); Sigma = D; % 5) update the weights with new mu,sigma and gamma [delta,eta,csi] = ComputeWeight(lambda,d,X,mu,Sigma,gamma); % 6) maximize Q2(lambda,Chi,Psi) options = optimoptions(@fmincon,'Algorithm','sqp','Display','off'); x0 = lambda; [A,b,Aeq,beq] = confuneq(GHmodel,d); [x_star,f_star] = fmincon(@(x)objfun(x,delta,eta,csi,GHmodel), ... x0,A,b,Aeq,beq,[],[],[],options); Q2(k) = -f_star; lambda = x_star; % go the to the first parametrization nu = -2 * lambda; % 7) check conditions theta{k} = {lambda,mu,Sigma,gamma}; if checkCondition(toll,theta,k,Q2) exitFlag = 'condition'; numIter = k; LogL = LogLikelihood(X,lambda,mu,Sigma,gamma); theta{k}{end+1} = nu; break end numIter = k; LogL = LogLikelihood(X,lambda,mu,Sigma,gamma); theta{k}{end+1} = nu; end % 8) build the param struct param.lambda = theta{numIter}{1}; param.mu = theta{numIter}{2}; param.sigma = theta{numIter}{3}; param.gamma = theta{numIter}{4}; param.nu = theta{numIter}{5}; nParam = 1 + d + d*(d+1) / 2 + d; % t AIC = -2 * LogL + 2 * nParam; % 9) return calibration information CalibrationData.LogL = LogL; CalibrationData.ExitFlag = exitFlag; CalibrationData.numIter = numIter; CalibrationData.AIC = AIC; end % MCECMalgorithm_t function [delta,eta,csi] = ComputeWeight(lambda,d,X,mu,Sigma,gamma) %ComputeWeight is a function for computing the weigths delta, eta and csi. %See formulas in the theory for analitic expression % INPUT: % OUTPUT: % % recover Chi and Psi from alpha_bar nu = -2 * lambda; Chi = nu - 2; Psi = 0; [N,~] = size(X); % 1) compute lambda_bar, Psi_bar and Chi_bar according to the model NIG, % generelized hyperbolic and hyperbolic lambda_bar = lambda - 0.5 * d; invSigma = inv(Sigma); Psi_bar = gamma' * invSigma * gamma + Psi; Chi_bar = zeros([N 1]); for i = 1 : N % check if Sigma is the right matrix Chi_bar(i) = (X(i,:)' - mu)' * invSigma * (X(i,:)' - mu); end Chi_bar = Chi_bar + Chi; % 2) compute weights delta = (Chi_bar / Psi_bar).^(-0.5) .* besselk(lambda_bar-1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); eta = (Chi_bar / Psi_bar).^(0.5) .* besselk(lambda_bar+1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); if nargout > 2 h = 0.001; csi = ((Chi_bar / Psi_bar).^(h/2) .* besselk(lambda_bar+h,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)) - 1) / h; end end %ComputeWeight function f = LogLikelihood(X,lambda,mu,Sigma,Gamma) %LogLikelihood computed the loglikelihood function at maximum % INPUT: % OUTPUT: [N, d] = size(X); f = 0; invSigma = inv(Sigma); nu = -2*lambda; % degrees of freedom c = (nu-2)^(nu/2) * (Gamma'*invSigma*Gamma)^((nu+d)/2) / ... ((2*pi)^(d/2)*sqrt(det(Sigma))*gamma(nu/2)*2^(nu/2-1)); for i = 1 : N x = X(i,:)'; factor = sqrt((nu - 2 + (x-mu)'*invSigma*(x-mu)) * Gamma'*invSigma*Gamma); density = c * besselk((nu+d)/2,factor) .* exp((x-mu)'*invSigma*Gamma) ./ ... factor.^((nu + d)/2); f = f + log(density); end end % density function condition = checkCondition(toll,theta,k,Q2) % REMARK: set different tollerance [N,~] = size(theta{k}); diff = zeros([N 1]); for i = 1 : N diff(i) = norm(theta{k}{i}-theta{k-1}{i}); end if (all(diff) < toll && norm(Q2(k) - Q2(k-1)) < toll) condition = true; else condition = false; end end % checkCondition function [mu,Sigma,gamma,lambda] = InitialConditions(X,d) X_bar = mean(X); mu = X_bar'; Sigma = cov(X); lambda = -2; gamma = ones([d 1])/1e5; end % initial conditions
github
skiamu/Thesis-master
MCECMalgorithm2.m
.m
Thesis-master/MatlabCode/GHcalibration/MCECMalgorithm2.m
7,110
utf_8
d1a1cbf9251f4b03d3d13ab18a2e705f
function [theta,LogL,exitFlag,numIter] = MCECMalgorithm2(toll,maxiter,X,GHmodel) %MCECMalgorithm implements a modified version of the EM algorithm for %fitting a Generalized Hyperbolic Distribution % INPUT: % toll = stopping tolerance % maxiter = maximum number of iterations % X = returns data % GHmodel = 't', 'VG', 'NIG' % OUTPUT: % theta = cell array of parameters % LogL = log-likelihood at optimum % exitFlag = 'maxiter' or 'condition' % numIter = number of algorithm iterations % REMARKS: scrivere la funzione obiettivo Q2 anke per gli altri modelli exitFlag = 'maxiter'; % 1) set initial conditions [N, d] = size(X); [mu,Sigma,gamma,lambda,Chi,Psi] = InitialConditions(X,GHmodel,d); X_bar = mean(X); theta = cell([maxiter 1]); theta{1} = {lambda,Chi,Psi,mu,Sigma,gamma}; Q2 = zeros([maxiter 1]); for k = 2 : maxiter k % 2) Compute delta, eta [delta,eta] = ComputeWeight(lambda,Chi,Psi,d,X,mu,Sigma,gamma,GHmodel); deltaMean = sum(delta) / N; etaMean = sum(eta) / N; % 3) update gamma gamma = (sum(delta * ones([1 d]) .* (repmat(X_bar,[N 1]) - X))' / N) / ... (deltaMean * etaMean - 1); % 4) update mu and Sigma mu = (sum(delta * ones([1 d]) .* X)' / N - gamma) / deltaMean; D = 0; for i = 1 : N D = D + delta(i) * (X(i,:)' - mu) * (X(i,:)' - mu)'; end D = D/N - etaMean * (gamma * gamma'); Sigma = det(Sigma)^(1/d) * D / det(D)^(1/d); % take the root with lowest phase, complex % Sigma = nthroot(det(Sigma),d) * D / nthroot(det(D),d); % 5) update the weights [delta,eta,csi] = ComputeWeight(lambda,Chi,Psi,d,X,mu,Sigma,gamma,GHmodel); % 6) maximize Q2(lambda,Chi,Psi) options = optimoptions(@fmincon,'Algorithm','sqp','Display','off'); x0 = [lambda;Chi;Psi]; [A,b,Aeq,beq] = confuneq(GHmodel); [x_star,f_star] = fmincon(@(x)objfun(x,delta,eta,csi,GHmodel), ... x0,A,b,Aeq,beq,[],[],[],options); Q2(k) = -f_star; lambda = x_star(1); Chi = x_star(2); Psi = x_star(3); % 7) check conditions theta{k} = {lambda,Chi,Psi,mu,Sigma,gamma}; if checkCondition(toll,theta,k,Q2) exitFlag = 'condition'; numIter = k; LogL = LogLikelihood(X,lambda,Chi,Psi,mu,Sigma,gamma,GHmodel); break end numIter = k; LogL = LogLikelihood(X,lambda,Chi,Psi,mu,Sigma,gamma,GHmodel); end end % MCECMalgorithm function [delta,eta,csi] = ComputeWeight(lambda,Chi,Psi,d,X,mu,Sigma,gamma,GHmodel) %ComputeWeight is a function for computing the weigths delta, eta and csi. %See formulas in the theory for analitic expression % INPUT: % OUTPUT: % [N,~] = size(X); % 1) compute lambda_bar, Psi_bar and Chi_bar according to the model lambda_bar = lambda - 0.5 * d; invSigma = inv(Sigma); Psi_bar = gamma' * invSigma * gamma; Chi_bar = zeros([N 1]); for i = 1 : N % check if Sigma is the right matrix Chi_bar(i) = (X(i,:)' - mu)' * invSigma * (X(i,:)' - mu); end switch GHmodel case 't' Chi_bar = Chi_bar + Chi; case 'VG' Psi_bar = Psi + Psi_bar; otherwise % NIG, general case Psi_bar = Psi_bar + Psi; Chi_bar = Chi_bar + Chi; end % 2) compute weights delta = (Chi_bar / Psi_bar).^(-0.5) .* besselk(lambda_bar-1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); eta = (Chi_bar / Psi_bar).^(0.5) .* besselk(lambda_bar+1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); if nargout > 2 h = 0.001; csi = ((Chi_bar / Psi_bar).^(h/2) .* besselk(lambda_bar+h,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)) - 1) / h; end end %ComputeWeight function f = objfun(x,delta,eta,csi,GHmodel) %objfun is the objective function Q2 for the maximization problem % INPUT: % x = vector of parameters, [lambda,Chi,Psi] % delta = % eta = % csi = % OUTPUT: % f = % REMARKS: different objective function for 't' and 'VG' [N, ~] = size(delta); switch GHmodel case 't' f = -x(1) * N * log(x(2) / 2) - N * log(gamma(-x(1))) + (x(1)-1) * sum(csi) - ... 0.5 * x(2) * sum(delta); case 'VG' f = x(1) * N * log(x(3) / 2) - N * log(gamma(x(1))) + (x(1) - 1) * sum(csi) - ... 0.5 * x(3) * sum(eta); otherwise f = (x(1)-1) * sum(csi) - 0.5 * x(2) * sum(delta) - 0.5 * x(3) * sum(eta) -... 0.5 * N * x(1) * log(x(2)) + 0.5 * N * x(1) * log(x(3)) - ... N * log(2 * besselk(x(1),sqrt(x(2) * x(3)))); end f = - f; % maximization problem end % objfun function [A,b,Aeq,beq] = confuneq(GHmodel) %confuneq is a function for setting the constraint for the maximization %problem % INPUT: % OUTPUT: switch GHmodel case 'NIG' % lambda = 0.5 A = [0 -1 0; 0 0 -1]; b = [eps; 0]; Aeq = [1 0 0]; beq = -0.5; case 'VG' % Chi = 0, Psi > 0 lambda > 0 A = [-1 0 0; 0 0 -1]; b = [eps; eps]; Aeq = [0 1 0]; beq = 0; case 't' % lambda < 0, Psi = 0, Chi > 0 Aeq = [0 0 1]; beq = 0; A = [0 -1 0; 1 0 0]; b = [eps; eps]; otherwise Aeq = []; beq = []; A = [0 -1 0; 0 0 -1]; b = [eps; eps]; end end % objfun function condition = checkCondition(toll,theta,k,Q2) % REMARK: set different tollerance [N,~] = size(theta{k}); diff = zeros([N 1]); for i = 1 : N diff(i) = norm(theta{k}{i}-theta{k-1}{i}); end if all(diff) < toll && norm(Q2(k) - Q2(k-1)) < toll condition = true; else condition = false; end end % checkCondition function f = LogLikelihood(X,lambda,Chi,Psi,mu,Sigma,Gamma,GHmodel) %LogLikelihood computed the loglikelihood function at maximum % INPUT: % OUTPUT: [N, d] = size(X); f = 0; invSigma = inv(Sigma); switch GHmodel case 't' nu = -2*lambda; % degrees of freedom c = (nu-2)^(nu/2) * (Gamma'*invSigma*Gamma)^((nu+d)/2) / ... ((2*pi)^(d/2)*sqrt(det(Sigma))*gamma(nu/2)*2^(nu/2-1)); for i = 1 : N x = X(i,:)'; factor = sqrt((nu - 2 + (x-mu)'*invSigma*(x-mu)) * Gamma'*invSigma*Gamma); density = c * besselk((nu+d)/2,factor) .* exp((x-mu)'*invSigma*Gamma) ./ ... factor.^((nu + d)/2); f = f + log(density); end case 'VG' c = 2*lambda^(lambda)*(2*lambda+Gamma'*invSigma*Gamma)^(d/2-lambda) / ... ((2*pi)^(d/2)*sqrt(det(Sigma))*gamma(lambda)); for i = 1 : N x = X(i,:)'; factor = sqrt((x-mu)'*invSigma*(x-mu)*(2*lambda + Gamma'*invSigma*Gamma)); density = c * besselk(lambda-d/2,factor) .* exp((x-mu)'*invSigma*Gamma) ./ ... factor.^(d/2 - lambda); f = f + log(density); end otherwise % NIG, general case c = sqrt(Chi*Psi)^(-lambda) * Psi^lambda * (Psi+Gamma'*invSigma*Gamma)^(0.5*d - lambda) / ... ((2*pi)^(d/2) * sqrt(det(Sigma)) * besselk(lambda,sqrt(Chi*Psi))); for i = 1 : N x = X(i,:)'; factor = sqrt((Chi + (x - mu)'*invSigma*(x - mu)) * (Psi + Gamma'*invSigma*Gamma)); density = c * besselk(lambda-d/2,factor) .* exp((x-mu)'*invSigma*Gamma) ./ ... (factor).^(d/2 - lambda); f = f + log(density); end end end % density function [mu,Sigma,gamma,lambda,Chi,Psi] = InitialConditions(X,GHmodel,d) X_bar = mean(X); mu = X_bar'; Sigma = cov(X); switch GHmodel case 't' gamma = ones([d 1])/1e5; lambda = -0.5; Chi = 0.7; Psi = 0.7; case 'VG' gamma = zeros([d 1]); lambda = 1; Chi = 0; Psi = 0.7; otherwise gamma = zeros([d 1]); lambda = 0.5; Chi = 0.7; Psi = 0.7; end end % initial conditions
github
skiamu/Thesis-master
MCECMalgorithm_VG.m
.m
Thesis-master/MatlabCode/GHcalibration/MCECMalgorithm_VG.m
4,360
utf_8
b8fca6ce4918a5f23d0144bcb5206e68
function [theta,LogL,exitFlag,numIter] = MCECMalgorithm_VG(toll,maxiter,X,GHmodel) %MCECMalgorithm implements a modified version of the EM algorithm for %fitting a Generalized Hyperbolic Distribution % INPUT: % toll = stopping tolerance % maxiter = maximum number of iterations % X = returns data % GHmodel = 't', 'VG', 'NIG' % OUTPUT: % theta = cell array of parameters % LogL = log-likelihood at optimum % exitFlag = 'maxiter' or 'condition' % numIter = number of algorithm iterations % REMARKS: in questo caso ci sono problemi numerici, controllare dispense % introduttive del pacchetto ghyp per capire il motivo e sistemare anke se % non fondamentale exitFlag = 'maxiter'; % 1) set initial conditions [N, d] = size(X); [mu,Sigma,gamma,lambda] = InitialConditions(X,d); X_bar = mean(X); theta = cell([maxiter 1]); theta{1} = {lambda,mu,Sigma,gamma}; Q2 = zeros([maxiter 1]); for k = 2 : maxiter k % 2) Compute delta, eta [delta,eta] = ComputeWeight(lambda,d,X,mu,Sigma,gamma); deltaMean = sum(delta) / N; etaMean = sum(eta) / N; % 3) update gamma gamma = (sum(delta * ones([1 d]) .* (repmat(X_bar,[N 1]) - X))' / N) / ... (deltaMean * etaMean - 1); % 4) update mu and Sigma mu = (sum(delta * ones([1 d]) .* X)' / N - gamma) / deltaMean; D = 0; for i = 1 : N D = D + delta(i) * (X(i,:)' - mu) * (X(i,:)' - mu)'; end D = D/N - etaMean * (gamma * gamma'); Sigma = D; % 5) update the weights with new mu,sigma and gamma [delta,eta,csi] = ComputeWeight(lambda,d,X,mu,Sigma,gamma); % 6) maximize Q2(lambda,Chi,Psi) options = optimoptions(@fmincon,'Algorithm','sqp','Display','off'); x0 = lambda; [A,b,Aeq,beq] = confuneq(GHmodel,d); [x_star,f_star] = fmincon(@(x)objfun(x,delta,eta,csi,GHmodel), ... x0,A,b,Aeq,beq,[],[],[],options); Q2(k) = -f_star; lambda = x_star % 7) check conditions theta{k} = {lambda,mu,Sigma,gamma}; if checkCondition(toll,theta,k,Q2) exitFlag = 'condition'; numIter = k; LogL = LogLikelihood(X,lambda,mu,Sigma,gamma); break end numIter = k; LogL = LogLikelihood(X,lambda,mu,Sigma,gamma); end end % MCECMalgorithm function [delta,eta,csi] = ComputeWeight(lambda,d,X,mu,Sigma,gamma) %ComputeWeight is a function for computing the weigths delta, eta and csi. %See formulas in the theory for analitic expression % INPUT: % OUTPUT: % % recover Chi and Psi from alpha_bar Psi = 2 * lambda; Chi = 0; [N,~] = size(X); % 1) compute lambda_bar, Psi_bar and Chi_bar according to the model NIG, % generelized hyperbolic and hyperbolic lambda_bar = lambda - 0.5 * d invSigma = inv(Sigma); Psi_bar = gamma' * invSigma * gamma + Psi; Chi_bar = zeros([N 1]); for i = 1 : N % check if Sigma is the right matrix Chi_bar(i) = (X(i,:)' - mu)' * invSigma * (X(i,:)' - mu); end Chi_bar = Chi_bar + Chi; % 2) compute weights delta = (Chi_bar / Psi_bar).^(-0.5) .* besselk(lambda_bar-1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); eta = (Chi_bar / Psi_bar).^(0.5) .* besselk(lambda_bar+1,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)); if nargout > 2 h = 0.001; csi = ((Chi_bar / Psi_bar).^(h/2) .* besselk(lambda_bar+h,sqrt(Chi_bar * Psi_bar)) ./ ... besselk(lambda_bar,sqrt(Chi_bar * Psi_bar)) - 1) / h; end end %ComputeWeight function f = LogLikelihood(X,lambda,mu,Sigma,Gamma) %LogLikelihood computed the loglikelihood function at maximum % INPUT: % OUTPUT: [N, d] = size(X); f = 0; invSigma = inv(Sigma); c = 2*lambda^(lambda)*(2*lambda+Gamma'*invSigma*Gamma)^(d/2-lambda) / ... ((2*pi)^(d/2)*sqrt(det(Sigma))*gamma(lambda)); for i = 1 : N x = X(i,:)'; factor = sqrt((x-mu)'*invSigma*(x-mu)*(2*lambda + Gamma'*invSigma*Gamma)); density = c * besselk(lambda-d/2,factor) .* exp((x-mu)'*invSigma*Gamma) ./ ... factor.^(d/2 - lambda); f = f + log(density); end end % density function condition = checkCondition(toll,theta,k,Q2) % REMARK: set different tollerance [N,~] = size(theta{k}); diff = zeros([N 1]); for i = 1 : N diff(i) = norm(theta{k}{i}-theta{k-1}{i}); end if (all(diff) < toll && norm(Q2(k) - Q2(k-1)) < toll) condition = true; else condition = false; end end % checkCondition function [mu,Sigma,gamma,lambda] = InitialConditions(X,d) X_bar = mean(X); mu = X_bar'; Sigma = cov(X); lambda = 0.5; gamma = zeros([d 1]); end % initial conditions
github
skiamu/Thesis-master
MethodofMomentsGM.m
.m
Thesis-master/MatlabCode/OldScript/MethodofMomentsGM.m
3,329
utf_8
9713e2182c294e8403ee1fa113093ad2
function [ x, error, lambda, param ] = MethodofMomentsGM( Sample,k,M,SampleFreq ) %MethodofMomentsGM is a function for calibrating a Gaussian Mixture models %by moment metching. It is used when time-series are not available. % INPUT: % Sample = vector of sample moments. Sample = [muC,sigmaC,gammaC,kappaC,... % ...,muE,sigmaE,gammaE,kappaE, rho12,rho13,rho23]. % % k = number of gaussian components % M = dimension % OUTPUT: % x = % error = % REMARKS: data in sample have an annual frequancy, they must be % converted to weekly if strcmp(SampleFreq,'y') Sample([1 5 9]) = (1 + Sample([1 5 9])).^(1/52) - 1; Sample([2 6 10]) = Sample([2 6 10]) / sqrt(52); end eta = 0.01; lambda = 0:eta:1; error = zeros(length(lambda),1); x = zeros(length(lambda),15); lb = [-ones([k*M 1]); zeros([k*M 1]); -ones([3 1])]; ub = [ones([k*M 1]);ones([k*M 1]);ones([3 1])]; % x0 = [0.000611; 0.001373;0.002340;0.000683;-0.016109;-0.017507;0.000069;... % 0.00566;0.019121;0.000062;0.006168;0.052513;0.0633;0.0207;-0.0236]; x0 = rand([15 length(lambda)]); for i = 1 : length(lambda) i [x(i,:), error(i)] = lsqnonlin(@(x) obj(x,Sample,k,M,lambda(i)),x0(:,i),lb,ub); % x0 = x(i,:); end if nargout > 3 [~,idxMin] = min(error); lambda = lambda(idxMin); x = x(idxMin,:); disp(['calibration error = ', num2str(error(idxMin))]); param = cell([k 1]); mu1 = x(1:3); mu2 = x(4:6); sigma1 = x(7:9); sigma2 = x(10:12); Rho = x(13:15); RhoM = [1 Rho(1) Rho(2); Rho(1) 1 Rho(3); Rho(2) Rho(3) 1]; S1 = corr2cov(sigma1,RhoM); S2 = corr2cov(sigma2,RhoM); param{1} = {mu1',S1,lambda}; % traspose since column vector are wanted param{2} = {mu2',S2,1-lambda}; end end %MethodofMomentsGM function F = obj(x,Sample,k,M,lambda) % 1) extract parameters % Mean = [mu1; mu2] Mean = x(1:k*M); Mean = reshape(Mean, [M k])'; % Std = [std1; std2] Std = x(k*M+1:2*k*M) ; Std = reshape(Std, [M k])'; % Rho = [rho12, rho13, rho23] Rho = x(2*k*M+1:end); lambda = [lambda; 1-lambda]; F = zeros(size(x)); % initialization % 2) computes theoretical moments for i = 1 : M mu = Mean(:,i); % first component's means sigma = Std(:,i); % first component's variances [muX,sigmaX,gammaX,kappaX] = ComputeMomentsGM(mu,sigma,lambda); F(1+(i-1)*4:i*4) = [muX;sigmaX;gammaX;kappaX] - Sample(1+(i-1)*4:i*4); end % 3) compute correlations RhoSample = Sample(13:end); RhoM = [1 RhoSample(1) RhoSample(2); RhoSample(1) 1 RhoSample(3); RhoSample(2) RhoSample(3) 1]; Sigma = corr2cov(Sample([2 5 9]),RhoM); k = 13; for i = 1 : 3 for j = 1 : i-1 F(k) = lambda(1) * Rho(k-12) * Std(1,j) * Std(1,i) + lambda(2) * Rho(k-12) * Std(2,j) * Std(2,i) + ... lambda(1) * lambda(2) * (Mean(1,i) - Mean(2,i)) * (Mean(1,j) - Mean(2,j)) - Sigma(i,j); k = k + 1; end end % F = SetConstraints(F,Mean,Std,Rho); end function F = SetConstraints(F,Mean,Std,Rho) % 1) check for unimodality for each marginal Unimodality = zeros([3 1]); for i = 1 : 3 Unimodality(i) = (Mean(1,i)-Mean(2,i))^2 < 27 * Std(1,i)^2 * ... Std(2,i)^2 / (4 * (Std(1,i)^2 + Std(2,i)^2)); end % 2) check for positive-definitness RhoM = [1 Rho(1) Rho(2); Rho(1) 1 Rho(3); Rho(2) Rho(3) 1]; S1 = corr2cov(Std(1,:),RhoM); S2 = corr2cov(Std(2,:),RhoM); [~,p1] = chol(S1); [~,p2] = chol(S2); if any(~Unimodality) || any([p1 p2]) F = 1e10 .* F; end end
github
skiamu/Thesis-master
MethodMomentsGM.m
.m
Thesis-master/MatlabCode/OldScript/MethodMomentsGM.m
2,993
utf_8
ae82ae45286c45748ee84f59cf05d2b4
function [x] = MethodMomentsGM(X) %MethodMomentsGM is a function for the calibration of a Gaussian Mixture %(GM) model by using the method of moments. % INPUT: % X = data matrix (asset class returns) % OUTPUT: % x = vector of parameters [lambda, mu1_1, mu2_1, mu3_1, sigma1_1, % sigma2_1,sigma3_1, mu1_2, mu2_2, mu3_2,sigma1_2, sigma2_2, sigma3_2, % rho12, rho13, rho23] [~, d] = size(X); % 1) compute sample moments C = cov(X); % correlation matrix MM = zeros([5 d]); for i = 1 : 5 MM(i,:) = mean(X.^i); end % 2) solve non-linear system lb = [0, -1, -1, -1, 0, 0, 0, -1, -1, -1, 0, 0, 0, -1, -1, -1]; ub = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; Niter = 50; x0 = 0.1 * randn([16 Niter]); % x = zeros([16 Niter]); % options = optimoptions(@fmincon, 'Algorithm','interior-point'); % for i = 1 : Niter % i % % x(:,i) = fmincon(@(x)0,x0(:,i),[],[],[],[],lb,ub,@(x)fminconstr(x,MM,C),options); % % x(:,i) = fsolve(@(x)fbnd(x,MM,C),x0(:,1)); % [x(:,i),r] = lsqnonlin(@(x)fbnd(x,MM,C),x0(:,i),lb,ub); % r % end [x] = lsqnonlin(@(x)fbnd(x,MM,C),x0(:,1),lb,ub); end % MethodMomentsGM function [c,ceq] = fminconstr(x,MM,C) c = []; % no nonlinear inequality ceq = fbnd(x,MM,C); % the fsolve objective is fmincon constraints end % fminconstr function F = fbnd(x,MM,C) %fbnd sets moment eqiations as constraints of the optimization problem % 1) extract parameters for readability reasons lambda = x(1); mu1_1 = x(2); mu2_1 = x(3); mu3_1 = x(4); sigma1_1 = x(5); sigma2_1 = x(6); sigma3_1 = x(7); mu1_2 = x(8); mu2_2 = x(9); mu3_2 = x(10); sigma1_2 = x(11); sigma2_2 = x(12); sigma3_2 = x(13); rho12 = x(14); rho13 = x(15); rho23 = x(16); % 2) set moment equation k = 0; F = zeros([16 1]); for i = 1 : 3 % for each asset class k = k + 1; mu1 = x(1+i); sigma1 = x(4+i); mu2 = x(7+i); sigma2 = x(10+i); F(k) = lambda * (mu1) + (1-lambda) * (mu2) - MM(1,i); F(k+1) = lambda * (sigma1^2 + mu1^2) + (1-lambda) * (sigma2^2 + mu2^2) - MM(2,i); F(k+2) = lambda * (mu1^3 + 3 * mu1 * sigma1^2) + ... (1-lambda) * (mu2^3 + 3 * mu2 * sigma2^2) - MM(3,i); F(k+3) = lambda * (mu1^4 + 6 * mu1^2 * sigma1^2 + 3 * sigma1^4) + ... (1-lambda) * (mu2^4 + 6 * mu2^2 * sigma2^2 + 3 * sigma2^4) - MM(4,i); end % 3) set correlation equations F(13) = lambda * rho12 * sigma1_1 * sigma2_1 + (1-lambda) * rho12 * sigma1_2 * sigma2_2 + ... lambda * (1-lambda) * (mu1_1 - mu1_2) * (mu2_1 - mu2_2) - C(1,2); F(14) = lambda * rho13 * sigma1_1 * sigma3_1 + (1-lambda) * rho13 * sigma1_2 * sigma3_2 + ... lambda * (1-lambda) * (mu1_1 - mu1_2) * (mu3_1 - mu3_2) - C(1,3); F(15) = lambda * rho23 * sigma2_1 * sigma3_1 + (1-lambda) * rho23 * sigma2_2 * sigma3_2 + ... lambda * (1-lambda) * (mu2_1 - mu2_2) * (mu3_1 - mu3_2) - C(2,3); % 4) set last equation F(16) = lambda * (mu1_1^5 + 10 * mu1_1^3 * sigma1_1^2 + 15 * mu1_1 * sigma1_1^4) + ... (1 - lambda) * (mu1_2^5 + 10 * mu1_2^3 * sigma1_2^2 + 15 * mu1_2 * sigma1_2^4) - MM(5,1); end % fbnd
github
skiamu/Thesis-master
DPalgorithm.m
.m
Thesis-master/MatlabCode/OldScript/DPalgorithm.m
5,206
utf_8
0c2054dfc130bf0f4459229632cb213e
function [ U, J] = DPalgorithm(N,M,X,param,model,VaR,alpha) %DPalgorithm implements a Dynamic Programming algorithm to solve a %stochastic reachability problem % INPUT: % N = number of time steps % M = dimension asset allocation (e.g. 3) % X = cell array of discretized target sets, to access the i-th % element use X{i} % param = density parameters (struct or cell array) % VaR = yearly value at risk % alpha = % OUTPUT: % U = cell array of asset allocations % Remarks: % 1) when the mixture is used, param is a cell array of the following % form {{mu1, Sigma1, lambda1}, ..., {mu_n, Sigma_n, lambda_n}} % 2) aggiungere VaR nel methodo 1 'Mixture', aggiungere metodo % analitico nelle GH U = cell([N 1]); % cell array, in each position there'll be a matrix J = cell([N+1 1]); % optimal value function J{end} = ones([length(X{end}) 1]); % indicator function of the last target set options = optimoptions(@fmincon,'Algorithm','active-set','SpecifyConstraintGradient',true,... 'Display','off','FiniteDifferenceType','central'); % options = optimoptions(@fmincon,'Algorithm','active-set','Display','off','SpecifyConstraintGradient',true); Aeq = ones([1 M]); beq = 1; % budget constraint lb = zeros([M 1]); ub = ones([M 1]); eta = 1e-4; % quantization step for integration for k = N : -1 : 1 k % print the current iteration u0 = [1; 0.; 0.]; % initial condition dimXk = length(X{k}); Uk = zeros([dimXk M]); Jk = zeros([dimXk 1]); int_domain = (X{k+1}(1):eta:X{k+1}(end))'; % improve int domain finesse Jinterp = interp1(X{k+1},J{k+1},int_domain); % interpolate optimal value function % int_domain = X{k+1}; % Jinterp = J{k+1}; for j = dimXk : -1 : 1 [Uk(j,:), Jk(j)] = fmincon(@(u)-objfun(u,X{k}(j),int_domain,Jinterp,param,model), ... u0,[],[],Aeq,beq,lb,ub,@(u)confuneq(u,param,model,VaR,alpha),options); u0 = Uk(j,:)'; % ititial condition = previuos optial solution end U{k} = Uk; J{k} = exp(-Jk); if k ~= 1 idx = find(X{k} <= 1.15 & X{k} >= 0.98); figure area(X{k}(idx),U{k}(idx,:)) title(strcat('k = ',num2str(k-1))) % saveas(gcf,[pwd strcat('/Latex/secondWIP/k',num2str(k-1),model,'.png')]); end end end % DPalgorithm function f = objfun(u,x,int_domain,J,param,model) %objfun defines the problem's objective function that will be maximized % INPUT: % u = asset allocation vector % x = realization portfolio value [scalar] % int_domain = integration domain, k+1 target set discretization % J = k+1 optimal value function % param = density parameters % OUTPUT: % f = objective function f = trapz(int_domain, J .* pf(int_domain,x,u,param,model)); f = log(f); % f = simpsons(J .* pf(int_domain,x,u,param,model),int_domain(1),int_domain(end),[]); end % objfun function [c, ceq, D, Deq] = confuneq(u,param,model,VaR,alpha) %confuneq states the max problem's constraints % INPUT: % u = asset allocation vector % param = density parameters % model = 'Gaussian','Mixture','GH' % VaR = % alpha = % OUTPUT: % c = inequality constraints % ceq = equality constraints VaRConstraintType = '2'; switch model case 'Gaussian' S = param.S; mu = param.mu; mu_p = -u' * mu; sigma_p = sqrt(u' * S * u); ceq = []; c = -VaR + (mu_p + norminv(1-alpha) * sigma_p); % variance constraint case 'Mixture' n = length(param); switch VaRConstraintType case '1' % analytic method % 1) compute the cdf Phi = 0; for i = 1 : n mu = u' * param{i}{1}; sigma = sqrt(u' * param{i}{2} * u); lambda = param{i}{3}; Phi = Phi + lambda * normcdf((-VaR - mu) / sigma); end % 2) setup the constraints ceq = []; c = Phi - alpha; % variance constraint case '2' % quadratic method % 1) compute covariance matrix of asset return w(k+1) W = zeros(length(u)); for i = 1 : n W = W + param{i}{3} * param{i}{2}; for j = 1 : i-1 W = W + param{i}{3}*param{j}{3}*(param{i}{1}-param{j}{1})... *(param{i}{1}-param{j}{1})'; end end % 2) setup the constrints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); ceq = []; c = u' * W * u - sigma_max^2; if nargout > 2 D = 2 * W * u; Deq = []; end end case 'GH' lambda = param.lambda; Chi = param.Chi; Psi = param.Psi; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' wMean = (Chi/Psi)^0.5 * besselk(lambda+1,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wMoment2 = (Chi/Psi) * besselk(lambda+2,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wVar = wMoment2 - wMean^2; wCov = wMean * Sigma + wVar * (gamma * gamma'); % 2) set up the constraints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); ceq = []; c = u' * wCov * u - sigma_max^2; % variance constraint if nargout > 2 D = 2 * wCov * u; Deq = []; end otherwise error('invalid model %s',model); end end % confuneq
github
skiamu/Thesis-master
DPalgorithm2.m
.m
Thesis-master/MatlabCode/OldScript/DPalgorithm2.m
4,972
utf_8
95b217a351bd5016bb21644121c0cafd
function [ U, J] = DPalgorithm(N,M,X,param,model,VaR,alpha) %DPalgorithm implements a Dynamic Programming algorithm to solve a %stochastic reachability problem % INPUT: % N = number of time steps % M = dimension asset allocation (e.g. 3) % X = cell array of discretized target sets, to access the i-th % element use X{i} % param = density parameters (struct or cell array) % VaR = yearly value at risk % alpha = % OUTPUT: % U = cell array of asset allocations % Remarks: % 1) when the mixture is used, param is a cell array of the following % form {{mu1, Sigma1, lambda1}, ..., {mu_n, Sigma_n, lambda_n}} % 2) aggiungere VaR nel methodo 1 'Mixture', aggiungere metodo % analitico nelle GH U = cell([N 1]); % cell array, in each position there'll be a matrix J = cell([N+1 1]); % optimal value function J{end} = ones([length(X{end}) 1]); % indicator function of the last target set options = optimoptions(@fmincon,'Algorithm','sqp','Display','off'); Aeq = ones([1 M]); beq = 1; A = -eye(M); b = zeros([M 1]); for k = N : -1 : 1 k % print the current iteration u0 = [0.0; 0.25; 0.75]; % initial condition % u0 = ones([M 1])/M; % equally-weighted portfolio, initial guess, (maybe better past solution) dimXk = length(X{k}); Uk = zeros([dimXk M]); Jk = zeros([dimXk 1]); for j = 1 : dimXk [Uk(j,:), Jk(j)] = fmincon(@(u)objfun(u,X{k}(j),X{k+1},J{k+1},param,model), ... u0,A,b,Aeq,beq,[],[],@(u)confuneq(u,param,model,VaR,alpha),options); u0 = Uk(j,:)'; % ititial condition = previuos optial solution end U{k} = Uk; J{k} = -Jk; end end % DPalgorithm function f = objfun(u,x,int_domain,J,param,model) %objfun defines the problem's objective function that will be maximized % INPUT: % u = asset allocation vector % x = realization portfolio value [scalar] % int_domain = integration domain, k+1 target set discretization % J = k+1 optimal value function % param = density parameters % OUTPUT: % f = objective function f = trapz(int_domain, J .* pf(int_domain,x,u,param,model)); % f = simpsons(J .* pf(int_domain,x,u,param,model),int_domain(1),int_domain(end),[]); f = -f; % solve the assocoated max problem end % objfun function [c, ceq] = confuneq(u,param,model,VaR,alpha) %confuneq states the max problem's constraints % INPUT: % u = asset allocation vector % param = density parameters % model = 'Gaussian','Mixture','GH' % VaR = % alpha = % OUTPUT: % c = inequality constraints % ceq = equality constraints VaRConstraintType = '2'; switch model case 'Gaussian' S = param.S; mu = param.mu; ceq = u' * ones(size(u)) - 1; % budget constraint mu_p = -u' * mu; sigma_p = sqrt(u' * S * u); c = [-u; % long-only constraint -VaR + (mu_p + norminv(1-alpha) * sigma_p)]; % variance constraint case 'Mixture' n = length(param); switch VaRConstraintType case '1' % analytic method % 1) compute the cdf Phi = 0; for i = 1 : n mu = u' * param{i}{1}; sigma = sqrt(u' * param{i}{2} * u); lambda = param{i}{3}; Phi = Phi + lambda * normcdf((-VaR - mu) / sigma); end % 2) setup the constraints ceq = u' * ones(size(u)) - 1; % budget constraint c = [-u; % long-only constraint Phi - alpha]; % variance constraint case '2' % quadratic method % 1) compute covariance matrix of asset return w(k+1) W = zeros(length(u)); for i = 1 : n W = W + param{i}{3} * param{i}{2}; for j = 1 : i-1 W = W + param{i}{3}*param{j}{3}*(param{i}{1}-param{j}{1})... *(param{i}{1}-param{j}{1})'; end end % 2) setup the constrints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); % ceq = u' * ones(size(u)) - 1; % budget constraint % c = [-u; % long-only constraint % u' * W * u - sigma_max^2]; % variance constraint ceq = []; c = u' * W * u - sigma_max^2; end case 'GH' lambda = param.lambda; Chi = param.Chi; Psi = param.Psi; Sigma = param.sigma; gamma = param.gamma; % 1) compute Cov[w(k+1)] = E[w(k+1)]*Sigma + Var[w(k+1)]*gamma*gamma' wMean = (Chi/Psi)^0.5 * besselk(lambda+1,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wMoment2 = (Chi/Psi) * besselk(lambda+2,sqrt(Chi*Psi)) / besselk(lambda,sqrt(Chi*Psi)); wVar = wMoment2 - wMean^2; wCov = wMean * Sigma + wVar * (gamma * gamma'); % 2) set up the constraints % By using this formula we suppose gaussianity, mu = 0 and % scaling rule, see how it can be improved sigma_max = VaR / norminv(1-alpha); ceq = u' * ones(size(u)) - 1; % budget constraint c = [-u; % long-only constraint u' * wCov * u - sigma_max^2]; % variance constraint otherwise error('invalid model %s',model); end end % confuneq
github
theislab/pseudodynamics-master
simulate_pd_branching_fv_toy.m
.m
pseudodynamics-master/finiteVolume/models/simulate_pd_branching_fv_toy.m
11,573
utf_8
464bbe02ad0e2384bf92aec583776639
% simulate_pd_branching_fv_toy.m is the matlab interface to the cvodes mex % which simulates the ordinary differential equation and respective % sensitivities according to user specifications. % this routine was generated using AMICI commit # in branch unknown branch in repo unknown repository. % % USAGE: % ====== % [...] = simulate_pd_branching_fv_toy(tout,theta) % [...] = simulate_pd_branching_fv_toy(tout,theta,kappa,data,options) % [status,tout,x,y,sx,sy] = simulate_pd_branching_fv_toy(...) % % INPUTS: % ======= % tout ... 1 dimensional vector of timepoints at which a solution to the ODE is desired % theta ... 1 dimensional parameter vector of parameters for which sensitivities are desired. % this corresponds to the specification in model.sym.p % kappa ... 1 dimensional parameter vector of parameters for which sensitivities are not desired. % this corresponds to the specification in model.sym.k % data ... struct containing the following fields. Can have the following fields % Y ... 2 dimensional matrix containing data. % columns must correspond to observables and rows to time-points % Sigma_Y ... 2 dimensional matrix containing standard deviation of data. % columns must correspond to observables and rows to time-points % T ... (optional) 2 dimensional matrix containing events. % columns must correspond to event-types and rows to possible event-times % Sigma_T ... (optional) 2 dimensional matrix containing standard deviation of events. % columns must correspond to event-types and rows to possible event-times % options ... additional options to pass to the cvodes solver. Refer to the cvodes guide for more documentation. % .atol ... absolute tolerance for the solver. default is specified in the user-provided syms function. % .rtol ... relative tolerance for the solver. default is specified in the user-provided syms function. % .maxsteps ... maximal number of integration steps. default is specified in the user-provided syms function. % .tstart ... start of integration. for all timepoints before this, values will be set to initial value. % .sens_ind ... 1 dimensional vector of indexes for which sensitivities must be computed. % default value is 1:length(theta). % .x0 ... user-provided state initialisation. This should be a vactor of dimension [#states, 1]. % default is state initialisation based on the model definition. % .sx0 ... user-provided sensitivity initialisation. this should be a matrix of dimension [#states x #parameters]. % default is sensitivity initialisation based on the derivative of the state initialisation. % .lmm ... linear multistep method for forward problem. % 1: Adams-Bashford % 2: BDF (DEFAULT) % .iter ... iteration method for linear multistep. % 1: Functional % 2: Newton (DEFAULT) % .linsol ... linear solver module. % direct solvers: % 1: Dense (DEFAULT) % 2: Band (not implented) % 3: LAPACK Dense (not implented) % 4: LAPACK Band (not implented) % 5: Diag (not implented) % implicit krylov solvers: % 6: SPGMR % 7: SPBCG % 8: SPTFQMR % sparse solvers: % 9: KLU % .stldet ... flag for stability limit detection. this should be turned on for stiff problems. % 0: OFF % 1: ON (DEFAULT) % .qPositiveX ... vector of 0 or 1 of same dimension as state vector. 1 enforces positivity of states. % .sensi_meth ... method for sensitivity analysis. % 'forward': forward sensitivity analysis (DEFAULT) % 'adjoint': adjoint sensitivity analysis % 'ss': steady state sensitivity analysis % .adjoint ... flag for adjoint sensitivity analysis. % true: on % false: off (DEFAULT) % .ism ... only available for sensi_meth == 1. Method for computation of forward sensitivities. % 1: Simultaneous (DEFAULT) % 2: Staggered % 3: Staggered1 % .Nd ... only available for sensi_meth == 2. Number of Interpolation nodes for forward solution. % Default is 1000. % .interpType ... only available for sensi_meth == 2. Interpolation method for forward solution. % 1: Hermite (DEFAULT for problems without discontinuities) % 2: Polynomial (DEFAULT for problems with discontinuities) % .ordering ... online state reordering. % 0: AMD reordering (default) % 1: COLAMD reordering % 2: natural reordering % % Outputs: % ======== % sol.status ... flag for status of integration. generally status<0 for failed integration % sol.t ... vector at which the solution was computed % sol.llh ... likelihood value % sol.chi2 ... chi2 value % sol.sllh ... gradient of likelihood % sol.s2llh ... hessian or hessian-vector-product of likelihood % sol.x ... time-resolved state vector % sol.y ... time-resolved output vector % sol.sx ... time-resolved state sensitivity vector % sol.sy ... time-resolved output sensitivity vector % sol.z event output % sol.sz sensitivity of event output function varargout = simulate_pd_branching_fv_toy(varargin) % DO NOT CHANGE ANYTHING IN THIS FILE UNLESS YOU ARE VERY SURE ABOUT WHAT YOU ARE DOING % MANUAL CHANGES TO THIS FILE CAN RESULT IN WRONG SOLUTIONS AND CRASHING OF MATLAB if(nargin<2) error('Not enough input arguments.'); else tout=varargin{1}; phi=varargin{2}; end if(nargin>=3) kappa=varargin{3}; else kappa=[]; end theta = exp(phi(:)); if(length(theta)<38) error('provided parameter vector is too short'); end xscale = []; if(nargin>=5) if(isa(varargin{5},'amioption')) options_ami = varargin{5}; else options_ami = amioption(varargin{5}); end else options_ami = amioption(); end if(isempty(options_ami.sens_ind)) options_ami.sens_ind = 1:38; end if(options_ami.sensi<2) options_ami.id = transpose([0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]); end options_ami.z2event = []; % MUST NOT CHANGE THIS VALUE if(~isempty(options_ami.pbar)) pbar = options_ami.pbar; else pbar = ones(size(theta)); end chainRuleFactor = theta(options_ami.sens_ind); if(nargout>1) if(nargout>4) options_ami.sensi = 1; options_ami.sensi_meth = 'forward'; else options_ami.sensi = 0; end end if(options_ami.ss>0) if(options_ami.sensi>1) error('Computation of steady state sensitivity only possible for first order sensitivities'); end options_ami.sensi = 0; end if(options_ami.sensi>0) if(options_ami.sensi_meth == 2) error('adjoint sensitivities are disabled as necessary routines were not compiled'); end end np = length(options_ami.sens_ind); % MUST NOT CHANGE THIS VALUE if(np == 0) options_ami.sensi = 0; end nxfull = 529; if(isempty(options_ami.qpositivex)) options_ami.qpositivex = zeros(nxfull,1); else if(numel(options_ami.qpositivex)>=nxfull) options_ami.qpositivex = options_ami.qpositivex(:); else error(['Number of elements in options_ami.qpositivex does not match number of states ' num2str(nxfull) ]); end end plist = options_ami.sens_ind-1; if(nargin>=4) if(isempty(varargin{4})); data=[]; else if(isa(varargin{4},'amidata')); data=varargin{4}; else data=amidata(varargin{4}); end if(data.ne>0); options_ami.nmaxevent = data.ne; else data.ne = options_ami.nmaxevent; end if(isempty(kappa)) kappa = data.condition; end if(isempty(tout)) tout = data.t; end end else data=[]; end if(~all(tout==sort(tout))) error('Provided time vector is not monotonically increasing!'); end if(not(length(tout)==length(unique(tout)))) error('Provided time vector has non-unique entries!!'); end if(max(options_ami.sens_ind)>38) error('Sensitivity index exceeds parameter dimension!') end if(length(kappa)<529) error('provided condition vector is too short'); end init = struct(); if(~isempty(options_ami.x0)) if(size(options_ami.x0,2)~=1) error('x0 field must be a row vector!'); end if(size(options_ami.x0,1)~=nxfull) error('Number of columns in x0 field does not agree with number of states!'); end init.x0 = options_ami.x0; end if(~isempty(options_ami.sx0)) if(size(options_ami.sx0,2)~=np) error('Number of rows in sx0 field does not agree with number of model parameters!'); end if(size(options_ami.sx0,1)~=nxfull) error('Number of columns in sx0 field does not agree with number of states!'); end init.sx0 = bsxfun(@times,options_ami.sx0,1./permute(chainRuleFactor,[2,1])); end sol = ami_pd_branching_fv_toy(tout,theta(1:38),kappa(1:529),options_ami,plist,pbar,xscale,init,data); if(options_ami.sensi==1) sol.sllh = sol.sllh.*theta(options_ami.sens_ind); sol.sx = bsxfun(@times,sol.sx,permute(theta(options_ami.sens_ind),[3,2,1])); sol.sy = bsxfun(@times,sol.sy,permute(theta(options_ami.sens_ind),[3,2,1])); sol.sz = bsxfun(@times,sol.sz,permute(theta(options_ami.sens_ind),[3,2,1])); sol.srz = bsxfun(@times,sol.srz,permute(theta(options_ami.sens_ind),[3,2,1])); sol.ssigmay = bsxfun(@times,sol.ssigmay,permute(theta(options_ami.sens_ind),[3,2,1])); sol.ssigmaz = bsxfun(@times,sol.ssigmaz,permute(theta(options_ami.sens_ind),[3,2,1])); end if(options_ami.sensi_meth == 3) sol.dxdotdp = bsxfun(@times,sol.dxdotdp,permute(theta(options_ami.sens_ind),[2,1])); sol.dydp = bsxfun(@times,sol.dydp,permute(theta(options_ami.sens_ind),[2,1])); sol.sx = -sol.J\sol.dxdotdp; sol.sy = sol.dydx*sol.sx + sol.dydp; end if(nargout>1) varargout{1} = sol.status; varargout{2} = sol.t; varargout{3} = sol.x; varargout{4} = sol.y; if(nargout>4) varargout{5} = sol.sx; varargout{6} = sol.sy; end else varargout{1} = sol; end end
github
fdcl-gwu/Matrix-Fisher-Distribution-master
pdf_MF_normal_deriv.m
.m
Matrix-Fisher-Distribution-master/pdf_MF_normal_deriv.m
5,874
utf_8
ba3f2c9db4d02a947c70fc3bd8d7716c
function varargout=pdf_MF_normal_deriv(s,bool_ddc,bool_scaled) %pdf_MF_norma_deriv: the derivatives of the normalizing constant for the matrix Fisher distribution %on SO(3) % [dc, ddc] = pdf_MF_normal(s,BOOL_DDC,BOOL_SCALED) returns the 3x1 first % order derivative dc and the 3x3 second order derivatives ddc of the normalizing % constant with respect to the proper singular values for the matrix Fisher % distribution on SO(3), for a given 3x1 (or 1x3) proper singular % values s. % % BOOL_DDC determines whether the second order derivative % are computed or not: % 0 - (defalut) is the same as dc=pdf_MF_normal_deriv(s), and the second % order derivatives are not computed % 1 - computes the second order derivatives, and reuturns ddc % % BOOL_SCALED determines whether the normalizing constant is % scaled or not: % 0 - (defalut) is the same as pdf_MF_normal_deriv(s,BOOL_DDC), and % then derivatives of the unscaled normalizing constant c are returned % 1 - computes the derivatives of the exponentially scaled normalizing constant, % c_bar = exp(-sum(s))*c % % Examples % dc=pdf_MF_normal_deriv(s) - first order derivatives of c % [dc, ddc]=pdf_MF_normal_deriv(s,true) - first and second % order derivatives of c % % dc_bar=pdf_MF_normal_deriv(s,false,true) - first order % derivatives of the exponentially scaled c % [dc_bar, ddc_bar]=pdf_MF_normal_deriv(s,true,true) - first and second % order derivatives of the exponentially scaled c % % See T. Lee, "Bayesian Attitude Estimation with the Matrix Fisher % Distribution on SO(3)", 2017, http://arxiv.org/abs/1710.03746 % % See also PDF_MF_NORMAL_DERIV_APPROX if nargin < 3 bool_scaled = false; end if nargin < 2 bool_ddc = false; end if ~bool_scaled dc=zeros(3,1); % derivatives of the normalizing constant for i=1:3 dc(i) = integral(@(u) f_kunze_s_deriv_i(u,s,i),-1,1); end varargout{1}=dc; if bool_ddc % compute the second order derivatives of the normalizing constant ddc=zeros(3,3); for i=1:3 ddc(i,i) = integral(@(u) f_kunze_s_deriv_ii(u,s,i),-1,1); for j=i+1:3 ddc(i,j) = integral(@(u) f_kunze_s_deriv_ij(u,s,i,j),-1,1); ddc(j,i)=ddc(i,j); end end varargout{2}=ddc; end else % derivatives of the scaled normalizing constant dc_bar = zeros(3,1); for i=1:3 index=circshift([1 2 3],[0 4-i]); j=index(2); k=index(3); dc_bar(k) = integral(@(u) f_kunze_s_deriv_scaled(u,[s(i),s(j),s(k)]),-1,1); end varargout{1}=dc_bar; % compute the second order derivatives of the scaled normalizing % constant if bool_ddc ddc_bar=zeros(3,3); for i=1:3 index=circshift([1 2 3],[0 4-i]); j=index(2); k=index(3); c_bar=pdf_MF_normal(s,1); ddc_bar(k,k) = integral(@(u) f_kunze_s_deriv_scaled_kk(u,[s(i),s(j),s(k)]),-1,1); ddc_bar(i,j) = integral(@(u) f_kunze_s_deriv_scaled_ij(u,[s(i),s(j),s(k)]),-1,1) ... -dc_bar(i)-dc_bar(j)-c_bar; ddc_bar(j,i) = ddc_bar(i,j); end varargout{2}=ddc_bar; end end end function Y=f_kunze_s_deriv_scaled(u,s) % integrand for the derivative of the scaled normalizing constant [l m]=size(u); for ii=1:l for jj=1:m J=besseli(0,1/2*(s(1)-s(2))*(1-u(ii,jj)),1)*besseli(0,1/2*(s(1)+s(2))*(1+u(ii,jj)),1); Y(ii,jj)=1/2*J*(u(ii,jj)-1)*exp((min([s(1) s(2)])+s(3))*(u(ii,jj)-1)); end end end function Y=f_kunze_s_deriv_scaled_kk(u,s) % integrand for the second order derivative of the scaled normalizing constant [l m]=size(u); for ii=1:l for jj=1:m J=besseli(0,1/2*(s(1)-s(2))*(1-u(ii,jj)),1)*besseli(0,1/2*(s(1)+s(2))*(1+u(ii,jj)),1); Y(ii,jj)=1/2*J*(u(ii,jj)-1)^2*exp((min([s(1) s(2)])+s(3))*(u(ii,jj)-1)); end end end function Y=f_kunze_s_deriv_scaled_ij(u,s) % integrand for the scaled second order derivative of the normalizing constant [l m]=size(u); for ii=1:l for jj=1:m J=1/4*besseli(1,1/2*(s(2)-s(3))*(1-u(ii,jj)),1)*besseli(0,1/2*(s(2)+s(3))*(1+u(ii,jj)),1) ... *exp((s(1)+min([s(2) s(3)]))*(u(ii,jj)-1))*u(ii,jj)*(1-u(ii,jj)) ... +1/4*besseli(0,1/2*(s(2)-s(3))*(1-u(ii,jj)),1)*besseli(1,1/2*(s(2)+s(3))*(1+u(ii,jj)),1) ... *exp((s(1)+min([s(2) s(3)]))*(u(ii,jj)-1))*u(ii,jj)*(1+u(ii,jj)); Y(ii,jj)=J; end end end function Y=f_kunze_s_deriv_i(u,s,i) % integrand for the derivative of the normalizing constant index=circshift([1 2 3],[0 4-i]); j=index(2); k=index(3); [l m]=size(u); for ii=1:l for jj=1:m J00=besseli(0,1/2*(s(j)-s(k))*(1-u(ii,jj)))*besseli(0,1/2*(s(j)+s(k))*(1+u(ii,jj))); Y(ii,jj)=1/2*J00*u(ii,jj)*exp(s(i)*u(ii,jj)); end end end function Y=f_kunze_s_deriv_ii(u,s,i) % integrand for the second-order derivative of the normalizing constant index=circshift([1 2 3],[0 4-i]); j=index(2); k=index(3); [l m]=size(u); for ii=1:l for jj=1:m J00=besseli(0,1/2*(s(j)-s(k))*(1-u(ii,jj)))*besseli(0,1/2*(s(j)+s(k))*(1+u(ii,jj))); Y(ii,jj)=1/2*J00*u(ii,jj)^2*exp(s(i)*u(ii,jj)); end end end function Y=f_kunze_s_deriv_ij(u,s,i,j) % integrand for the mixed second-order derivative of the normalizing constant k=setdiff([1 2 3],[i,j]); [l m]=size(u); for ii=1:l for jj=1:m J10=besseli(1,1/2*(s(j)-s(k))*(1-u(ii,jj)))*besseli(0,1/2*(s(j)+s(k))*(1+u(ii,jj))); J01=besseli(0,1/2*(s(j)-s(k))*(1-u(ii,jj)))*besseli(1,1/2*(s(j)+s(k))*(1+u(ii,jj))); Y(ii,jj)=1/4*J10*u(ii,jj)*(1-u(ii,jj))*exp(s(i)*u(ii,jj))... +1/4*J01*u(ii,jj)*(1+u(ii,jj))*exp(s(i)*u(ii,jj)); end end end
github
fdcl-gwu/Matrix-Fisher-Distribution-master
pdf_MF_M2S.m
.m
Matrix-Fisher-Distribution-master/pdf_MF_M2S.m
4,026
utf_8
ed0f8ec92f034dd89b2b4f9bf5b22d27
function [s FVAL NITER]=pdf_MF_M2S(d,s0) %pdf_MF_M2S: transforms the first moments into the proper singular values % s=pdf_MF_M2S(d,s0) numerically solves the following equations for s % % \frac{1}{c(S)}\frac{\partial c(S)}{s_i} - d_i = 0, % % to find the proper singular values of the matrix Fisher distribution % whose first moments match with d. It is solved via Newton-Armijo % iteration with a polynomial line search, and the optional input variable % s0 specifis the initial guess of the iteration. % % [s, FVAL, niter]=pdf_MF_M2S(d,s0) returns the value of the equation at % s, and the number of iterations % % See T. Lee, "Bayesian Attitude Estimation with the Matrix Fisher % Distribution on SO(3)", 2017, http://arxiv.org/abs/1710.03746 % C. T. Kelly, "Iterative Methods For Linear And Nonlinear Equations," % SIAM, 1995, Section 8.3.1. % % See also PDF_MF_M2S_APPROX bool_scaled=1; if nargin < 2 if max(abs(d)) < 0.5 s0 = pdf_MF_M2S_approx(d,0); elseif min(abs(d)) > 0.5 s0 = pdf_MF_M2S_approx(d,1); if min(abs(d)) > 0.99 s = pdf_MF_M2S_approx(d,1); return; end else s0=rand(3,1).*sign(d); end end s=s0; eps=1e-12; alpha=0.05; nf=2*eps; NITER=0; MAX_ITER=100; sigma0=0.1; sigma1=0.5; while nf > eps && NITER < MAX_ITER NITER=NITER+1; f_stack=[]; lambda_stack=[]; [f, df]=func(s,d,1,bool_scaled); s_dir=-df\f; f_stack=stack3(f_stack,f); lambda_stack=stack3(lambda_stack,0); lambda=1; s_trial=s+lambda*s_dir; f_trial=func(s_trial,d,0,bool_scaled); f_stack=stack3(f_stack,f_trial); lambda_stack=stack3(lambda_stack,lambda); % polynomial line search: three-point parabolic method N_SUBITER=0; while norm(f_stack(end)) > (1-alpha*lambda)*norm(f) && N_SUBITER < MAX_ITER N_SUBITER=N_SUBITER+1; if length(lambda_stack) < 3 lambda=sigma1; else lam2=lambda_stack(2); lam3=lambda_stack(3); f2=f_stack(2); f3=f_stack(3); poly_coff_2=1/lam2/lam3/(lam2-lam3)*(lam3*(norm(f2)-norm(f))-lam2*(norm(f3)-norm(f))); if poly_coff_2 > 0 poly_coff_1=1/(lam2-lam3)*(-lam3*(norm(f2)-norm(f))/lam2+lam2*(norm(f3)-norm(f))/lam3); lambda_t=-poly_coff_1/2/poly_coff_2; lambda=saturation(lambda_t,sigma0*lam3,sigma1*lam3) else lambda=sigma1*lam3; end end s_trial=s+lambda*s_dir; f_trial=func(s_trial,d,0,bool_scaled); f_stack=stack3(f_stack,f_trial); lambda_stack=stack3(lambda_stack,lambda); end s=s_trial; nf=max(abs(f_trial)); end FVAL=f_trial; if NITER == MAX_ITER || N_SUBITER == MAX_ITER disp('Warning: MAX iteration reached'); disp('diag(D) = '); disp(d); disp('diag(S) = '); disp(s); end end function Y=stack3(X,x) Y=[X x]; n=size(Y,2); if n > 3 Y=Y(:,n-2:n); end end function y=saturation(x,min_x,max_x) if x <= min_x y=min_x; elseif x >= max_x y=max_x; else y=x; end end function varargout=func(s,d,bool_df,bool_scaled) if ~bool_scaled c=pdf_MF_normal(s,0); if ~bool_df dc=pdf_MF_normal_deriv(s,0,0); f=dc-c*d; varargout{1}=f; else [dc, ddc]=pdf_MF_normal_deriv(s,1,0); f=dc-c*d; df=ddc-d*dc'; varargout{1}=f; varargout{2}=df; end else c_bar=pdf_MF_normal(s,1); if ~bool_df dc_bar=pdf_MF_normal_deriv(s,0,1); f=dc_bar/c_bar-(d-ones(3,1)); varargout{1}=f; else [dc_bar, ddc_bar]=pdf_MF_normal_deriv(s,1,1); %f=dc_bar-c_bar*(d-ones(3,1)); %df=ddc_bar-(d-ones(3,1))*dc_bar'; f=dc_bar/c_bar-(d-ones(3,1)); df=ddc_bar/c_bar-dc_bar*dc_bar'/c_bar^2; varargout{1}=f; varargout{2}=df; end end end
github
fdcl-gwu/Matrix-Fisher-Distribution-master
est_MF.m
.m
Matrix-Fisher-Distribution-master/est_MF.m
5,390
utf_8
c81a7da56900c7f0616ba50153d92c06
function est_MF %est_MF: attitude estimation with the matrix Fisher %distributionp on SO(3) % % Internal variables % - filename : the name of the mat file where estimation results are saved % - EST_METHOD : determine the estimation scheme % 0 : first order estimation % 1 : unscented estimation % - F : estimated matrix paramter % - s : estimated proper singular values % - RM : estimated mean attitude % - rot_est_err : estimtion error in degrees % % See T. Lee, "Bayesian Attitude Estimation with the Matrix Fisher % Distribution on SO(3)", 2017, http://arxiv.org/abs/1710.03746 close all; global h J Jd m g e1 e2 e3 rho %% Estimation method and the initial estimate filename='est_MF_first_order_0'; EST_METHOD=0; F0=100*expm(pi*hat(e1)); % filename='est_MF_first_order_1'; % EST_METHOD=0; % F0=zeros(3,3); % % % filename='est_MF_unscented_0'; % EST_METHOD=1; % F0=100*expm(pi*hat(e1)); % % % filename='est_MF_unscented_1'; % EST_METHOD=1; % F0=zeros(3,3); assert(EST_METHOD==0 || EST_METHOD==1,'EST_METHOD should be either 0 or 1'); if EST_METHOD==0 disp('ESTIMATOR: First order attitude estimation'); else disp('ESTIMATOR: Unscented attitude estimation'); end %% Rigid body parameters m=1; g=9.81; e1=[1 0 0]'; e2=[0 1 0]'; e3=[0 0 1]'; Body.a=0.8; Body.b=0.2; Body.h=0.6; rho=0.5*Body.h*e3; J=diag([1/4*Body.b^2+1/3*Body.h^2,... 1/4*Body.a^2+1/3*Body.h^2,... 1/4*(Body.a^2+Body.b^2)]); Jd=trace(J)/2*eye(3)-J; %% True Trajectory disp('Generating the true reference trajectories...'); h=0.02; T=10; t=0:h:T; N=length(t); R_true=zeros(3,3,N); W_true=zeros(3,N); R_true(:,:,1)=eye(3); W_true(:,1)=1.3*sqrt(m*g*norm(rho)*2/trace(J))*[1 1 1]; for k=1:N-1 [R_true(:,:,k+1) W_true(:,k+1)]=lgviSO(R_true(:,:,k),W_true(:,k)); end %% Sampling attitude and angular velocity measurements disp('Generating the measurements...'); rng(1); H=diag([1.8 1.6 2.4]); W_err_sigma=h*H*H'; %W_err_sigma=h*diag([0.5^2 0.8^2 1^2]); W_err = (randn(N,3)*chol(W_err_sigma))'; W_mea = W_true + W_err; Fz=diag([40 50 35]); [R_mea_err accept_ratio]=pdf_MF_sampling(Fz,N); for k=1:N R_mea(:,:,k)=R_true(:,:,k)*R_mea_err(:,:,k); rot_mea_err(k)=180/pi*norm(vee(logm(R_mea_err(:,:,k)))); end %% Estimation routine disp('Estimating...'); F=zeros(3,3,N); U=zeros(3,3,N); S=zeros(3,3,N); V=zeros(3,3,N); RM=zeros(3,3,N); F(:,:,1)=F0; [U0 S0 V0]=psvd(F0); U(:,:,1)=U0; S(:,:,1)=S0; V(:,:,1)=V0; RM(:,:,1)=U(:,:,1)*V(:,:,1)'; k_R_mea=[]; t_start=tic; for k=1:N-1 % Prediction / Propagation if EST_METHOD == 0 [F(:,:,k+1) U(:,:,k+1) S(:,:,k+1) V(:,:,k+1)]=FirstOrderPropagation(F(:,:,k),W_mea(:,k),W_err_sigma,h); else [F(:,:,k+1) U(:,:,k+1) S(:,:,k+1) V(:,:,k+1)]=UnscentedPropagation(F(:,:,k),W_mea(:,k),W_err_sigma,h); end RM(:,:,k+1)=U(:,:,k+1)*V(:,:,k+1)'; if rem(k,5)==0 % Measurement update / Correction k_R_mea=[k_R_mea; k+1]; [F(:,:,k+1) U(:,:,k+1) S(:,:,k+1) V(:,:,k+1) RM(:,:,k+1)]=MeasurementUpdate(F(:,:,k+1),R_mea(:,:,k+1),Fz); end if rem(k,5)==0 disp(['Completed ' num2str(k/(N-1)*100,3) '%']); disp([F(:,:,k+1), S(:,:,k+1)]); disp([180/pi*norm((logmso3(R_true(:,:,k)'*RM(:,:,k))))]); disp(' '); end end t_elapsed = toc(t_start); disp('Post processing...'); for k=1:N errRf(k)=norm(R_true(:,:,k)-RM(:,:,k)); rot_est_err(k)=180/pi*norm((logmso3(R_true(:,:,k)'*RM(:,:,k)))); s(:,k)=diag(S(:,:,k)); end figure; plot(t,rot_est_err,'b',t(k_R_mea),rot_est_err(k_R_mea),'bo'); xlabel('$t$','interpreter','latex'); ylabel('Est. error'); figure; for ii=1:3 subplot(3,1,ii); plot(t,1./s(ii,:),'b',t(k_R_mea),1./s(ii,k_R_mea),'b.'); end subplot(3,1,1);ylabel('$\frac{1}{s_2+s_3}$','interpreter','latex'); subplot(3,1,2);ylabel('$\frac{1}{s_3+s_1}$','interpreter','latex'); subplot(3,1,3);ylabel('$\frac{1}{s_1+s_2}$','interpreter','latex'); xlabel('$t$','interpreter','latex'); %% save(filename); evalin('base',['load ' filename]); disp(['Saved to "' filename '.mat", and loaded to workspace']); end function [F U S V RM]=MeasurementUpdate(F,Z,Fz) F=F+Z*Fz'; [U S V]=psvd(F); RM=U*V'; end function [Fkp Ukp Skp Vkp]=FirstOrderPropagation(Fk,Wk,Gk,h) [Uk Sk Vk]=psvd(Fk); EQk=pdf_MF_moment(diag(Sk)); ERk=Uk*diag(EQk)*Vk'; ERkp=ERk*(eye(3)+h/2*(-trace(Gk)*eye(3)+Gk))*expm(h*hat(Wk)); [Ukp Dkp Vkp]=psvd(ERkp); skp=pdf_MF_M2S(diag(Dkp)); Skp=diag(skp); Fkp=Ukp*Skp*Vkp'; end function [Fkp Ukp Skp Vkp]=UnscentedPropagation(Fk,Wk,Gk,h) [R W0 W]=pdf_MF_unscented_transform(Fk); R_bar_kp=W0*R(:,:,1)*expm(hat(h*Wk)); for i=1:3 R_bar_kp=R_bar_kp+W(i)*R(:,:,2*i)*expm(hat(h*Wk))+W(i)*R(:,:,2*i+1)*expm(hat(h*Wk)); end R_bar_kp=R_bar_kp*(eye(3)+h/2*(-trace(Gk)*eye(3)+Gk)); [Ukp Dkp Vkp]=psvd(R_bar_kp); skp=pdf_MF_M2S(diag(Dkp)); Skp=diag(skp); Fkp=Ukp*Skp*Vkp'; end function [Rkp Wkp]=lgviSO(Rk,Wk) global m g rho J e1 e2 e3 h Mgk=m*g*hat(rho)*Rk'*e3; fi=h*Wk+h^2/2*inv(J)*Mgk; f=fi+1; gk=h*J*Wk+h^2/2*Mgk; while norm(fi-f) > 1e-15 f=fi; GG=gk+(hat(gk)-2*J)*f+(gk'*f)*f; nabG=(hat(gk)-2*J)+gk'*f*eye(3)+f*gk'; fi=f-inv(nabG)*GG; end Fk=(eye(3)+hat(fi))*inv(eye(3)-hat(fi)); Rkp=Rk*Fk; Mgkp=m*g*hat(rho)*Rkp'*e3; Wkp=J\(Fk'*(J*Wk+h/2*Mgk)+h/2*Mgkp); end
github
fdcl-gwu/Matrix-Fisher-Distribution-master
pdf_MF_sampling.m
.m
Matrix-Fisher-Distribution-master/pdf_MF_sampling.m
1,555
utf_8
d3322b8045c4c44ca7a12bccefb79634
function [R accept_ratio]=pdf_MF_sampling(F,N) %pdf_MF_sampling: samping for the matrix Fisher distribution on SO(3) % R=pdf_MF_sampling(F,N) returns N rotation matricies distributed % according to the matrix Fisher distribution with hte matrix parameter F % % See T. Lee, "Bayesian Attitude Estimation with the Matrix Fisher % Distribution on SO(3)", 2017, http://arxiv.org/abs/1710.03746 [U S V]=svd(F); B=zeros(4,4); B(1:3,1:3)=2*S-trace(S)*eye(3); B(4,4)=trace(S); [x accept_ratio]=sampBing(B,N); R=zeros(3,3,N); for i=1:N q4=x(4,i); q=x(1:3,i); R(:,:,i)=(q4^2-q'*q)*eye(3)+2*q*q'+2*q4*hat(q); R(:,:,i)=U*R(:,:,i)*V'; end end function [x accept_ratio]=sampBing(B,N) % simulating Bingham distribution % See Kent, Ganeiber, and Mardia, "A new method to simulate the Bingham and % related distribution, 2013 lamB=eig(B); A=-B; lamA=-lamB; min_lamA=min(lamA); lamA=lamA-min_lamA; A=A-min_lamA*eye(4); funb = @(b) 1/(b+2*lamA(1))+1/(b+2*lamA(2))+1/(b+2*lamA(3))+1/(b+2*lamA(4))-1; tol = optimoptions('fsolve','TolFun', 1e-8, 'TolX', 1e-8,'display','off'); [b err exitflag]=fsolve(funb,1,tol); if exitflag ~= 1 disp([err exitflag]); end W=eye(4)+2*A/b; Mstar=exp(-(4-b)/2)*(4/b)^2; x=zeros(4,N); nx=0; nxi=0; while nx < N xi=mvnrnd(zeros(4,1),inv(W))'; xi=xi/norm(xi); nxi=nxi+1; pstar_Bing=exp(-xi'*A*xi); pstar_ACGD=(xi'*W*xi)^(-2); u=rand(1); if u < (pstar_Bing / (Mstar*pstar_ACGD)) nx=nx+1; x(:,nx)=xi; end end accept_ratio=N/nxi; end
github
fdcl-gwu/Matrix-Fisher-Distribution-master
pdf_MF_normal.m
.m
Matrix-Fisher-Distribution-master/pdf_MF_normal.m
2,234
utf_8
c5ebd05c4302aa66a42359b15367a456
function c_return=pdf_MF_normal(s,bool_scaled) %pdf_MF_normal: the normalizing constant for the matrix Fisher distribution %on SO(3) % c = pdf_MF_normal(s) is the normalizing constant for the % matrix Fisher distribution on SO(3), for a given 3x1 (or 1x3) proper singular % values s. % % c = pdf_MF_normal(s,BOOL_SCALED) returns an exponentially scaled value % specified by BOOL_SCALED: % 0 - (defalut) is the same as pdf_MF_normal(s) % 1 - returnes an exponentially scaled normlaizing constant, % exp(-sum(s))*c % % See T. Lee, "Bayesian Attitude Estimation with the Matrix Fisher % Distribution on SO(3)", 2017, http://arxiv.org/abs/1710.03746 % % See also PDF_MF_NORMAL_APPROX assert(or(min(size(s)==[1 3]),min(size(s)==[3 1])),'ERROR: s should be 3 by 1 or 1 by 3'); % if bool_scaled is not defined, then set it false if nargin < 2 bool_scaled=false; end if ~bool_scaled % return the normalizing constant without any scaling c = integral(@(u) f_kunze_s(u,s),-1,1); c_return = c; else % return the normalizing constant scaled by exp(-sum(s)) if s(1)>= s(2) c_bar = integral(@(u) f_kunze_s_scaled_1(u,s),-1,1); else c_bar = integral(@(u) f_kunze_s_scaled_2(u,s),-1,1); end c_return = c_bar; %c=c_bar*exp(sum(s)); end end function Y=f_kunze_s(u,s) % integrand for the normalizing constant [l m]=size(u); for ii=1:l for jj=1:m J=besseli(0,1/2*(s(1)-s(2))*(1-u(ii,jj)))*besseli(0,1/2*(s(1)+s(2))*(1+u(ii,jj))); Y(ii,jj)=1/2*exp(s(3)*u(ii,jj))*J; end end end function Y=f_kunze_s_scaled_1(u,s) % integrand for the normalizing constant scaled by exp(-sum(s)) when s(1) % >= s(2) [l m]=size(u); for ii=1:l for jj=1:m J=besseli(0,1/2*(s(1)-s(2))*(1-u(ii,jj)),1)*besseli(0,1/2*(s(1)+s(2))*(1+u(ii,jj)),1); Y(ii,jj)=1/2*exp((s(2)+s(3))*(u(ii,jj)-1))*J; end end end function Y=f_kunze_s_scaled_2(u,s) % integrand for the normalizing constant scaled by exp(-sum(s)) when s(1) % <= s(2) [l m]=size(u); for ii=1:l for jj=1:m J=besseli(0,1/2*(s(1)-s(2))*(1-u(ii,jj)),1)*besseli(0,1/2*(s(1)+s(2))*(1+u(ii,jj)),1); Y(ii,jj)=1/2*exp((s(1)+s(3))*(u(ii,jj)-1))*J; end end end
github
mcubelab/rgrasp-master
savejson.m
.m
rgrasp-master/software/jsonlab-1.0/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
mcubelab/rgrasp-master
loadjson.m
.m
rgrasp-master/software/jsonlab-1.0/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
mcubelab/rgrasp-master
loadubjson.m
.m
rgrasp-master/software/jsonlab-1.0/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
mcubelab/rgrasp-master
saveubjson.m
.m
rgrasp-master/software/jsonlab-1.0/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
mcubelab/rgrasp-master
ikTrajServer_internal.m
.m
rgrasp-master/software/planning/ik_server/ikTrajServer_internal.m
3,737
utf_8
9a5fa5ae61613f0297f936806ff84e4d
function ret_json = ikTrajServer_internal(r, data_json, options) data = JSON.parse(data_json); % 1. Get hand target pose q0 = cell2mat(data.q0)'; target_hand_pos = []; target_hand_ori = []; if isfield(data, 'target_hand_pos') target_hand_pos = cell2mat(data.target_hand_pos)'; %[x,y,z] end if isfield(data, 'target_hand_ori') target_hand_ori = cell2mat(data.target_hand_ori)'; %[qw,qx,qy,qz] end if isfield(data, 'tip_hand_transform') options.tip_hand_transform = cell2mat(data.tip_hand_transform)'; %[x,y,z, qw,qx,qy,qz] end if isfield(data, 'straightness') options.straightness = data.straightness; end if isfield(data, 'pos_tol') options.pos_tol = data.pos_tol; end if isfield(data, 'ori_tol') options.ori_tol = data.ori_tol; end if isfield(data, 'inframebb') options.inframebb = data.inframebb; options.inframebb.tip_hand_transform = options.tip_hand_transform'; % xyzrpy options.inframebb.lb = cell2mat(options.inframebb.lb)'; options.inframebb.ub = cell2mat(options.inframebb.ub)'; options.inframebb.frame_mat = cellcelltomat(options.inframebb.frame_mat); % need to special treat matrix end if isfield(data, 'target_link') options.target_link = data.target_link; end if isfield(data, 'target_joint_bb') options.target_joint_bb = cell2mat(data.target_joint_bb{1}); end if isfield(data, 'N') options.N = data.N; end if isfield(data, 'ik_only') options.ik_only = data.ik_only; end % 2. Get Other Object Pose (for collision avoidance), not used right % now if isfield(data, 'object_list') positions = zeros(3, length(data.object_list)); orientations = zeros(4, length(data.object_list)); % 2.1 Prepare objects info: parse obj pose information from message for i = 1:length(data.object_list) object = data.object_list{i}; pose = object.pose; positions(1:3, i) = [pose.position.x; ... pose.position.y; ... pose.position.z]; orientations(1:4, i) = [pose.orientation.w; ... pose.orientation.x; ... pose.orientation.y; ... pose.orientation.z]; end end % 3. display options options % 4. do planning, will cache the robot [xtraj, snopt_info_iktraj, infeasible_constraint_iktraj, snopt_info_ik, infeasible_constraint_ik]... = runPlanning(r, q0, target_hand_pos, target_hand_ori, options); % 5. publish the data in xtraj with a standard ROS type q_traj = []; if ~isempty(xtraj) %ts = xtraj.pp.breaks; if isobject(xtraj) ts = linspace(xtraj.pp.breaks(1), xtraj.pp.breaks(end), length(xtraj.pp.breaks)*10); q_and_qdot = xtraj.eval(ts); q_traj = q_and_qdot(1:6, 1:end); % this q's are in rad else % for ik only q_traj = xtraj; end end ret.q_traj = q_traj; ret.snopt_info_iktraj = snopt_info_iktraj; ret.infeasible_constraint_iktraj = infeasible_constraint_iktraj; ret.snopt_info_ik = snopt_info_ik; ret.infeasible_constraint_ik = infeasible_constraint_ik; %ret_json = savejson('', ret, '/tmp/ret'); ret_json = savejson('', ret); end function B = cellcelltomat(A) B = zeros(length(A), length(A{1})); for i=1:length(A) B(i,:) = cell2mat(A{i}); end end
github
mcubelab/rgrasp-master
sub2ind2d.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/sub2ind2d.m
136
utf_8
727b74a55a13af99fd671e8d45a7ac73
% a faster version for sub2ind for 2d case function linIndex = sub2ind2d(sz, rowSub, colSub) linIndex = (colSub-1) * sz(1) + rowSub;
github
mcubelab/rgrasp-master
nmsRange2.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/nmsRange2.m
1,162
utf_8
2a7015acc141a2906694c5c52ddc2a2b
% A sped up version of nmsRange() function finalPick = nmsRange2(scores,range,minvalue) %tic; finalPick = zeros(size(scores)); changeScore = scores; changeScore(changeScore<=minvalue) = 0.0; % suppres the scores that are under minvalue xdim = size(changeScore,1); ydim = size(changeScore,2); ind_havevalue = find(changeScore(:)); score_ind_list = [changeScore(ind_havevalue), ind_havevalue]; % [[score1, ind1];[score2, ind2];[score2, ind2]] sorted_score_ind_list = sortrows(score_ind_list, 1, 'descend'); % sort the scores first and retrive them from high to low for i = 1:size(sorted_score_ind_list,1) currMax = sorted_score_ind_list(i,1); currInd = sorted_score_ind_list(i,2); y = fix((currInd-1) / xdim) + 1; % manually doing the conversion is faster than ind2sub x = currInd - (y-1)*xdim; if(changeScore(x,y) < 1e-8) % already got suppressed continue; end finalPick(x,y) = currMax; xstart = max(x-range,1); xend = min(x+range,xdim); ystart = max(y-range,1); yend = min(y+range,ydim); changeScore(xstart:xend, ystart:yend) = 0.0; end %fprintf('[Matlab Timing nmsRange2] '); toc end
github
mcubelab/rgrasp-master
fill_depth_cross_bf.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/bxf/fill_depth_cross_bf.m
1,901
utf_8
94541444b63dc32ed860bb45e3d50f11
% In-paints the depth image using a cross-bilateral filter. The operation % is implemented via several filterings at various scales. The number of % scales is determined by the number of spacial and range sigmas provided. % 3 spacial/range sigmas translated into filtering at 3 scales. % % Args: % imgRgb - the RGB image, a uint8 HxWx3 matrix % imgDepthAbs - the absolute depth map, a HxW double matrix whose values % indicate depth in meters. % spaceSigmas - (optional) sigmas for the spacial gaussian term. % rangeSigmas - (optional) sigmas for the intensity gaussian term. % % Returns: % imgDepthAbs - the inpainted depth image. function imgDepthAbs = fill_depth_cross_bf(imgRgb, imgDepthAbs, ... spaceSigmas, rangeSigmas) error(nargchk(2,4,nargin)); assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8'); assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double'); if nargin < 3 %spaceSigmas = [ 12]; spaceSigmas = [12 5 8]; end if nargin < 4 % rangeSigmas = [0.2]; rangeSigmas = [0.2 0.08 0.02]; end assert(numel(spaceSigmas) == numel(rangeSigmas)); assert(isa(rangeSigmas, 'double')); assert(isa(spaceSigmas, 'double')); % Create the 'noise' image and get the maximum observed depth. imgIsNoise = imgDepthAbs == 0 | imgDepthAbs == 10; maxDepthObs = max(imgDepthAbs(~imgIsNoise)); % Convert the depth image to uint8. imgDepth = imgDepthAbs ./ maxDepthObs; imgDepth(imgDepth > 1) = 1; imgDepth = uint8(imgDepth * 255); % Run the cross-bilateral filter. if ispc imgDepthAbs = mex_cbf_windows(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:)); else imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), imgIsNoise, spaceSigmas(:), rangeSigmas(:)); end % Convert back to absolute depth (meters). imgDepthAbs = im2double(imgDepthAbs) .* maxDepthObs; end
github
mcubelab/rgrasp-master
draw_square_3d.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/draw_square_3d.m
1,073
utf_8
0462ce22c01b036dfb5c0083946973ea
% Draws a square in 3D % % Args: % corners - 8x2 matrix of 2d corners. % color - matlab color code, a single character. % lineWidth - the width of each line of the square. % % Author: Nathan Silberman ([email protected]) function draw_square_3d(corners, color, lineWidth) if nargin < 2 color = 'r'; end if nargin < 3 lineWidth = 0.5; end vis_line(corners(1,:), corners(2,:), color, lineWidth); vis_line(corners(2,:), corners(3,:), color, lineWidth); vis_line(corners(3,:), corners(4,:), color, lineWidth); vis_line(corners(4,:), corners(1,:), color, lineWidth); vis_line(corners(5,:), corners(6,:), color, lineWidth); vis_line(corners(6,:), corners(7,:), color, lineWidth); vis_line(corners(7,:), corners(8,:), color, lineWidth); vis_line(corners(8,:), corners(5,:), color, lineWidth); vis_line(corners(1,:), corners(5,:), color, lineWidth); vis_line(corners(2,:), corners(6,:), color, lineWidth); vis_line(corners(3,:), corners(7,:), color, lineWidth); vis_line(corners(4,:), corners(8,:), color, lineWidth); end
github
mcubelab/rgrasp-master
pointCloudGPU_faster.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/pointCloudGPU_faster.m
36,588
utf_8
0a79c3d12eac92d864fb3b874162e4d6
classdef pointCloudGPU < matlab.mixin.Copyable & vision.internal.EnforceScalarHandle % pointCloud Object for storing a 3-D point cloud. % ptCloud = pointCloud(xyzPoints) creates a point cloud object whose % coordinates are specified by an M-by-3 or M-by-N-by-3 matrix xyzPoints. % % ptCloud = pointCloud(xyzPoints, Name, Value) specifies additional % name-value pair arguments described below: % % 'Color' A matrix C specifying the color of each point in % the point cloud. If the coordinates are an M-by-3 % matrix, C must be an M-by-3 matrix, where each row % contains a corresponding RGB value. If the % coordinates are an M-by-N-by-3 matrix xyzPoints, C % must be an M-by-N-by-3 matrix containing % 1-by-1-by-3 RGB values for each point. % % Default: [] % % 'Normal' A matrix NV specifying the normal vector at % each point. If the coordinates are an M-by-3 % matrix, NV must be an M-by-3 matrix, where each row % contains a corresponding normal vector. If the % coordinates are an M-by-N-by-3 matrix xyzPoints, NV % must be an M-by-N-by-3 matrix containing % 1-by-1-by-3 normal vector for each point. % % Default: [] % % 'Intensity' A vector or matrix INT specifying the grayscale % intensity at each point. If the coordinates are an % M-by-3 matrix, INT must be an M-by-1 vector, where % each element contains a corresponding intensity % value. If the coordinates are an M-by-N-by-3 matrix % xyzPoints, INT must be an M-by-N matrix containing % intensity value for each point. % % Default: [] % % pointCloud properties : % Location - Matrix of [X, Y, Z] point coordinates (read only) % Color - Matrix of point RGB colors % Normal - Matrix of [NX, NY, NZ] point normal directions % Intensity - Matrix of point grayscale intensities % Count - Number of points (read only) % XLimits - The range of coordinates along X-axis (read only) % YLimits - The range of coordinates along Y-axis (read only) % ZLimits - The range of coordinates along Z-axis (read only) % % pointCloud methods: % findNearestNeighbors - Retrieve K nearest neighbors of a point % findNeighborsInRadius - Retrieve neighbors of a point within a specified radius % findPointsInROI - Retrieve points within a region of interest % select - Select points specified by index % removeInvalidPoints - Remove invalid points % % Notes % ----- % - To reduce memory use, point locations are suggested to be stored as single. % % Example : Find the shortest distance between two point clouds % ------------------------------------------------------------- % ptCloud1 = pointCloud(rand(100, 3, 'single')); % % ptCloud2 = pointCloud(1+rand(100, 3, 'single')); % % minDist = inf; % % % Find the nearest neighbor in ptCloud2 for each point in ptCloud1 % for i = 1 : ptCloud1.Count % point = ptCloud1.Location(i,:); % [~, dist] = findNearestNeighbors(ptCloud2, point, 1); % if dist < minDist % minDist = dist; % end % end % % See also pcshow, pcfromkinect, reconstructScene, pcread, pcwrite, % pctransform, pcdenoise, pcdownsample, pcregrigid, pcmerge % Copyright 2014 The MathWorks, Inc. % % References % ---------- % Marius Muja and David G. Lowe, "Fast Approximate Nearest Neighbors with % Automatic Algorithm Configuration", in International Conference on % Computer Vision Theory and Applications (VISAPP'09), 2009 properties (GetAccess = public, SetAccess = private) % Location is an M-by-3 or M-by-N-by-3 matrix. Each entry specifies % the x, y, z coordinates of a point. Location = single([]); end properties (Access = public) % Color is an M-by-3 or M-by-N-by-3 uint8 matrix. Each entry % specifies the RGB color of a point. Color = uint8([]); % Normal is an M-by-3 or M-by-N-by-3 matrix. Each entry % specifies the x, y, z component of a normal vector. Normal = single([]); % Intensity is an M-by-1 or M-by-N matrix. Each entry % specifies the grayscale intensity of a point. Intensity = single([]); end properties(Access = protected, Transient) Kdtree = []; end properties(Access = protected, Hidden) IsOrganized; Version = 1.1; % 2017a end properties(Dependent) % Count specifies the number of points in the point cloud. Count; % XLimits is a 1-by-2 vector that specifies the range of point % locations along X axis. XLimits; % YLimits is a 1-by-2 vector that specifies the range of point % locations along Y axis. YLimits; % ZLimits is a 1-by-2 vector that specifies the range of point % locations along Z axis. ZLimits; end methods %================================================================== % Constructor %================================================================== % pcd = pointCloud(xyzPoints); % pcd = pointCloud(..., 'Color', C); % pcd = pointCloud(..., 'Normal', nv); % pcd = pointCloud(..., 'Intensity', I); function this = pointCloudGPU(varargin) narginchk(1, 7); [xyzPoints, C, nv, I, O, U2O] = validateAndParseInputs(varargin{:}); this.Location = xyzPoints; this.IsOrganized = ~ismatrix(this.Location); % M-by-N-by-3 this.Color = C; this.Normal = nv; this.Intensity = I; this.OrganizedLoc = O; this.UnorganizedToOrganizedInd = U2O; end %================================================================== % K nearest neighbor search %================================================================== function [indices, dists] = findNearestNeighbors(this, point, K, varargin) %findNearestNeighbors Find the nearest neighbors of a point. % % [indices, dists] = findNearestNeighbors(ptCloud, point, K) % returns the K nearest neighbors of a query point. The point % is an [X, Y, Z] vector. indices is a column vector that % contains K linear indices to the stored points in the point % cloud. dists is a column vector that contains K Euclidean % distances to the point. % % [...] = findNearestNeighbors(... , Name, Value) % specifies additional name-value pairs described below: % % 'Sort' True or false. When set to true, % the returned indices are sorted in the % ascending order based on the distance % from a query point. % % Default: false % % 'MaxLeafChecks' An integer specifying the number of leaf % nodes that are searched in Kdtree. If the tree % is searched partially, the returned result may % not be exact. A larger number may increase the % search accuracy but reduce efficiency. When this % number is set to inf, the whole tree will be % searched to return exact search result. % % Default: inf % % Example : Find K-nearest neighbors % --------- % % Create a point cloud object with randomly generated points % ptCloud = pointCloud(1000*rand(100,3,'single')); % % % Define a query point and number of neighbors % point = [50, 50, 50]; % K = 10; % % % Get the indices and distances of 10 nearest points % [indices, dists] = findNearestNeighbors(ptCloud, point, K); narginchk(3, 7); validateattributes(point, {'single', 'double'}, ... {'real', 'nonsparse', 'finite', 'size', [1, 3]}, mfilename, 'point'); if isa(this.Location, 'single') point = single(point); else point = double(point); end validateattributes(K, {'single', 'double'}, ... {'nonsparse', 'scalar', 'positive', 'integer'}, mfilename, 'K'); K = min(double(K), numel(this.Location)/3); [doSort, MaxLeafChecks] = validateAndParseSearchOption(varargin{:}); % Use bruteforce if there are fewer than 500 points if numel(this.Location)/3 < 500 if ~this.IsOrganized allDists = visionSSDMetric(point', this.Location'); else allDists = visionSSDMetric(point', reshape(this.Location, [], 3)'); end % This function will ensure returning actual number of neighbors % The result is already sorted [dists, indices] = vision.internal.partialSort(allDists, K); tf = isfinite(dists); indices = indices(tf); dists = dists(tf); else this.buildKdtree(); searchOpts.checks = MaxLeafChecks; searchOpts.eps = 0; [indices, dists, valid] = this.Kdtree.knnSearch(point, K, searchOpts); % This step will ensure returning actual number of neighbors indices = indices(1:valid); dists = dists(1:valid); % Sort the result if specified if doSort [dists, IND] = sort(dists); indices = indices(IND); end end if nargout > 1 dists = sqrt(dists); end end %================================================================== % Radius search %================================================================== function [indices, dists] = findNeighborsInRadius(this, point, radius, varargin) %findNeighborsInRadius Find the neighbors within a radius. % % [indices, dists] = findNeighborsInRadius(ptCloud, point, radius) % returns the neighbors within a radius of a query point. % The query point is an [X, Y, Z] vector. indices is a column % vector that contains the linear indices to the stored points in % the point cloud object ptCloud. dists is a column vector that % contains the Euclidean distances to the query point. % % [...] = findNeighborsInRadius(... , Name, Value) specifies % specifies additional name-value pairs described below: % % 'Sort' True or false. When set to true, % the returned indices are sorted in the % ascending order based on the distance % from a query point. % % Default: false % % 'MaxLeafChecks' An integer specifying the number of leaf % nodes that are searched in Kdtree. If the tree % is searched partially, the returned result may % not be exact. A larger number may increase the % search accuracy but reduce efficiency. When this % number is set to inf, the whole tree will be % searched to return exact search result. % % Default: inf % % Example : Find neighbors within a given radius using Kdtree % ----------------------------------------------------------- % % Create a point cloud object with randomly generated points % ptCloud = pointCloud(100*rand(1000, 3, 'single')); % % % Define a query point and search radius % point = [50, 50, 50]; % radius = 5; % % % Get all the points within a radius % [indices, dists] = findNeighborsInRadius(ptCloud, point, radius); narginchk(3, 7); validateattributes(point, {'single', 'double'}, ... {'real', 'nonsparse', 'finite', 'size', [1, 3]}, mfilename, 'point'); if isa(this.Location, 'single') point = single(point); else point = double(point); end validateattributes(radius, {'single', 'double'}, ... {'nonsparse', 'scalar', 'nonnegative', 'finite'}, mfilename, 'radius'); radius = double(radius); [doSort, MaxLeafChecks] = validateAndParseSearchOption(varargin{:}); % Use bruteforce if there are less than 500 points if numel(this.Location)/3 < 500 if ~this.IsOrganized allDists = visionSSDMetric(point', this.Location'); else allDists = visionSSDMetric(point', reshape(this.Location, [], 3)'); end indices = uint32(find(allDists <= radius^2))'; dists = allDists(indices)'; tf = isfinite(dists); indices = indices(tf); dists = dists(tf); else this.buildKdtree(); searchOpts.checks = MaxLeafChecks; searchOpts.eps = 0; [indices, dists] = this.Kdtree.radiusSearch(point, radius, searchOpts); end % Sort the result if specified if doSort [dists, IND] = sort(dists); indices = indices(IND); end if nargout > 1 dists = sqrt(dists); end end %================================================================== % Box search %================================================================== function indices = findPointsInROI(this, roi) %findPointsInROI Find points within a region of interest. % % indices = findPointsInROI(ptCloud, roi) returns the points % within a region of interest, roi. The roi is a cuboid % specified as a 1-by-6 vector in the format of [xmin, xmax, % ymin, ymax, zmin, zmax]. indices is a column vector that % contains the linear indices to the stored points in the % point cloud object, ptCloud. % % Example : Find points within a given cuboid % ------------------------------------------- % % Create a point cloud object with randomly generated points % ptCloudA = pointCloud(100*rand(1000, 3, 'single')); % % % Define a cuboid % roi = [0, 50, 0, inf, 0, inf]; % % % Get all the points within the cuboid % indices = findPointsInROI(ptCloudA, roi); % ptCloudB = select(ptCloudA, indices); % % pcshow(ptCloudA.Location, 'r'); % hold on; % pcshow(ptCloudB.Location, 'g'); % hold off; narginchk(2, 2); validateattributes(roi, {'single', 'double'}, ... {'real', 'nonsparse', 'numel', 6}, mfilename, 'roi'); if isvector(roi) roi = reshape(roi, [2, 3])'; end if any(roi(:, 1) > roi(:, 2)) error(message('vision:pointcloud:invalidROI')); end roi = double(roi); % Use bruteforce if there are less than 500 points if numel(this.Location)/3 < 500 if ~this.IsOrganized tf = this.Location(:,1)>=roi(1)&this.Location(:,1)<=roi(4) ... &this.Location(:,2)>=roi(2)&this.Location(:,2)<=roi(5) ... &this.Location(:,3)>=roi(3)&this.Location(:,3)<=roi(6); indices = uint32(find(tf)); else tf = this.Location(:,:,1)>=roi(1)&this.Location(:,:,1)<=roi(4) ... &this.Location(:,:,2)>=roi(2)&this.Location(:,:,2)<=roi(5) ... &this.Location(:,:,3)>=roi(3)&this.Location(:,:,3)<=roi(6); indices = uint32(find(tf)); end else this.buildKdtree(); indices = this.Kdtree.boxSearch(roi); end end %================================================================== % Obtain a subset of this point cloud object %================================================================== function ptCloudOut = select(this, varargin) %select Select points specified by index. % % ptCloudOut = select(ptCloud, indices) returns a pointCloud % object that contains the points selected using linear % indices. % % ptCloudOut = select(ptCloud, row, column) returns a pointCloud % object that contains the points selected using row and % column subscripts. This syntax applies only to organized % point cloud (M-by-N-by-3). % % Example : Downsample a point cloud with fixed step % ------------------------------------------------- % ptCloud = pcread('teapot.ply'); % % % Downsample a point cloud with fixed step size % stepSize = 10; % indices = 1:stepSize:ptCloud.Count; % % ptCloudOut = select(ptCloud, indices); % % pcshow(ptCloudOut); narginchk(2, 3); if nargin == 2 indices = varargin{1}; validateattributes(indices, {'numeric'}, ... {'real','nonsparse', 'vector', 'integer'}, mfilename, 'indices'); else % Subscript syntax is only for organized point cloud if ndims(this.Location) ~= 3 error(message('vision:pointcloud:organizedPtCloudOnly')); end row = varargin{1}; column = varargin{2}; validateattributes(row, {'numeric'}, ... {'real','nonsparse', 'vector', 'integer'}, mfilename, 'row'); validateattributes(column, {'numeric'}, ... {'real','nonsparse', 'vector', 'integer'}, mfilename, 'column'); indices = sub2ind([size(this.Location,1), size(this.Location,2)], row, column); end % Obtain the subset for every property [loc, c, nv, intensity] = this.subsetImpl(indices); ptCloudOut = pointCloud(loc, 'Color', c, 'Normal', nv, ... 'Intensity', intensity); end %================================================================== % Remove invalid points from this point cloud object %================================================================== function [ptCloudOut, indices] = removeInvalidPoints(this) %removeInvalidPoints Remove invalid points. % % [ptCloudOut, indices] = removeInvalidPoints(ptCloud) removes % points whose coordinates contain Inf or NaN. The second % output, indices, is a vector of linear indices indicating % locations of valid points in the point cloud. % % Note : % ------ % An organized point cloud (M-by-N-by-3) will become % unorganized (X-by-3) after calling this function. % % Example : Remove NaN valued points from a point cloud % --------------------------------------------------------- % ptCloud = pointCloud(nan(100,3)) % % ptCloud = removeInvalidPoints(ptCloud) % Find all valid points tf = isfinite(this.Location); if ~this.IsOrganized indices = (sum(tf, 2) == 3); else indices = (sum(reshape(tf, [], 3), 2) == 3); end [loc, c, nv, I] = this.subsetImpl(indices); ptCloudOut = pointCloud(loc, 'Color', c, 'Normal', nv, 'Intensity', I); if nargout > 1 indices = find(indices); end end end methods %================================================================== % Writable Property %================================================================== function set.Color(this, value) validateattributes(value,{'uint8'}, {'real','nonsparse'}); if ~isempty(value) && ~isequal(size(value), size(this.Location)) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZColor')); end this.Color = value; end function set.Normal(this, value) validateattributes(value,{'single', 'double'}, {'real','nonsparse'}); if ~isempty(value) && ~isequal(size(value), size(this.Location)) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZNormal')); end if isa(this.Location,'double') %#ok<MCSUP> value = double(value); else value = single(value); end this.Normal = value; end function set.Intensity(this, value) validateattributes(value,{'single', 'double'}, {'real','nonsparse'}); if ~isempty(value) if ~this.IsOrganized && ~isequal(numel(value), this.Count) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZIntensity')); elseif this.IsOrganized && ~isequal(size(value), ... [size(this.Location,1),size(this.Location,2)]) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZIntensity')); end end if isa(this.Location,'double') %#ok<MCSUP> value = double(value); else value = single(value); end this.Intensity = value; end %================================================================== % Dependent Property %================================================================== function xlim = get.XLimits(this) tf = ~isnan(this.Location); if ~this.IsOrganized tf = (sum(tf, 2)==3); xlim = [min(this.Location(tf, 1)), max(this.Location(tf, 1))]; else tf = (sum(tf, 3)==3); X = this.Location(:, :, 1); xlim = [min(X(tf)), max(X(tf))]; end end %================================================================== function ylim = get.YLimits(this) tf = ~isnan(this.Location); if ~this.IsOrganized tf = (sum(tf, 2)==3); ylim = [min(this.Location(tf, 2)), max(this.Location(tf, 2))]; else tf = (sum(tf, 3)==3); Y = this.Location(:, :, 2); ylim = [min(Y(tf)), max(Y(tf))]; end end %================================================================== function zlim = get.ZLimits(this) tf = ~isnan(this.Location); if ~this.IsOrganized tf = (sum(tf, 2)==3); zlim = [min(this.Location(tf, 3)), max(this.Location(tf, 3))]; else tf = (sum(tf, 3)==3); Z = this.Location(:, :, 3); zlim = [min(Z(tf)), max(Z(tf))]; end end %================================================================== function count = get.Count(this) if ~this.IsOrganized count = size(this.Location, 1); else count = size(this.Location, 1)*size(this.Location, 2); end end end methods (Access = public, Hidden) %================================================================== % helper function to get subset for each property %================================================================== function [loc, c, nv, intensity] = subsetImpl(this, indices) if ~isempty(this.Location) if ~this.IsOrganized loc = this.Location(indices, :); else loc = reshape(this.Location, [], 3); loc = loc(indices, :); end else loc = zeros(0, 3, 'single'); end if nargout > 1 if ~isempty(this.Color) if ~this.IsOrganized c = this.Color(indices, :); else c = reshape(this.Color, [], 3); c = c(indices, :); end else c = uint8.empty; end end if nargout > 2 if ~isempty(this.Normal) if ~this.IsOrganized nv = this.Normal(indices, :); else nv = reshape(this.Normal, [], 3); nv = nv(indices, :); end else if isa(loc, 'single') nv = single.empty; else nv = double.empty; end end end if nargout > 3 if ~isempty(this.Intensity) if ~this.IsOrganized intensity = this.Intensity(indices); else intensity = this.Intensity(:); intensity = intensity(indices); end else if isa(loc, 'single') intensity = single.empty; else intensity = double.empty; end end end end %================================================================== % helper function to support multiple queries in KNN search % indices, dists: K-by-numQueries % valid: 1-by-K % Note, the algorithm may return less than K results for each % query. Therefore, only 1:valid(n) in n-th column of indices and % dists are valid results. Invalid indices are all zeros. %================================================================== function [indices, dists, valid] = multiQueryKNNSearchImpl(this, points, K) % Validate the inputs validateattributes(points, {'single', 'double'}, ... {'real', 'nonsparse', 'size', [NaN, 3]}, mfilename, 'points'); if isa(this.Location, 'single') points = single(points); else points = double(points); end validateattributes(K, {'single', 'double'}, ... {'nonsparse', 'scalar', 'positive', 'integer'}, mfilename, 'K'); K = min(double(K), this.Count); this.buildKdtree(); % Use exact search in Kdtree searchOpts.checks = 0; searchOpts.eps = 0; [indices, dists, valid] = this.Kdtree.knnSearch(points, K, searchOpts); end %================================================================== % helper function to compute normals % normals: the same size of the Location matrix % % Note, the algorithm uses PCA to fit local planes around a point, % and chooses the normal direction (inward/outward) arbitrarily. %================================================================== function normals = surfaceNormalImpl(this, K) % Reset K if there are not enough points K = min(double(K), this.Count); if this.Count <= 2 normals = NaN(size(this.Location), 'like', this.Location); return; end t = tic; this.buildKdtree(); if ~this.IsOrganized loc = this.Location; else loc = reshape(this.Location, [], 3); end % Use exact search in Kdtree searchOpts.checks = 0; searchOpts.eps = 0; % Find K nearest neighbors for each point [indices2, ~, valid2] = this.Kdtree.knnSearch(loc, K, searchOpts); fprintf('[MATLAB knnSearch] '); toc(t); t = tic; indices = selfKNNSearchImplGPU(loc, K, this.OrganizedLoc, this.UnorganizedToOrganizedInd); fprintf('[MATLAB selfKNNSearchImplGPU] '); toc(t); valid = uint32(ones(size(loc,1), 1) * K); % Find normal vectors for each point normals = visionPCANormal(loc, indices, valid); if this.IsOrganized normals = reshape(normals, size(this.Location)); end end end methods (Access = protected) %================================================================== % helper function to index data %================================================================== function buildKdtree(this) if isempty(this.Kdtree) % Build a Kdtree to index the data this.Kdtree = vision.internal.Kdtree(); createIndex = true; elseif this.Kdtree.needsReindex(this.Location) createIndex = true; else createIndex = false; end if createIndex this.Kdtree.index(this.Location); end end end methods(Static, Access=private) %================================================================== % load object %================================================================== function this = loadobj(s) if isfield(s, 'Version') this = pointCloud(s.Location,... 'Color', s.Color, ... 'Normal', s.Normal, ... 'Intensity', s.Intensity); else this = pointCloud(s.Location,... 'Color', s.Color, ... 'Normal', s.Normal); end end end methods(Access=private) %================================================================== % save object %================================================================== function s = saveobj(this) % save properties into struct s.Location = this.Location; s.Color = this.Color; s.Normal = this.Normal; s.Intensity = this.Intensity; s.Version = this.Version; end end methods(Access=protected) %================================================================== % copy object %================================================================== % Override copyElement method: function cpObj = copyElement(obj) % Make a copy except the internal Kdtree cpObj = pointCloud(obj.Location, 'Color', obj.Color, ... 'Normal', obj.Normal, 'Intensity', obj.Intensity); end end end %================================================================== % parameter validation %================================================================== function [xyzPoints, C, nv, I, O, U2O] = validateAndParseInputs(varargin) % Validate and parse inputs narginchk(1, 7); parser = inputParser; parser.CaseSensitive = false; % Parse the arguments according to the format of the first argument if ismatrix(varargin{1}) dims = [NaN, 3]; else dims = [NaN, NaN, 3]; end parser.addRequired('xyzPoints', @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse','size', dims})); parser.addParameter('Color', uint8([]), @(x)validateattributes(x,{'uint8', 'single', 'double'}, {'real','nonsparse'})); parser.addParameter('Normal', single([]), @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse'})); parser.addParameter('Intensity', single([]), @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse'})); parser.addRequired('OrganizedLoc', @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse','size', [NaN, NaN, 3]})); parser.addRequired('UnorganizedToOrganizedInd', @(x)validateattributes(x,{'double'}, {'real','nonsparse'})); parser.parse(varargin{:}); xyzPoints = parser.Results.xyzPoints; C = parser.Results.Color; if ~isa(C, 'uint8') C = im2uint8(C); end nv = parser.Results.Normal; if isa(xyzPoints, 'single') nv = single(nv); else nv = double(nv); end I = parser.Results.Intensity; if isa(xyzPoints, 'single') I = single(I); else I = double(I); end O = parser.Results.OrganizedLoc; U2O = int(parser.Results.UnorganizedToOrganizedInd); end %================================================================== % parameter validation for search %================================================================== function [doSort, maxLeafChecks] = validateAndParseSearchOption(varargin) persistent p; if isempty(p) % Validate and parse search options p = inputParser; p.CaseSensitive = false; p.addParameter('Sort', false, @(x)validateattributes(x, {'logical'}, {'scalar'})); p.addParameter('MaxLeafChecks', inf, @validateMaxLeafChecks); parser = p; else parser = p; end parser.parse(varargin{:}); doSort = parser.Results.Sort; maxLeafChecks = parser.Results.MaxLeafChecks; if isinf(maxLeafChecks) % 0 indicates infinite search in internal function maxLeafChecks = 0; end end %================================================================== function validateMaxLeafChecks(value) % Validate MaxLeafChecks if any(isinf(value)) validateattributes(value,{'double'}, {'real','nonsparse','scalar','positive'}); else validateattributes(value,{'double'}, {'real','nonsparse','scalar','integer','positive'}); end end
github
mcubelab/rgrasp-master
vis_cube.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/vis_cube.m
445
utf_8
8ba84e855aa99957bf175a602279772b
% Visualizes a 3D bounding box. % % Args: % bb3d - 3D bounding box struct % color - matlab color code, a single character % lineWidth - the width of each line of the square % % See: % create_bounding_box_3d.m % % Author: % Nathan Silberman ([email protected]) function vis_cube(bb3d, color, lineWidth) if nargin < 3 lineWidth = 0.5; end corners = get_corners_of_bb3d(bb3d); draw_square_3d(corners, color, lineWidth); end
github
mcubelab/rgrasp-master
ppmtopng_and_remove_ppm_nowait.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/ppmtopng_and_remove_ppm_nowait.m
247
utf_8
c826d1a0125128c901661f52cd5ff668
% Doing compression with pnmtopng is faster than use imwrite to save png function ppmtopng_and_remove_ppm_nowait(ppmfilepath, pngfilepath) system(sprintf('pnmtopng -compression 1 %s > %s && rm %s &', ppmfilepath, pngfilepath, ppmfilepath)); end
github
mcubelab/rgrasp-master
loadjson.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/loadjson.m
22,559
ibm852
09a85cd74f0d5c9b0eb6ba3396e252d5
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 492 2015-06-05 20:52:02Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) try string = fileread(fname); catch try string = urlread(['file://',fname]); catch string = urlread(['file://',fullfile(pwd,fname)]); end end else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); object.(valid_field(str))=val; if next_char == '}' break; end parse_char(','); end end parse_char('}'); if(isstruct(object)) object=struct2jdata(object); end %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=-1; if(isfield(varargin{1},'progressbar_')) pbar=varargin{1}.progressbar_; end if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ismatrix(object)) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len pos=skip_whitespace(pos,inStr,len); if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; pos=skip_whitespace(pos,inStr,len); end %%------------------------------------------------------------------------- function c = next_char global pos inStr len pos=skip_whitespace(pos,inStr,len); if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function newpos=skip_whitespace(pos,inStr,len) newpos=pos; while newpos <= len && isspace(inStr(newpos)) newpos = newpos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos); keyboard; pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr isoct currstr=inStr(pos:min(pos+30,end)); if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len if(isfield(varargin{1},'progressbar_')) waitbar(pos/len,varargin{1}.progressbar_,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end function opt=varargin2struct(varargin) % % opt=varargin2struct('param1',value1,'param2',value2,...) % or % opt=varargin2struct(...,optstruct,...) % % convert a series of input parameters into a structure % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % date: 2012/12/22 % % input: % 'param', value: the input parameters should be pairs of a string and a value % optstruct: if a parameter is a struct, the fields will be merged to the output struct % % output: % opt: a struct where opt.param1=value1, opt.param2=value2 ... % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % len=length(varargin); opt=struct; if(len==0) return; end i=1; while(i<=len) if(isstruct(varargin{i})) opt=mergestruct(opt,varargin{i}); elseif(ischar(varargin{i}) && i<len) opt=setfield(opt,lower(varargin{i}),varargin{i+1}); i=i+1; else error('input must be in the form of ...,''name'',value,... pairs or structs'); end i=i+1; end function val=jsonopt(key,default,varargin) % % val=jsonopt(key,default,optstruct) % % setting options based on a struct. The struct can be produced % by varargin2struct from a list of 'param','value' pairs % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % % $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $ % % input: % key: a string with which one look up a value from a struct % default: if the key does not exist, return default % optstruct: a struct where each sub-field is a key % % output: % val: if key exists, val=optstruct.key; otherwise val=default % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % val=default; if(nargin<=2) return; end opt=varargin{1}; if(isstruct(opt)) if(isfield(opt,key)) val=getfield(opt,key); elseif(isfield(opt,lower(key))) val=getfield(opt,lower(key)); end end function newdata=struct2jdata(data,varargin) % % newdata=struct2jdata(data,opt,...) % % convert a JData object (in the form of a struct array) into an array % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % % input: % data: a struct array. If data contains JData keywords in the first % level children, these fields are parsed and regrouped into a % data object (arrays, trees, graphs etc) based on JData % specification. The JData keywords are % "_ArrayType_", "_ArraySize_", "_ArrayData_" % "_ArrayIsSparse_", "_ArrayIsComplex_" % opt: (optional) a list of 'Param',value pairs for additional options % The supported options include % 'Recursive', if set to 1, will apply the conversion to % every child; 0 to disable % % output: % newdata: the covnerted data if the input data does contain a JData % structure; otherwise, the same as the input. % % examples: % obj=struct('_ArrayType_','double','_ArraySize_',[2 3], % '_ArrayIsSparse_',1 ,'_ArrayData_',null); % ubjdata=struct2jdata(obj); % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % fn=fieldnames(data); newdata=data; len=length(data); if(jsonopt('Recursive',0,varargin{:})==1) for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end function s=mergestruct(s1,s2) % % s=mergestruct(s1,s2) % % merge two struct objects into one % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % date: 2012/12/22 % % input: % s1,s2: a struct object, s1 and s2 can not be arrays % % output: % s: the merged struct object. fields in s1 and s2 will be combined in s. % % license: % BSD License, see LICENSE_BSD.txt files for details % % -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(~isstruct(s1) || ~isstruct(s2)) error('input parameters contain non-struct'); end if(length(s1)>1 || length(s2)>1) error('can not merge struct arrays'); end fn=fieldnames(s2); s=s1; for i=1:length(fn) s=setfield(s,fn{i},getfield(s2,fn{i})); end
github
mcubelab/rgrasp-master
vis_point_cloud.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/vis_point_cloud.m
2,400
utf_8
ff3f3e4dabfb83d67b26a57980abcbc4
% Visualizes a 3D point cloud. % % Args: % points3d - Nx3 or Nx2 point cloud where N is the number of points. % colors - (optional) Nx3 vector of colors or Nx1 vector of values which which % be scaled for visualization. % sizes - (optional) Nx1 vector of point sizes or a scalar value which is applied % to every point in the cloud. % sampleSize - (optional) the maximum number of points to show. Note that since matlab % is slow, around 5000 points is a good sampleSize is practice. % % Author: Nathan Silberman ([email protected]) function vis_point_cloud(points, colors, sizes, sampleSize) removeNaN = sum(isnan(points),2)>0; points(removeNaN,:)=[]; [N, D] = size(points); assert(D == 2 || D == 3, 'points must be Nx2 or Nx3'); if ~exist('colors', 'var') || isempty(colors) norms = sqrt(sum(points.^2, 2)); colors = values2colors(norms); elseif size(colors,1)>1 colors(removeNaN,:)=[]; end if ~exist('sizes', 'var') || isempty(sizes) sizes = ones(N, 1) * 10; elseif numel(sizes) == 1 sizes = sizes * ones(N, 1); elseif numel(sizes) ~= N error('sizes:size', 'sizes must be Nx1'); end if ~exist('sampleSize', 'var') || isempty(sampleSize) sampleSize = 5000; end % Sample the points, colors and sizes. N = size(points, 1); if N > sampleSize seq = randperm(size(points, 1)); seq = seq(1:sampleSize); points = points(seq, :); if size(colors,1)>1 colors = colors(seq, :); end sizes = sizes(seq); end switch size(points, 2) case 2 vis_2d(points, colors, sizes); case 3 vis_3d(points, colors, sizes); otherwise error('Points must be either 2 or 3d'); end axis equal; %view(0,90); %s view(0,8); end function colors = values2colors(values) values = scale_values(values); inds = ceil(values * 255) + 1; h = colormap(jet(256)); colors = h(inds, :); end function values = scale_values(values) if length(values(:))>1, values = values - min(values(:)); values = values ./ max(values(:)); end end function vis_3d(points, colors, sizes) X = points(:,1); Y = points(:,2); Z = points(:,3); scatter3(X, Y, Z, sizes, colors, 'filled'); end function vis_2d(points, colors, sizes) X = points(:,1); Y = points(:,2); scatter(X, Y, sizes, colors, 'filled'); xlabel('x'); ylabel('y'); end
github
mcubelab/rgrasp-master
pointCloudGPU.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/pointCloudGPU.m
36,079
utf_8
e94ea6fea9383d5041cf8f66b0f9523a
classdef pointCloudGPU < matlab.mixin.Copyable & vision.internal.EnforceScalarHandle % pointCloud Object for storing a 3-D point cloud. % ptCloud = pointCloud(xyzPoints) creates a point cloud object whose % coordinates are specified by an M-by-3 or M-by-N-by-3 matrix xyzPoints. % % ptCloud = pointCloud(xyzPoints, Name, Value) specifies additional % name-value pair arguments described below: % % 'Color' A matrix C specifying the color of each point in % the point cloud. If the coordinates are an M-by-3 % matrix, C must be an M-by-3 matrix, where each row % contains a corresponding RGB value. If the % coordinates are an M-by-N-by-3 matrix xyzPoints, C % must be an M-by-N-by-3 matrix containing % 1-by-1-by-3 RGB values for each point. % % Default: [] % % 'Normal' A matrix NV specifying the normal vector at % each point. If the coordinates are an M-by-3 % matrix, NV must be an M-by-3 matrix, where each row % contains a corresponding normal vector. If the % coordinates are an M-by-N-by-3 matrix xyzPoints, NV % must be an M-by-N-by-3 matrix containing % 1-by-1-by-3 normal vector for each point. % % Default: [] % % 'Intensity' A vector or matrix INT specifying the grayscale % intensity at each point. If the coordinates are an % M-by-3 matrix, INT must be an M-by-1 vector, where % each element contains a corresponding intensity % value. If the coordinates are an M-by-N-by-3 matrix % xyzPoints, INT must be an M-by-N matrix containing % intensity value for each point. % % Default: [] % % pointCloud properties : % Location - Matrix of [X, Y, Z] point coordinates (read only) % Color - Matrix of point RGB colors % Normal - Matrix of [NX, NY, NZ] point normal directions % Intensity - Matrix of point grayscale intensities % Count - Number of points (read only) % XLimits - The range of coordinates along X-axis (read only) % YLimits - The range of coordinates along Y-axis (read only) % ZLimits - The range of coordinates along Z-axis (read only) % % pointCloud methods: % findNearestNeighbors - Retrieve K nearest neighbors of a point % findNeighborsInRadius - Retrieve neighbors of a point within a specified radius % findPointsInROI - Retrieve points within a region of interest % select - Select points specified by index % removeInvalidPoints - Remove invalid points % % Notes % ----- % - To reduce memory use, point locations are suggested to be stored as single. % % Example : Find the shortest distance between two point clouds % ------------------------------------------------------------- % ptCloud1 = pointCloud(rand(100, 3, 'single')); % % ptCloud2 = pointCloud(1+rand(100, 3, 'single')); % % minDist = inf; % % % Find the nearest neighbor in ptCloud2 for each point in ptCloud1 % for i = 1 : ptCloud1.Count % point = ptCloud1.Location(i,:); % [~, dist] = findNearestNeighbors(ptCloud2, point, 1); % if dist < minDist % minDist = dist; % end % end % % See also pcshow, pcfromkinect, reconstructScene, pcread, pcwrite, % pctransform, pcdenoise, pcdownsample, pcregrigid, pcmerge % Copyright 2014 The MathWorks, Inc. % % References % ---------- % Marius Muja and David G. Lowe, "Fast Approximate Nearest Neighbors with % Automatic Algorithm Configuration", in International Conference on % Computer Vision Theory and Applications (VISAPP'09), 2009 properties (GetAccess = public, SetAccess = private) % Location is an M-by-3 or M-by-N-by-3 matrix. Each entry specifies % the x, y, z coordinates of a point. Location = single([]); end properties (Access = public) % Color is an M-by-3 or M-by-N-by-3 uint8 matrix. Each entry % specifies the RGB color of a point. Color = uint8([]); % Normal is an M-by-3 or M-by-N-by-3 matrix. Each entry % specifies the x, y, z component of a normal vector. Normal = single([]); % Intensity is an M-by-1 or M-by-N matrix. Each entry % specifies the grayscale intensity of a point. Intensity = single([]); end properties(Access = protected, Transient) Kdtree = []; end properties(Access = protected, Hidden) IsOrganized; Version = 1.1; % 2017a end properties(Dependent) % Count specifies the number of points in the point cloud. Count; % XLimits is a 1-by-2 vector that specifies the range of point % locations along X axis. XLimits; % YLimits is a 1-by-2 vector that specifies the range of point % locations along Y axis. YLimits; % ZLimits is a 1-by-2 vector that specifies the range of point % locations along Z axis. ZLimits; end methods %================================================================== % Constructor %================================================================== % pcd = pointCloud(xyzPoints); % pcd = pointCloud(..., 'Color', C); % pcd = pointCloud(..., 'Normal', nv); % pcd = pointCloud(..., 'Intensity', I); function this = pointCloudGPU(varargin) narginchk(1, 7); [xyzPoints, C, nv, I] = validateAndParseInputs(varargin{:}); this.Location = xyzPoints; this.IsOrganized = ~ismatrix(this.Location); % M-by-N-by-3 this.Color = C; this.Normal = nv; this.Intensity = I; end %================================================================== % K nearest neighbor search %================================================================== function [indices, dists] = findNearestNeighbors(this, point, K, varargin) %findNearestNeighbors Find the nearest neighbors of a point. % % [indices, dists] = findNearestNeighbors(ptCloud, point, K) % returns the K nearest neighbors of a query point. The point % is an [X, Y, Z] vector. indices is a column vector that % contains K linear indices to the stored points in the point % cloud. dists is a column vector that contains K Euclidean % distances to the point. % % [...] = findNearestNeighbors(... , Name, Value) % specifies additional name-value pairs described below: % % 'Sort' True or false. When set to true, % the returned indices are sorted in the % ascending order based on the distance % from a query point. % % Default: false % % 'MaxLeafChecks' An integer specifying the number of leaf % nodes that are searched in Kdtree. If the tree % is searched partially, the returned result may % not be exact. A larger number may increase the % search accuracy but reduce efficiency. When this % number is set to inf, the whole tree will be % searched to return exact search result. % % Default: inf % % Example : Find K-nearest neighbors % --------- % % Create a point cloud object with randomly generated points % ptCloud = pointCloud(1000*rand(100,3,'single')); % % % Define a query point and number of neighbors % point = [50, 50, 50]; % K = 10; % % % Get the indices and distances of 10 nearest points % [indices, dists] = findNearestNeighbors(ptCloud, point, K); narginchk(3, 7); validateattributes(point, {'single', 'double'}, ... {'real', 'nonsparse', 'finite', 'size', [1, 3]}, mfilename, 'point'); if isa(this.Location, 'single') point = single(point); else point = double(point); end validateattributes(K, {'single', 'double'}, ... {'nonsparse', 'scalar', 'positive', 'integer'}, mfilename, 'K'); K = min(double(K), numel(this.Location)/3); [doSort, MaxLeafChecks] = validateAndParseSearchOption(varargin{:}); % Use bruteforce if there are fewer than 500 points if numel(this.Location)/3 < 500 if ~this.IsOrganized allDists = visionSSDMetric(point', this.Location'); else allDists = visionSSDMetric(point', reshape(this.Location, [], 3)'); end % This function will ensure returning actual number of neighbors % The result is already sorted [dists, indices] = vision.internal.partialSort(allDists, K); tf = isfinite(dists); indices = indices(tf); dists = dists(tf); else this.buildKdtree(); searchOpts.checks = MaxLeafChecks; searchOpts.eps = 0; [indices, dists, valid] = this.Kdtree.knnSearch(point, K, searchOpts); % This step will ensure returning actual number of neighbors indices = indices(1:valid); dists = dists(1:valid); % Sort the result if specified if doSort [dists, IND] = sort(dists); indices = indices(IND); end end if nargout > 1 dists = sqrt(dists); end end %================================================================== % Radius search %================================================================== function [indices, dists] = findNeighborsInRadius(this, point, radius, varargin) %findNeighborsInRadius Find the neighbors within a radius. % % [indices, dists] = findNeighborsInRadius(ptCloud, point, radius) % returns the neighbors within a radius of a query point. % The query point is an [X, Y, Z] vector. indices is a column % vector that contains the linear indices to the stored points in % the point cloud object ptCloud. dists is a column vector that % contains the Euclidean distances to the query point. % % [...] = findNeighborsInRadius(... , Name, Value) specifies % specifies additional name-value pairs described below: % % 'Sort' True or false. When set to true, % the returned indices are sorted in the % ascending order based on the distance % from a query point. % % Default: false % % 'MaxLeafChecks' An integer specifying the number of leaf % nodes that are searched in Kdtree. If the tree % is searched partially, the returned result may % not be exact. A larger number may increase the % search accuracy but reduce efficiency. When this % number is set to inf, the whole tree will be % searched to return exact search result. % % Default: inf % % Example : Find neighbors within a given radius using Kdtree % ----------------------------------------------------------- % % Create a point cloud object with randomly generated points % ptCloud = pointCloud(100*rand(1000, 3, 'single')); % % % Define a query point and search radius % point = [50, 50, 50]; % radius = 5; % % % Get all the points within a radius % [indices, dists] = findNeighborsInRadius(ptCloud, point, radius); narginchk(3, 7); validateattributes(point, {'single', 'double'}, ... {'real', 'nonsparse', 'finite', 'size', [1, 3]}, mfilename, 'point'); if isa(this.Location, 'single') point = single(point); else point = double(point); end validateattributes(radius, {'single', 'double'}, ... {'nonsparse', 'scalar', 'nonnegative', 'finite'}, mfilename, 'radius'); radius = double(radius); [doSort, MaxLeafChecks] = validateAndParseSearchOption(varargin{:}); % Use bruteforce if there are less than 500 points if numel(this.Location)/3 < 500 if ~this.IsOrganized allDists = visionSSDMetric(point', this.Location'); else allDists = visionSSDMetric(point', reshape(this.Location, [], 3)'); end indices = uint32(find(allDists <= radius^2))'; dists = allDists(indices)'; tf = isfinite(dists); indices = indices(tf); dists = dists(tf); else this.buildKdtree(); searchOpts.checks = MaxLeafChecks; searchOpts.eps = 0; [indices, dists] = this.Kdtree.radiusSearch(point, radius, searchOpts); end % Sort the result if specified if doSort [dists, IND] = sort(dists); indices = indices(IND); end if nargout > 1 dists = sqrt(dists); end end %================================================================== % Box search %================================================================== function indices = findPointsInROI(this, roi) %findPointsInROI Find points within a region of interest. % % indices = findPointsInROI(ptCloud, roi) returns the points % within a region of interest, roi. The roi is a cuboid % specified as a 1-by-6 vector in the format of [xmin, xmax, % ymin, ymax, zmin, zmax]. indices is a column vector that % contains the linear indices to the stored points in the % point cloud object, ptCloud. % % Example : Find points within a given cuboid % ------------------------------------------- % % Create a point cloud object with randomly generated points % ptCloudA = pointCloud(100*rand(1000, 3, 'single')); % % % Define a cuboid % roi = [0, 50, 0, inf, 0, inf]; % % % Get all the points within the cuboid % indices = findPointsInROI(ptCloudA, roi); % ptCloudB = select(ptCloudA, indices); % % pcshow(ptCloudA.Location, 'r'); % hold on; % pcshow(ptCloudB.Location, 'g'); % hold off; narginchk(2, 2); validateattributes(roi, {'single', 'double'}, ... {'real', 'nonsparse', 'numel', 6}, mfilename, 'roi'); if isvector(roi) roi = reshape(roi, [2, 3])'; end if any(roi(:, 1) > roi(:, 2)) error(message('vision:pointcloud:invalidROI')); end roi = double(roi); % Use bruteforce if there are less than 500 points if numel(this.Location)/3 < 500 if ~this.IsOrganized tf = this.Location(:,1)>=roi(1)&this.Location(:,1)<=roi(4) ... &this.Location(:,2)>=roi(2)&this.Location(:,2)<=roi(5) ... &this.Location(:,3)>=roi(3)&this.Location(:,3)<=roi(6); indices = uint32(find(tf)); else tf = this.Location(:,:,1)>=roi(1)&this.Location(:,:,1)<=roi(4) ... &this.Location(:,:,2)>=roi(2)&this.Location(:,:,2)<=roi(5) ... &this.Location(:,:,3)>=roi(3)&this.Location(:,:,3)<=roi(6); indices = uint32(find(tf)); end else this.buildKdtree(); indices = this.Kdtree.boxSearch(roi); end end %================================================================== % Obtain a subset of this point cloud object %================================================================== function ptCloudOut = select(this, varargin) %select Select points specified by index. % % ptCloudOut = select(ptCloud, indices) returns a pointCloud % object that contains the points selected using linear % indices. % % ptCloudOut = select(ptCloud, row, column) returns a pointCloud % object that contains the points selected using row and % column subscripts. This syntax applies only to organized % point cloud (M-by-N-by-3). % % Example : Downsample a point cloud with fixed step % ------------------------------------------------- % ptCloud = pcread('teapot.ply'); % % % Downsample a point cloud with fixed step size % stepSize = 10; % indices = 1:stepSize:ptCloud.Count; % % ptCloudOut = select(ptCloud, indices); % % pcshow(ptCloudOut); narginchk(2, 3); if nargin == 2 indices = varargin{1}; validateattributes(indices, {'numeric'}, ... {'real','nonsparse', 'vector', 'integer'}, mfilename, 'indices'); else % Subscript syntax is only for organized point cloud if ndims(this.Location) ~= 3 error(message('vision:pointcloud:organizedPtCloudOnly')); end row = varargin{1}; column = varargin{2}; validateattributes(row, {'numeric'}, ... {'real','nonsparse', 'vector', 'integer'}, mfilename, 'row'); validateattributes(column, {'numeric'}, ... {'real','nonsparse', 'vector', 'integer'}, mfilename, 'column'); indices = sub2ind([size(this.Location,1), size(this.Location,2)], row, column); end % Obtain the subset for every property [loc, c, nv, intensity] = this.subsetImpl(indices); ptCloudOut = pointCloud(loc, 'Color', c, 'Normal', nv, ... 'Intensity', intensity); end %================================================================== % Remove invalid points from this point cloud object %================================================================== function [ptCloudOut, indices] = removeInvalidPoints(this) %removeInvalidPoints Remove invalid points. % % [ptCloudOut, indices] = removeInvalidPoints(ptCloud) removes % points whose coordinates contain Inf or NaN. The second % output, indices, is a vector of linear indices indicating % locations of valid points in the point cloud. % % Note : % ------ % An organized point cloud (M-by-N-by-3) will become % unorganized (X-by-3) after calling this function. % % Example : Remove NaN valued points from a point cloud % --------------------------------------------------------- % ptCloud = pointCloud(nan(100,3)) % % ptCloud = removeInvalidPoints(ptCloud) % Find all valid points tf = isfinite(this.Location); if ~this.IsOrganized indices = (sum(tf, 2) == 3); else indices = (sum(reshape(tf, [], 3), 2) == 3); end [loc, c, nv, I] = this.subsetImpl(indices); ptCloudOut = pointCloud(loc, 'Color', c, 'Normal', nv, 'Intensity', I); if nargout > 1 indices = find(indices); end end end methods %================================================================== % Writable Property %================================================================== function set.Color(this, value) validateattributes(value,{'uint8'}, {'real','nonsparse'}); if ~isempty(value) && ~isequal(size(value), size(this.Location)) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZColor')); end this.Color = value; end function set.Normal(this, value) validateattributes(value,{'single', 'double'}, {'real','nonsparse'}); if ~isempty(value) && ~isequal(size(value), size(this.Location)) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZNormal')); end if isa(this.Location,'double') %#ok<MCSUP> value = double(value); else value = single(value); end this.Normal = value; end function set.Intensity(this, value) validateattributes(value,{'single', 'double'}, {'real','nonsparse'}); if ~isempty(value) if ~this.IsOrganized && ~isequal(numel(value), this.Count) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZIntensity')); elseif this.IsOrganized && ~isequal(size(value), ... [size(this.Location,1),size(this.Location,2)]) %#ok<MCSUP> error(message('vision:pointcloud:unmatchedXYZIntensity')); end end if isa(this.Location,'double') %#ok<MCSUP> value = double(value); else value = single(value); end this.Intensity = value; end %================================================================== % Dependent Property %================================================================== function xlim = get.XLimits(this) tf = ~isnan(this.Location); if ~this.IsOrganized tf = (sum(tf, 2)==3); xlim = [min(this.Location(tf, 1)), max(this.Location(tf, 1))]; else tf = (sum(tf, 3)==3); X = this.Location(:, :, 1); xlim = [min(X(tf)), max(X(tf))]; end end %================================================================== function ylim = get.YLimits(this) tf = ~isnan(this.Location); if ~this.IsOrganized tf = (sum(tf, 2)==3); ylim = [min(this.Location(tf, 2)), max(this.Location(tf, 2))]; else tf = (sum(tf, 3)==3); Y = this.Location(:, :, 2); ylim = [min(Y(tf)), max(Y(tf))]; end end %================================================================== function zlim = get.ZLimits(this) tf = ~isnan(this.Location); if ~this.IsOrganized tf = (sum(tf, 2)==3); zlim = [min(this.Location(tf, 3)), max(this.Location(tf, 3))]; else tf = (sum(tf, 3)==3); Z = this.Location(:, :, 3); zlim = [min(Z(tf)), max(Z(tf))]; end end %================================================================== function count = get.Count(this) if ~this.IsOrganized count = size(this.Location, 1); else count = size(this.Location, 1)*size(this.Location, 2); end end end methods (Access = public, Hidden) %================================================================== % helper function to get subset for each property %================================================================== function [loc, c, nv, intensity] = subsetImpl(this, indices) if ~isempty(this.Location) if ~this.IsOrganized loc = this.Location(indices, :); else loc = reshape(this.Location, [], 3); loc = loc(indices, :); end else loc = zeros(0, 3, 'single'); end if nargout > 1 if ~isempty(this.Color) if ~this.IsOrganized c = this.Color(indices, :); else c = reshape(this.Color, [], 3); c = c(indices, :); end else c = uint8.empty; end end if nargout > 2 if ~isempty(this.Normal) if ~this.IsOrganized nv = this.Normal(indices, :); else nv = reshape(this.Normal, [], 3); nv = nv(indices, :); end else if isa(loc, 'single') nv = single.empty; else nv = double.empty; end end end if nargout > 3 if ~isempty(this.Intensity) if ~this.IsOrganized intensity = this.Intensity(indices); else intensity = this.Intensity(:); intensity = intensity(indices); end else if isa(loc, 'single') intensity = single.empty; else intensity = double.empty; end end end end %================================================================== % helper function to support multiple queries in KNN search % indices, dists: K-by-numQueries % valid: 1-by-K % Note, the algorithm may return less than K results for each % query. Therefore, only 1:valid(n) in n-th column of indices and % dists are valid results. Invalid indices are all zeros. %================================================================== function [indices, dists, valid] = multiQueryKNNSearchImpl(this, points, K) % Validate the inputs validateattributes(points, {'single', 'double'}, ... {'real', 'nonsparse', 'size', [NaN, 3]}, mfilename, 'points'); if isa(this.Location, 'single') points = single(points); else points = double(points); end validateattributes(K, {'single', 'double'}, ... {'nonsparse', 'scalar', 'positive', 'integer'}, mfilename, 'K'); K = min(double(K), this.Count); this.buildKdtree(); % Use exact search in Kdtree searchOpts.checks = 0; searchOpts.eps = 0; [indices, dists, valid] = this.Kdtree.knnSearch(points, K, searchOpts); end %================================================================== % helper function to compute normals % normals: the same size of the Location matrix % % Note, the algorithm uses PCA to fit local planes around a point, % and chooses the normal direction (inward/outward) arbitrarily. %================================================================== function normals = surfaceNormalImpl(this, K) % Reset K if there are not enough points K = min(double(K), this.Count); if this.Count <= 2 normals = NaN(size(this.Location), 'like', this.Location); return; end t = tic; this.buildKdtree(); if ~this.IsOrganized loc = this.Location; else loc = reshape(this.Location, [], 3); end % Use exact search in Kdtree searchOpts.checks = 0; searchOpts.eps = 0; % Find K nearest neighbors for each point [indices2, ~, valid2] = this.Kdtree.knnSearch(loc, K, searchOpts); fprintf('[MATLAB knnSearch] '); toc(t); t = tic; indices = selfKNNSearchImplGPU(loc, K); fprintf('[MATLAB selfKNNSearchImplGPU] '); toc(t); valid = uint32(ones(size(loc,1), 1) * K); % Find normal vectors for each point normals = visionPCANormal(loc, indices, valid); if this.IsOrganized normals = reshape(normals, size(this.Location)); end end end methods (Access = protected) %================================================================== % helper function to index data %================================================================== function buildKdtree(this) if isempty(this.Kdtree) % Build a Kdtree to index the data this.Kdtree = vision.internal.Kdtree(); createIndex = true; elseif this.Kdtree.needsReindex(this.Location) createIndex = true; else createIndex = false; end if createIndex this.Kdtree.index(this.Location); end end end methods(Static, Access=private) %================================================================== % load object %================================================================== function this = loadobj(s) if isfield(s, 'Version') this = pointCloud(s.Location,... 'Color', s.Color, ... 'Normal', s.Normal, ... 'Intensity', s.Intensity); else this = pointCloud(s.Location,... 'Color', s.Color, ... 'Normal', s.Normal); end end end methods(Access=private) %================================================================== % save object %================================================================== function s = saveobj(this) % save properties into struct s.Location = this.Location; s.Color = this.Color; s.Normal = this.Normal; s.Intensity = this.Intensity; s.Version = this.Version; end end methods(Access=protected) %================================================================== % copy object %================================================================== % Override copyElement method: function cpObj = copyElement(obj) % Make a copy except the internal Kdtree cpObj = pointCloud(obj.Location, 'Color', obj.Color, ... 'Normal', obj.Normal, 'Intensity', obj.Intensity); end end end %================================================================== % parameter validation %================================================================== function [xyzPoints, C, nv, I] = validateAndParseInputs(varargin) % Validate and parse inputs narginchk(1, 7); parser = inputParser; parser.CaseSensitive = false; % Parse the arguments according to the format of the first argument if ismatrix(varargin{1}) dims = [NaN, 3]; else dims = [NaN, NaN, 3]; end parser.addRequired('xyzPoints', @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse','size', dims})); parser.addParameter('Color', uint8([]), @(x)validateattributes(x,{'uint8', 'single', 'double'}, {'real','nonsparse'})); parser.addParameter('Normal', single([]), @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse'})); parser.addParameter('Intensity', single([]), @(x)validateattributes(x,{'single', 'double'}, {'real','nonsparse'})); parser.parse(varargin{:}); xyzPoints = parser.Results.xyzPoints; C = parser.Results.Color; if ~isa(C, 'uint8') C = im2uint8(C); end nv = parser.Results.Normal; if isa(xyzPoints, 'single') nv = single(nv); else nv = double(nv); end I = parser.Results.Intensity; if isa(xyzPoints, 'single') I = single(I); else I = double(I); end end %================================================================== % parameter validation for search %================================================================== function [doSort, maxLeafChecks] = validateAndParseSearchOption(varargin) persistent p; if isempty(p) % Validate and parse search options p = inputParser; p.CaseSensitive = false; p.addParameter('Sort', false, @(x)validateattributes(x, {'logical'}, {'scalar'})); p.addParameter('MaxLeafChecks', inf, @validateMaxLeafChecks); parser = p; else parser = p; end parser.parse(varargin{:}); doSort = parser.Results.Sort; maxLeafChecks = parser.Results.MaxLeafChecks; if isinf(maxLeafChecks) % 0 indicates infinite search in internal function maxLeafChecks = 0; end end %================================================================== function validateMaxLeafChecks(value) % Validate MaxLeafChecks if any(isinf(value)) validateattributes(value,{'double'}, {'real','nonsparse','scalar','positive'}); else validateattributes(value,{'double'}, {'real','nonsparse','scalar','integer','positive'}); end end
github
mcubelab/rgrasp-master
get_corners_of_bb3d.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/get_corners_of_bb3d.m
1,861
utf_8
d4a28e913ae46cbc141499a0146c6964
% Gets the 3D coordinates of the corners of a 3D bounding box. % % Args: % bb3d - 3D bounding box struct. % % Returns: % corners - 8x3 matrix of 3D coordinates. % % See: % create_bounding_box_3d.m % % Author: Nathan Silberman ([email protected]) function corners = get_corners_of_bb3d(bb3d) corners = zeros(8, 3); % Order the bases. [~, inds] = sort(abs(bb3d.basis(:,1)), 'descend'); basis = bb3d.basis(inds, :); coeffs = bb3d.coeffs(inds); [~, inds] = sort(abs(basis(2:3,2)), 'descend'); if inds(1) == 2 basis(2:3,:) = flipdim(basis(2:3,:), 1); coeffs(2:3) = flipdim(coeffs(2:3), 2); end % Now, we know the basis vectors are orders X, Y, Z. Next, flip the basis % vectors towards the viewer. basis = flip_towards_viewer(basis, repmat(bb3d.centroid, [3 1])); coeffs = abs(coeffs); corners(1,:) = -basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3); corners(2,:) = basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3); corners(3,:) = basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3); corners(4,:) = -basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + basis(3,:) * coeffs(3); corners(5,:) = -basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3); corners(6,:) = basis(1,:) * coeffs(1) + basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3); corners(7,:) = basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3); corners(8,:) = -basis(1,:) * coeffs(1) + -basis(2,:) * coeffs(2) + -basis(3,:) * coeffs(3); corners = corners + repmat(bb3d.centroid, [8 1]); end function normals = flip_towards_viewer(normals, points) points = points ./ repmat(sqrt(sum(points.^2, 2)), [1, 3]); proj = sum(points .* normals, 2); flip = proj > 0; normals(flip, :) = -normals(flip, :); end
github
mcubelab/rgrasp-master
pcregrigidGPU.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/pcregrigidGPU.m
19,811
utf_8
350410e2e891575befca65c50a6b58ec
function [tform, movingReg, rmse] = pcregrigid(moving, fixed, varargin) %PCREGRIGID Register two point clouds with ICP algorithm. % tform = PCREGRIGID(moving, fixed) returns the rigid transformation that % registers the moving point cloud with the fixed point cloud. moving and % fixed are pointCloud object. tform is an affine3d object that describes % the rigid 3-D transform. The rigid transformation between the moving % and fixed are estimated by Iterative Closest Point (ICP) algorithm. % Consider downsampling point clouds using pcdownsample before using % PCREGRIGID to improve accuracy and efficiency of registration. % % [tform, movingReg] = PCREGRIGID(moving, fixed) additionally % returns the transformed point cloud, movingReg, that is aligned with % the fixed point cloud. % % [..., rmse] = PCREGRIGID(moving, fixed) additionally returns the % root mean squared error of the Euclidean distance between the aligned % point clouds. % % [...] = PCREGRIGID(...,Name, Value) specifies additional % name-value pairs described below: % % 'Metric' A string used to specify the metric of the % minimization function. The ICP algorithm minimized % the distance between the two point clouds according % to the given metric. Valid strings are % 'pointToPoint' and 'pointToPlane'. Setting Metric % to 'pointToPlane' can reduce the number of % iterations to process. However, this metric % requires extra algorithmic steps within each % iteration. The 'pointToPlane' metric helps % registration of planar surfaces. % % Default: 'pointToPoint' % % 'Extrapolate' A boolean to turn on/off the extrapolation step % that traces out a path in the registration state % space, described in the original paper of ICP by % Besl and McKay (1992). This may reduce the number % of iterations to converge. % % Default: false % % 'InlierRatio' A scalar to specify the percentage of inliers. % During an ICP iteration, every point in the moving % point cloud is matched to its nearest neighbor in % the fixed point cloud. The pair of matched points % is considered as an inlier if its Euclidean % distance falls into the given percentage of the % distribution of matching distance. By default, all % matching pairs are used. % % Default: 1 % % 'MaxIterations' A positive integer to specify the maximum number % of iterations before ICP stops. % % Default: 20 % % 'Tolerance' A 2-element vector, [Tdiff, Rdiff], to specify % the tolerance of absolute difference in translation % and rotation estimated in consecutive ICP % iterations. Tdiff measures the Euclidean distance % between two translation vectors, while Rdiff % measures the angular difference in radians. The % algorithm stops when the average difference between % estimated rigid transformations in the three most % recent consecutive iterations falls below the % specified tolerance value. % % Default: [0.01, 0.009] % % 'InitialTransform' An affine3d object to specify the initial rigid % transformation. This is useful when a coarse % estimation can be provided externally. % % Default: affine3d() % % 'Verbose' Set true to display progress information. % % Default: false % % Notes % ----- % - The registration algorithm is based on Iterative Closest Point (ICP) % algorithm, which is an iterative process. Best performance might % require adjusting the options for different data. % % - Point cloud normals are required by the registration algorithm when % 'pointToPlane' metric is chosen. If the Normal property of the second % input is empty, the function fills it. % % - When the Normal property is filled automatically, the number of % points, K, to fit local plane is set to 6. This default may not work % under all circumstances. If the registration with 'pointToPlane' % metric fails, consider calling pcnormals function with a custom value % of K. % % Class Support % ------------- % moving and fixed must be pointCloud object. % % Example: Align two point clouds % -------------------------------- % ptCloud = pcread('teapot.ply'); % figure % pcshow(ptCloud) % title('Teapot') % % % Create a transform object with 30 degree rotation along z-axis and % % translation [5, 5, 10] % A = [cos(pi/6) sin(pi/6) 0 0; ... % -sin(pi/6) cos(pi/6) 0 0; ... % 0 0 1 0; ... % 5 5 10 1]; % tform1 = affine3d(A); % % % Transform the point cloud % ptCloudTformed = pctransform(ptCloud, tform1); % % figure % pcshow(ptCloudTformed) % title('Transformed Teapot') % % % Apply the rigid registration % [tform, ptCloudReg] = pcregrigid(ptCloudTformed, ptCloud, 'Extrapolate', true); % % % Visualize the alignment % pcshowpair(ptCloud, ptCloudReg) % % % Compare the result with the true transformation % disp(tform1.T); % tform2 = invert(tform); % disp(tform2.T); % % See also pointCloud, pctransform, affine3d, pcshow, pcdownsample, % pcshowpair, pcdenoise, pcmerge % Copyright 2014 The MathWorks, Inc. % % References % ---------- % Besl, Paul J.; N.D. McKay (1992). "A Method for Registration of 3-D % Shapes". IEEE Trans. on Pattern Analysis and Machine Intelligence (Los % Alamitos, CA, USA: IEEE Computer Society) 14 (2): 239-256. % % Chen, Yang; Gerard Medioni (1991). "Object modelling by registration of % multiple range images". Image Vision Comput. (Newton, MA, USA: % Butterworth-Heinemann): 145-155 % Validate inputs [metric, doExtrapolate, inlierRatio, maxIterations, tolerance, ... initialTransform, verbose] = validateAndParseOptInputs(moving, fixed, varargin{:}); printer = vision.internal.MessagePrinter.configure(verbose); % A copy of the input with unorganized M-by-3 data ptCloudA = removeInvalidPoints(moving); [ptCloudB, validPtCloudIndices] = removeInvalidPoints(fixed); % At least three points are needed to determine a 3-D transformation if ptCloudA.Count < 3 || ptCloudB.Count < 3 error(message('vision:pointcloud:notEnoughPoints')); end % Normal vector is needed for PointToPlane metric if strcmpi(metric, 'PointToPlane') % Compute the unit normal vector if it is not provided. if isempty(fixed.Normal) fixedCount = fixed.Count; % Use 6 neighboring points to estimate a normal vector. You may use % pcnormals with customized parameter to compute normals upfront. fixed.Normal = surfaceNormalImpl(fixed, 6); ptCloudB.Normal = [fixed.Normal(validPtCloudIndices), ... fixed.Normal(validPtCloudIndices + fixedCount), ... fixed.Normal(validPtCloudIndices + fixedCount * 2)]; end % Remove points if their normals are invalid tf = isfinite(ptCloudB.Normal); validIndices = find(sum(tf, 2) == 3); if numel(validIndices) < ptCloudB.Count [loc, ~, nv] = subsetImpl(ptCloudB, validIndices); ptCloudB = pointCloud(loc, 'Normal', nv); if ptCloudB.Count < 3 error(message('vision:pointcloud:notEnoughPoints')); end end end Rs = zeros(3, 3, maxIterations+1); Ts = zeros(3, maxIterations+1); % Quaternion and translation vector qs = [ones(1, maxIterations+1); zeros(6, maxIterations+1)]; % The difference of quaternion and translation vector in consecutive % iterations dq = zeros(7, maxIterations+1); % The angle between quaternion and translation vectors in consecutive % iterations dTheta = zeros(maxIterations+1, 1); % RMSE Err = zeros(maxIterations+1, 1); % Apply the initial condition. % We use pre-multiplication format in this algorithm. Rs(:,:,1) = initialTransform.T(1:3, 1:3)'; Ts(:,1) = initialTransform.T(4, 1:3)'; qs(:,1) = [vision.internal.quaternion.rotationToQuaternion(Rs(:,:,1)); Ts(:,1)]; locA = ptCloudA.Location; if qs(1) ~= 0 || any(qs(2:end,1)) locA = rigidTransform(ptCloudA.Location, Rs(:,:,1), Ts(:,1)); end stopIteration = maxIterations; upperBound = max(1, round(inlierRatio(1)*ptCloudA.Count)); % Start ICP iterations for i = 1 : maxIterations printer.linebreak; printer.print('--------------------------------------------\n'); printer.printMessage('vision:pointcloud:icpIteration',i); printer.printMessageNoReturn('vision:pointcloud:findCorrespondenceStart'); % Find the correspondence [indices, dists] = multiQueryKNNSearchImplGPU(ptCloudB, locA); % Remove outliers keepInlierA = false(ptCloudA.Count, 1); [~, idx] = sort(dists); keepInlierA(idx(1:upperBound)) = true; inlierIndicesA = find(keepInlierA); inlierIndicesB = indices(keepInlierA); inlierDist = dists(keepInlierA); if numel(inlierIndicesA) < 3 error(message('vision:pointcloud:notEnoughPoints')); end printer.printMessage('vision:pointcloud:stepCompleted'); if i == 1 Err(i) = sqrt(sum(inlierDist)/length(inlierDist)); end printer.printMessageNoReturn('vision:pointcloud:estimateTransformStart'); % Estimate transformation given correspondences if strcmpi(metric, 'PointToPoint') [R, T] = vision.internal.calibration.rigidTransform3D(... locA(inlierIndicesA, :), ... ptCloudB.Location(inlierIndicesB, :)); else % PointToPlane [R, T] = pointToPlaneMetric(locA(inlierIndicesA, :), ... ptCloudB.Location(inlierIndicesB, :), ptCloudB.Normal(inlierIndicesB, :)); end % Bad correspondence may lead to singular matrix if any(isnan(T))||any(isnan(R(:))) error(message('vision:pointcloud:singularMatrix')); end % Update the total transformation Rs(:,:,i+1) = R * Rs(:,:,i); Ts(:,i+1) = R * Ts(:,i) + T; printer.printMessage('vision:pointcloud:stepCompleted'); % RMSE locA = rigidTransform(ptCloudA.Location, Rs(:,:,i+1), Ts(:,i+1)); squaredError = sum((locA(inlierIndicesA, :) - ptCloudB.Location(inlierIndicesB, :)).^2, 2); Err(i+1) = sqrt(sum(squaredError)/length(squaredError)); % Convert to vector representation qs(:,i+1) = [vision.internal.quaternion.rotationToQuaternion(Rs(:,:,i+1)); Ts(:,i+1)]; % With extrapolation, we might be able to converge faster if doExtrapolate printer.printMessageNoReturn('vision:pointcloud:updateTransformStart'); extrapolateInTransformSpace; printer.printMessage('vision:pointcloud:stepCompleted'); end % Check convergence % Compute the mean difference in R/T from the recent three iterations. [dR, dT] = getChangesInTransformation; printer.printMessage('vision:pointcloud:checkConverge',num2str(tdiff), num2str(rdiff), num2str(Err(i+1))); % Stop ICP if it already converges if dT <= tolerance(1) && dR <= tolerance(2) stopIteration = i; break; end end % Make the R to be orthogonal as much as possible R = Rs(:,:,stopIteration+1)'; [U, ~, V] = svd(R); R = U * V'; tformMatrix = [R, zeros(3,1);... Ts(:, stopIteration+1)', 1]; tform = affine3d(tformMatrix); rmse = Err(stopIteration+1); printer.linebreak; printer.print('--------------------------------------------\n'); printer.printMessage('vision:pointcloud:icpSummary',stopIteration, num2str(rmse)); if nargout >= 2 movingReg = pctransform(moving, tform); end %====================================================================== % Nested function to perform extrapolation % Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes. % IEEE Transactions on pattern analysis and machine intelligence, p245. %====================================================================== function extrapolateInTransformSpace dq(:,i+1) = qs(:,i+1) - qs(:,i); n1 = norm(dq(:,i)); n2 = norm(dq(:,i+1)); dTheta(i+1) = (180/pi)*acos(dot(dq(:,i),dq(:,i+1))/(n1*n2)); angleThreshold = 10; scaleFactor = 25; if i > 2 && dTheta(i+1) < angleThreshold && dTheta(i) < angleThreshold d = [Err(i+1), Err(i), Err(i-1)]; v = [0, -n2, -n1-n2]; vmax = scaleFactor * n2; dv = extrapolate(v,d,vmax); if dv ~= 0 q = qs(:,i+1) + dv * dq(:,i+1)/n2; q(1:4) = q(1:4)/norm(q(1:4)); % Update transformation and data qs(:,i+1) = q; Rs(:,:,i+1) = vision.internal.quaternion.quaternionToRotation(q(1:4)); Ts(:,i+1) = q(5:7); locA = rigidTransform(ptCloudA.Location, Rs(:,:,i+1), Ts(:,i+1)); end end end %====================================================================== % Nested function to compute the changes in rotation and translation %====================================================================== function [dR, dT] = getChangesInTransformation dR = 0; dT = 0; count = 0; for k = max(i-2,1):i % Rotation difference in radians rdiff = acos(dot(qs(1:4,k),qs(1:4,k+1))/(norm(qs(1:4,k))*norm(qs(1:4,k+1)))); % Euclidean difference tdiff = sqrt(sum((Ts(:,k)-Ts(:,k+1)).^2)); dR = dR + rdiff; dT = dT + tdiff; count = count + 1; end dT = dT/count; dR = dR/count; end end %========================================================================== % Parameter validation %========================================================================== function [metric, doExtrapolate, inlierRatio, maxIterations, tolerance, ... initialTransform, verbose] = validateAndParseOptInputs(moving, fixed, varargin) if ~isa(moving, 'pointCloud') error(message('vision:pointcloud:notPointCloudObject','moving')); end if ~isa(fixed, 'pointCloud') error(message('vision:pointcloud:notPointCloudObject','fixed')); end persistent p; if isempty(p) % Set input parser defaults = struct(... 'Metric', 'PointToPoint', ... 'Extrapolate', false, ... 'InlierRatio', 1.0,... 'MaxIterations', 20,... 'Tolerance', [0.01, 0.009],... 'InitialTransform', affine3d(),... 'Verbose', false); p = inputParser; p.CaseSensitive = false; p.addParameter('Metric', defaults.Metric); p.addParameter('Extrapolate', defaults.Extrapolate, ... @(x)validateattributes(x,{'logical'}, {'scalar','nonempty'})); p.addParameter('InlierRatio', defaults.InlierRatio, ... @(x)validateattributes(x,{'single', 'double'}, {'real','nonempty','scalar','>',0,'<=',1})); p.addParameter('MaxIterations', defaults.MaxIterations, ... @(x)validateattributes(x,{'single', 'double'}, {'scalar','integer'})); p.addParameter('Tolerance', defaults.Tolerance, ... @(x)validateattributes(x,{'single', 'double'}, {'real','nonnegative','numel', 2})); p.addParameter('InitialTransform', defaults.InitialTransform, ... @(x)validateattributes(x,{'affine3d'}, {'scalar'})); p.addParameter('Verbose', defaults.Verbose, ... @(x)validateattributes(x,{'logical'}, {'scalar','nonempty'})); parser = p; else parser = p; end parser.parse(varargin{:}); metric = validatestring(parser.Results.Metric, {'PointToPoint', 'PointToPlane'}, mfilename, 'Metric'); doExtrapolate = parser.Results.Extrapolate; inlierRatio = parser.Results.InlierRatio; maxIterations = parser.Results.MaxIterations; tolerance = parser.Results.Tolerance; initialTransform = parser.Results.InitialTransform; if ~(isRigidTransform(initialTransform)) error(message('vision:pointcloud:rigidTransformOnly')); end verbose = parser.Results.Verbose; end %========================================================================== % Determine if transformation is rigid transformation %========================================================================== function tf = isRigidTransform(tform) singularValues = svd(tform.T(1:tform.Dimensionality,1:tform.Dimensionality)); tf = max(singularValues)-min(singularValues) < 100*eps(max(singularValues(:))); tf = tf && abs(det(tform.T)-1) < 100*eps(class(tform.T)); end %========================================================================== function B = rigidTransform(A, R, T) B = A * R'; B(:,1) = B(:,1) + T(1); B(:,2) = B(:,2) + T(2); B(:,3) = B(:,3) + T(3); end %========================================================================== % Solve the following minimization problem: % min_{R, T} sum(|dot(R*p+T-q,nv)|^2) % % p, q, nv are all N-by-3 matrix, and nv is the unit normal at q % % Here the problem is solved by linear approximation to the rotation matrix % when the angle is small. %========================================================================== function [R, T] = pointToPlaneMetric(p, q, nv) % Set up the linear system cn = [cross(p,nv,2),nv]; C = cn'*cn; qp = q-p; b = [sum(sum(qp.*repmat(cn(:,1),1,3).*nv, 2)); sum(sum(qp.*repmat(cn(:,2),1,3).*nv, 2)); sum(sum(qp.*repmat(cn(:,3),1,3).*nv, 2)); sum(sum(qp.*repmat(cn(:,4),1,3).*nv, 2)); sum(sum(qp.*repmat(cn(:,5),1,3).*nv, 2)); sum(sum(qp.*repmat(cn(:,6),1,3).*nv, 2))]; % X is [alpha, beta, gamma, Tx, Ty, Tz] X = C\b; cx = cos(X(1)); cy = cos(X(2)); cz = cos(X(3)); sx = sin(X(1)); sy = sin(X(2)); sz = sin(X(3)); R = [cy*cz, sx*sy*cz-cx*sz, cx*sy*cz+sx*sz; cy*sz, cx*cz+sx*sy*sz, cx*sy*sz-sx*cz; -sy, sx*cy, cx*cy]; T = X(4:6); end %========================================================================== % Extrapolation in quaternion space. Details are found in: % Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes. % IEEE Transactions on pattern analysis and machine intelligence, 239-256. %========================================================================== function dv = extrapolate(v,d,vmax) p1 = polyfit(v,d,1); % linear fit p2 = polyfit(v,d,2); % parabolic fit v1 = -p1(2)/p1(1); % linear zero crossing point v2 = -p2(2)/(2*p2(1)); % polynomial top point if (issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1])) % Parabolic update dv = v2; elseif (issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])... || (v2 < 0 && issorted([0 v1 vmax]))) % Line update dv = v1; elseif (v1 > vmax && v2 > vmax) % Maximum update dv = vmax; else % No extrapolation dv = 0; end end
github
mcubelab/rgrasp-master
vis_line.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/vis_line.m
845
utf_8
ea51e5d49df00cb5106f03a9ea6e0c1f
% Visualizes a line in 2D or 3D space % % Args: % p1 - 1x2 or 1x3 point % p2 - 1x2 or 1x3 point % color - matlab color code, a single character % lineWidth - the width of the drawn line % % Author: Nathan Silberman ([email protected]) function vis_line(p1, p2, color, lineWidth) if nargin < 3 color = 'b'; end if nargin < 4 lineWidth = 0.5; end % Make sure theyre the same size. assert(ndims(p1) == ndims(p2), 'Vectors are of different dimensions'); assert(all(size(p1) == size(p2)), 'Vectors are of different dimensions'); switch numel(p1) case 2 line([p1(1) p2(1)], [p1(2) p2(2)], 'Color', color); case 3 line([p1(1) p2(1)], [p1(2) p2(2)], [p1(3) p2(3)], 'Color', color, 'LineWidth', lineWidth); otherwise error('vectors must be either 2 or 3 dimensional'); end end
github
mcubelab/rgrasp-master
BBfromPoints.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/utils/BBfromPoints.m
1,397
utf_8
2f2824b485191037c1983b5e9ff66fd5
function [bb3dAlginedZ,bb3dTight] = BBfromPoints(objPts) % objPts is 3xN point could [coeffPCA,scorePCA,latentPCA] = pca(objPts'); Rot = [coeffPCA(:,1),coeffPCA(:,2),cross(coeffPCA(:,1),coeffPCA(:,2))]; % Follow righthand rule Vproj = Rot'*objPts; [projmin] = min(Vproj,[],2); [projmax] = max(Vproj,[],2); centroid = Rot*[0.5*(projmax(1)+projmin(1));... 0.5*(projmax(2)+projmin(2)); ... 0.5*(projmax(3)+projmin(3))]; bb3dTight.basis = Rot'; bb3dTight.coeffs = [projmax(1)-projmin(1), projmax(2)-projmin(2), projmax(3)-projmin(3)]/2; bb3dTight.centroid = centroid'; bb3dAlginedZ = getBBAlginedZ(objPts); end function bb3dAlginedZ = getBBAlginedZ(objPts) zmin = min(objPts(3,:)); zmax = max(objPts(3,:)); [C,V]= pca(objPts(1:2,:)'); Vproj = C'*objPts(1:2,:); [projmin] = min(Vproj,[],2); [projmax] = max(Vproj,[],2); bb3dAlginedZ = []; bb3dAlginedZ.basis = [C' [0;0]; 0 0 1]; % one row is one basis centroid2D = C*[0.5*(projmax(1)+projmin(1)); 0.5*(projmax(2)+projmin(2))]; bb3dAlginedZ.coeffs = [projmax(1)-projmin(1), projmax(2)-projmin(2), zmax-zmin]/2; bb3dAlginedZ.centroid = [centroid2D(1), centroid2D(2), 0.5*(zmax+zmin)]; end
github
mcubelab/rgrasp-master
warpFL.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/SIFTflow/warpFL.m
212
utf_8
8a88e59d40dc4a442477f98d01b9301b
% warp i2 according to flow field in vx vy function [warpI2,I]=warp(i2,vx,vy) [M,N]=size(i2); [x,y]=meshgrid(1:N,1:M); warpI2=interp2(x,y,i2,x+vx,y+vy,'bicubic'); I=find(isnan(warpI2)); warpI2(I)=zeros(size(I));
github
mcubelab/rgrasp-master
computeColor.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/SIFTflow/computeColor.m
3,142
utf_8
a36a650437bc93d4d8ffe079fe712901
function img = computeColor(u,v) % computeColor color codes flow field U, V % According to the c++ source code of Daniel Scharstein % Contact: [email protected] % Author: Deqing Sun, Department of Computer Science, Brown University % Contact: [email protected] % $Date: 2007-10-31 21:20:30 (Wed, 31 Oct 2006) $ % Copyright 2007, Deqing Sun. % % All Rights Reserved % % Permission to use, copy, modify, and distribute this software and its % documentation for any purpose other than its incorporation into a % commercial product is hereby granted without fee, provided that the % above copyright notice appear in all copies and that both that % copyright notice and this permission notice appear in supporting % documentation, and that the name of the author and Brown University not be used in % advertising or publicity pertaining to distribution of the software % without specific, written prior permission. % % THE AUTHOR AND BROWN UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, % INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY % PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR OR BROWN UNIVERSITY BE LIABLE FOR % ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES % WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN % ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF % OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. nanIdx = isnan(u) | isnan(v); u(nanIdx) = 0; v(nanIdx) = 0; colorwheel = makeColorwheel(); ncols = size(colorwheel, 1); rad = sqrt(u.^2+v.^2); a = atan2(-v, -u)/pi; fk = (a+1) /2 * (ncols-1) + 1; % -1~1 maped to 1~ncols k0 = floor(fk); % 1, 2, ..., ncols k1 = k0+1; k1(k1==ncols+1) = 1; f = fk - k0; for i = 1:size(colorwheel,2) tmp = colorwheel(:,i); col0 = tmp(k0)/255; col1 = tmp(k1)/255; col = (1-f).*col0 + f.*col1; idx = rad <= 1; col(idx) = 1-rad(idx).*(1-col(idx)); % increase saturation with radius col(~idx) = col(~idx)*0.75; % out of range img(:,:, i) = uint8(floor(255*col.*(1-nanIdx))); end; %% function colorwheel = makeColorwheel() % color encoding scheme % adapted from the color circle idea described at % http://members.shaw.ca/quadibloc/other/colint.htm RY = 15; YG = 6; GC = 4; CB = 11; BM = 13; MR = 6; ncols = RY + YG + GC + CB + BM + MR; colorwheel = zeros(ncols, 3); % r g b col = 0; %RY colorwheel(1:RY, 1) = 255; colorwheel(1:RY, 2) = floor(255*(0:RY-1)/RY)'; col = col+RY; %YG colorwheel(col+(1:YG), 1) = 255 - floor(255*(0:YG-1)/YG)'; colorwheel(col+(1:YG), 2) = 255; col = col+YG; %GC colorwheel(col+(1:GC), 2) = 255; colorwheel(col+(1:GC), 3) = floor(255*(0:GC-1)/GC)'; col = col+GC; %CB colorwheel(col+(1:CB), 2) = 255 - floor(255*(0:CB-1)/CB)'; colorwheel(col+(1:CB), 3) = 255; col = col+CB; %BM colorwheel(col+(1:BM), 3) = 255; colorwheel(col+(1:BM), 1) = floor(255*(0:BM-1)/BM)'; col = col+BM; %MR colorwheel(col+(1:MR), 3) = 255 - floor(255*(0:MR-1)/MR)'; colorwheel(col+(1:MR), 1) = 255;
github
mcubelab/rgrasp-master
SIFTflowc2f.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/SIFTflow/SIFTflowc2f.m
5,485
utf_8
a5d8f4d01080d208613afeb9cce2e799
% function to do coarse to fine SIFT flow matching function [vx,vy,energylist]=SIFTflowc2f(im1,im2,SIFTflowpara,isdisplay,Segmentation) if isfield(SIFTflowpara,'alpha') alpha=SIFTflowpara.alpha; else alpha=0.01; end if isfield(SIFTflowpara,'d') d=SIFTflowpara.d; else d=alpha*20; end if isfield(SIFTflowpara,'gamma') gamma=SIFTflowpara.gamma; else gamma=0.001; end if isfield(SIFTflowpara,'nlevels') nlevels=SIFTflowpara.nlevels; else nlevels=4; end if isfield(SIFTflowpara,'wsize') wsize=SIFTflowpara.wsize; else wsize=3; end if isfield(SIFTflowpara,'topwsize') topwsize=SIFTflowpara.topwsize; else topwsize=10; end if isfield(SIFTflowpara,'nIterations') nIterations=SIFTflowpara.nIterations; else nIterations=40; end if isfield(SIFTflowpara,'nTopIterations') nTopIterations=SIFTflowpara.nTopIterations; else nTopIterations=100; end if exist('isdisplay','var')~=1 isdisplay=false; end if exist('Segmentation','var')==1 IsSegmentation=true; else IsSegmentation=false; end % build the pyramid pyrd(1).im1=im1; pyrd(1).im2=im2; if IsSegmentation pyrd(1).seg=Segmentation; end for i=2:nlevels pyrd(i).im1=imresize(imfilter(pyrd(i-1).im1,fspecial('gaussian',5,0.67),'same','replicate'),0.5,'bicubic'); pyrd(i).im2=imresize(imfilter(pyrd(i-1).im2,fspecial('gaussian',5,0.67),'same','replicate'),0.5,'bicubic'); % pyrd(i).im1 = reduceImage(pyrd(i-1).im1); % pyrd(i).im2 = reduceImage(pyrd(i-1).im2); if IsSegmentation pyrd(i).seg=imresize(pyrd(i-1).seg,0.5,'nearest'); end end for i=1:nlevels [height,width,nchannels]=size(pyrd(i).im1); [height2,width2,nchannels]=size(pyrd(i).im2); [xx,yy]=meshgrid(1:width,1:height); pyrd(i).xx=round((xx-1)*(width2-1)/(width-1)+1-xx); pyrd(i).yy=round((yy-1)*(height2-1)/(height-1)+1-yy); end nIterationArray=round(linspace(nIterations,nIterations,nlevels)); for i=nlevels:-1:1 if isdisplay fprintf('Level: %d...',i); end [height,width,nchannels]=size(pyrd(i).im1); [height2,width2,nchannels]=size(pyrd(i).im2); [xx,yy]=meshgrid(1:width,1:height); if i==nlevels % vx=zeros(height,width); % vy=vx; vx=pyrd(i).xx; vy=pyrd(i).yy; winSizeX=ones(height,width)*topwsize; winSizeY=ones(height,width)*topwsize; else % vx=imresize(vx-pyrd(i+1).xx,[height,width],'bicubic')*2+pyrd(i).xx; % vy=imresize(vy-pyrd(i+1).yy,[height,width],'bicubic')*2+pyrd(i).yy; % winSizeX=decideWinSize(vx,wsize); % winSizeY=decideWinSize(vy,wsize); vx=round(pyrd(i).xx+imresize(vx-pyrd(i+1).xx,[height,width],'bicubic')*2); vy=round(pyrd(i).yy+imresize(vy-pyrd(i+1).yy,[height,width],'bicubic')*2); winSizeX=ones(height,width)*(wsize+i-1); winSizeY=ones(height,width)*(wsize+i-1); end if nchannels<=3 Im1=im2feature(pyrd(i).im1); Im2=im2feature(pyrd(i).im2); else Im1=pyrd(i).im1; Im2=pyrd(i).im2; end % compute the image-based coefficient if IsSegmentation imdiff=zeros(height,width,2); imdiff(:,1:end-1,1)=double(pyrd(i).seg(:,1:end-1)==pyrd(i).seg(:,2:end)); imdiff(1:end-1,:,2)=double(pyrd(i).seg(1:end-1,:)==pyrd(i).seg(2:end,:)); Im_s=imdiff*alpha+(1-imdiff)*alpha*0.01; Im_d=imdiff*alpha*100+(1-imdiff)*alpha*0.01*20; end if i==nlevels if IsSegmentation [flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nTopIterations,2,topwsize],vx,vy,winSizeX,winSizeY,Im_s,Im_d); else [flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nTopIterations,2,topwsize],vx,vy,winSizeX,winSizeY); %[flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nTopIterations,0,topwsize],vx,vy,winSizeX,winSizeY); end % [flow1,foo1]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nIterationArray(i),0,topwsize],vx,vy,winSizeX,winSizeY); % [flow2,foo2]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nTopIterations,2,topwsize],vx,vy,winSizeX,winSizeY); % if foo1(end)<foo2(end) % flow=flow1; % foo=foo1; % else % flow=flow2; % foo=foo2; % end else %[flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nIterations,nlevels-i,wsize],vx,vy,winSizeX,winSizeY); if IsSegmentation [flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nIterationArray(i),nlevels-i,wsize],vx,vy,winSizeX,winSizeY,Im_s,Im_d); else [flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nIterationArray(i),nlevels-i,wsize],vx,vy,winSizeX,winSizeY); %[flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nIterationArray(i),0,wsize],vx,vy,winSizeX,winSizeY); end % [flow,foo]=mexDiscreteFlow(Im1,Im2,[alpha,d,gamma*2^(i-1),nIterationArray(i),0,wsize],vx,vy,winSizeX,winSizeY); end energylist(i).data=foo; vx=flow(:,:,1); vy=flow(:,:,2); if isdisplay fprintf('done!\n'); end end function winSizeIm=decideWinSize(offset,wsize) % design the DOG filter f1=fspecial('gaussian',9,1); f2=fspecial('gaussian',9,.5); f=f2-f1; foo=imfilter(abs(imfilter(offset,f,'same','replicate')),fspecial('gaussian',9,1.5),'same','replicate'); Min=min(foo(:)); Max=max(foo(:)); winSizeIm=wsize*(foo-Min)/(Max-Min)+wsize;
github
mcubelab/rgrasp-master
warpImage.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/SIFTflow/warpImage.m
530
utf_8
6c87e60f54c4d09e7e47627e7e105b4b
% function to warp images with different dimensions function [warpI2,mask]=warpImage(im,vx,vy,type) [height2,width2,nchannels]=size(im); [height1,width1]=size(vx); [xx,yy]=meshgrid(1:width2,1:height2); [XX,YY]=meshgrid(1:width1,1:height1); XX=XX+vx; YY=YY+vy; mask=XX<1 | XX>width2 | YY<1 | YY>height2; XX=min(max(XX,1),width2); YY=min(max(YY,1),height2); if ~exist('type','var') type = 'bicubic'; end for i=1:nchannels foo=interp2(xx,yy,im(:,:,i),XX,YY,type); foo(mask)=0.6; warpI2(:,:,i)=foo; end mask=1-mask;
github
mcubelab/rgrasp-master
warpFLColor.m
.m
rgrasp-master/catkin_ws/src/passive_vision/src/stateIntegrator/SIFTflow/warpFLColor.m
514
utf_8
3806cd3429b55ca97a9faff4365e77a7
% Function to warp color image im2 to the grid of im1. It uses the pixels % in im1 to fill in the holes of warpI2 if there is any in the warping function warpI2=warpFLColor(im1,im2,vx,vy) if isfloat(im1)~=1 im1=im2double(im1); end if isfloat(im2)~=1 im2=im2double(im2); end if exist('vy')~=1 vy=vx(:,:,2); vx=vx(:,:,1); end nChannels=size(im1,3); for i=1:nChannels [im,isNan]=warpFL(im2(:,:,i),vx,vy); temp=im1(:,:,i); im(isNan)=temp(isNan); warpI2(:,:,i)=im; end
github
Eden-Kramer-Lab/ParametricContinuousPhaseEstimation-master
generate_data.m
.m
ParametricContinuousPhaseEstimation-master/ParametricContinuousPhase/generate_data.m
7,335
utf_8
cbf27e38ff020110e488175471a837ea
function data = generate_data(chanal_num , sample_rate , data_length , scale_noise , SNR ,W_cfg , k_config) %% chanal_num = number of chanal that we want to generate *** ex=32 %% sample rate = frequence of generating data *** ex=1000 %%%% data length = seconds of data that we want have synchrony in a %%%% specific band , current data is 3X more than data length and our %%%% synchrony varies by W_cfg and K_cfg **** ex = 16 %%%% scale_noise = use this option to change power of noise *** ex = .5 %%%% SNR = signal to noise ratio *** ex = 250 %%%% W_cfg is an array with 4 option that specifies centerfrequency and %%%% detunitng and a distribution for generating other chanal delta W %%%% W_cfg.W is a vector with size 1*3 specifies ceterfrequncy for each part %%%%of 3 part **** ex = [25 50 80] %%%% W_cfg.detuning is a vector with size 1*3 specifies detuning of these %%%% frequnecies **** ex = [3 5 1] %%%% W_cfg.mean we need a distribution to generate new dutuing for other %%%% chanal (exept 2 first chaal) , for this we use a guaussian %%%% distribution that this porperty specifies mean of it *** ex =0 %%%% W_cfg.sigma this property specifies sigma of gaussian distribtion for %%%% other chanals (except 2 first of them) ex = 1; %%%% K_cfg is an array with 3 option that specifies couupling rength %%%% length and a distributio for other chanlas (except first chanal) %%%% K_cfg.K is a vector with size 1*3 specifies coupling strngth for %%%% each part of 3 part **** ex = [3 .2 1] %%%% K_cfg.mean we need a distribution to generate new coupling strength %%%% for other chanal (exept first chaal), for this we use a guaussian %%%% distribution that this porperty specifies mean of it *** ex =0 %%%% K_cfg.sigma this property specifies sigma of gaussian distribtion for %%%% other chanals (excet first of them) ex = 1; number_of_chanals=chanal_num; % Randomize initial phases initial_phase = randn(number_of_chanals,1)*2; tim_sec=data_length; dt = 1/sample_rate; % step size (here 1ms) phases = zeros(number_of_chanals,(3*tim_sec)./dt); phases(1:number_of_chanals,1)= initial_phase(1:number_of_chanals,1); for ind=1:number_of_chanals noiseterm(ind,:)=powernoise(1,((3*tim_sec)./dt)+1,'normalize').*scale_noise; end %%%% making data for 3X more KK = []; WW = []; for iii=1:3 %%%%% gaussian distribuation delta_K = randn(number_of_chanals-1,1) * sqrt(k_config.sigma) + k_config.mean; delta_W = randn(number_of_chanals-1,1) * sqrt(W_cfg.sigma) + W_cfg.mean; KK(:,iii) = [k_config.K(iii); k_config.K(iii)+delta_K]; WW(:,iii) = [ W_cfg.W(iii) ;W_cfg.W(iii)-W_cfg.detuning(iii)-delta_W ]; end %%%%% smoothig changes over time gus_win = gausswin(5000); % <-- this value determines the width of the smoothing window gus_win = gus_win/sum(gus_win); [row_num, col_num] = size(KK); for ii=1:row_num temp_k = []; temp_w = []; for jj=1:col_num temp_k = [temp_k ones(1,data_length*sample_rate).*KK(ii,jj)]; temp_w = [temp_w ones(1,data_length*sample_rate).*WW(ii,jj)]; end K(ii,:) = conv(temp_k,gus_win,'same'); W(ii,:) = conv(temp_w,gus_win,'same'); end W=W.*(2*pi); %radians per sec K=K.*(2*pi); %scaling of coupling %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % for time=2:(3*tim_sec)/dt %%% SIMULATION of the phase-oscillators %%%%%%%%%% % for ind=1:number_of_chanals % phases(ind,time)= phases(ind,time-1) + (dt*(W(ind,time))+ sum(-dt.*K(:,time).* (sin((phases(ind,time-1) -phases(:,time-1)))) ) )+ noiseterm(ind,time-1) ; % end % end phases(:,1) = 0.1*randn(number_of_chanals,1); for time=2:(3*tim_sec)/dt %%% SIMULATION of the phase-oscillators %%%%%%%%%% ind = 1; phases(ind,time) = phases(ind,time-1) + dt *W(ind,time-1) + noiseterm(ind,time-1) ; for ind=2:number_of_chanals phases(ind,time)= phases(ind,time-1) + dt * W(ind,time-1) + dt * K(ind,time-1)* sin(phases(1,time-1)-phases(ind,time-1)) + noiseterm(ind,time-1) ; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ph= (mod(phases',2*pi))'; xx=(exp(1i*(ph(:,1:1:end)))'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% NOISE %%%%%%% noiseterm=randn(number_of_chanals,3*tim_sec*sample_rate);%.*((3*tim_sec*sample_rate)/(2*sqrt(3*tim_sec*sample_rate))); % white noise properly scaled %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% data = ((real(xx)'))+((noiseterm).* 1./sqrt(SNR)); %creating composite signal %%%% additional functions function x = powernoise(alpha, N, varargin) % Generate samples of power law noise. The power spectrum % of the signal scales as f^(-alpha). % Useage: % x = powernoise(alpha, N) % x = powernoise(alpha, N, 'option1', 'option2', ...) % Inputs: % alpha - power law scaling exponent % N - number of samples to generate % Output: % x - N x 1 vector of power law samples % With no option strings specified, the power spectrum is % deterministic, and the phases are uniformly distributed in the range % -pi to +pi. The power law extends all the way down to 0Hz (DC) % component. By specifying the 'randpower' option string however, the % power spectrum will be stochastic with Chi-square distribution. The % 'normalize' option string forces scaling of the output to the range % [-1, 1], consequently the power law will not necessarily extend % right down to 0Hz. % (cc) Max Little, 2008. This software is licensed under the % Attribution-Share Alike 2.5 Generic Creative Commons license: % http://creativecommons.org/licenses/by-sa/2.5/ % If you use this work, please cite: % Little MA et al. (2007), "Exploiting nonlinear recurrence and fractal % scaling properties for voice disorder detection", Biomed Eng Online, 6:23 % As of 20080323 markup % If you use this work, consider saying hi on comp.dsp % Dale B. Dalrymple opt_randpow = false; opt_normal = false; for j = 1:(nargin-2) switch varargin{j} case 'normalize', opt_normal = true; case 'randpower', opt_randpow = true; end end N2 = floor(N/2)-1; f = (2:(N2+1))'; A2 = 1./(f.^(alpha/2)); if (~opt_randpow) p2 = (rand(N2,1)-0.5)*2*pi; d2 = A2.*exp(i*p2); else % 20080323 p2 = randn(N2,1) + i * randn(N2,1); d2 = A2.*p2; end d = [1; d2; 1/((N2+2)^alpha); flipud(conj(d2))]; x = real(ifft(d)); if (opt_normal) x = ((x - min(x))/(max(x) - min(x)) - 0.5) * 2; end function r = circ_dist(x,y) % % r = circ_dist(alpha, beta) % Pairwise difference x_i-y_i around the circle computed efficiently. % Input: % alpha sample of linear random variable % beta sample of linear random variable or one single angle % Output: % r matrix with differences % References: % Biostatistical Analysis, J. H. Zar, p. 651 % PHB 3/19/2009 % Circular Statistics Toolbox for Matlab % By Philipp Berens, 2009 % [email protected] - www.kyb.mpg.de/~berens/circStat.html if size(x,1)~=size(y,1) && size(x,2)~=size(y,2) && length(y)~=1 error('Input dimensions do not match.') end r = angle(exp(1i*x)./exp(1i*y));
github
Eden-Kramer-Lab/ParametricContinuousPhaseEstimation-master
acf.m
.m
ParametricContinuousPhaseEstimation-master/ParametricContinuousPhase/acf.m
2,458
utf_8
236f4d8adcb8a89ee0851080b4ee4309
function ta = acf(y,p) % ACF - Compute Autocorrelations Through p Lags % >> myacf = acf(y,p) % % Inputs: % y - series to compute acf for, nx1 column vector % p - total number of lags, 1x1 integer % % Output: % myacf - px1 vector containing autocorrelations % (First lag computed is lag 1. Lag 0 not computed) % % % A bar graph of the autocorrelations is also produced, with % rejection region bands for testing individual autocorrelations = 0. % % Note that lag 0 autocorelation is not computed, % and is not shown on this graph. % % Example: % >> acf(randn(100,1), 10) % % -------------------------- % USER INPUT CHECKS % -------------------------- [n1, n2] = size(y) ; if n2 ~=1 error('Input series y must be an nx1 column vector') end [a1, a2] = size(p) ; if ~((a1==1 & a2==1) & (p<n1)) error('Input number of lags p must be a 1x1 scalar, and must be less than length of series y') end % ------------- % BEGIN CODE % ------------- ta = zeros(p,1) ; global N N = max(size(y)) ; global ybar ybar = mean(y); % Collect ACFs at each lag i for i = 1:p ta(i) = acf_k(y,i) ; end % Plot ACF % Plot rejection region lines for test of individual autocorrelations % H_0: rho(tau) = 0 at alpha=.05 bar(ta) line([0 p+.5], (1.96)*(1/sqrt(N))*ones(1,2)) line([0 p+.5], (-1.96)*(1/sqrt(N))*ones(1,2)) % Some figure properties line_hi = (1.96)*(1/sqrt(N))+.05; line_lo = -(1.96)*(1/sqrt(N))-.05; bar_hi = max(ta)+.05 ; bar_lo = -max(ta)-.05 ; if (abs(line_hi) > abs(bar_hi)) % if rejection lines might not appear on graph axis([0 p+.60 line_lo line_hi]) else axis([0 p+.60 bar_lo bar_hi]) end title({' ','Sample Autocorrelations',' '}) xlabel('Lag Length') set(gca,'YTick',[-1:.20:1]) % set number of lag labels shown if (p<28 & p>4) set(gca,'XTick',floor(linspace(1,p,4))) elseif (p>=28) set(gca,'XTick',floor(linspace(1,p,8))) end set(gca,'TickLength',[0 0]) % --------------- % SUB FUNCTION % --------------- function ta2 = acf_k(y,k) % ACF_K - Autocorrelation at Lag k % acf(y,k) % % Inputs: % y - series to compute acf for % k - which lag to compute acf % global ybar global N cross_sum = zeros(N-k,1) ; % Numerator, unscaled covariance for i = (k+1):N cross_sum(i) = (y(i)-ybar)*(y(i-k)-ybar) ; end % Denominator, unscaled variance yvar = (y-ybar)'*(y-ybar) ; ta2 = sum(cross_sum) / yvar ;
github
Eden-Kramer-Lab/ParametricContinuousPhaseEstimation-master
fminsearchbnd.m
.m
ParametricContinuousPhaseEstimation-master/ParametricContinuousPhase/fminsearchbnd.m
8,139
utf_8
1316d7f9d69771e92ecc70425e0f9853
function [x,fval,exitflag,output] = fminsearchbnd(fun,x0,LB,UB,options,varargin) % FMINSEARCHBND: FMINSEARCH, but with bound constraints by transformation % usage: x=FMINSEARCHBND(fun,x0) % usage: x=FMINSEARCHBND(fun,x0,LB) % usage: x=FMINSEARCHBND(fun,x0,LB,UB) % usage: x=FMINSEARCHBND(fun,x0,LB,UB,options) % usage: x=FMINSEARCHBND(fun,x0,LB,UB,options,p1,p2,...) % usage: [x,fval,exitflag,output]=FMINSEARCHBND(fun,x0,...) % % arguments: % fun, x0, options - see the help for FMINSEARCH % % LB - lower bound vector or array, must be the same size as x0 % % If no lower bounds exist for one of the variables, then % supply -inf for that variable. % % If no lower bounds at all, then LB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % UB - upper bound vector or array, must be the same size as x0 % % If no upper bounds exist for one of the variables, then % supply +inf for that variable. % % If no upper bounds at all, then UB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % Notes: % % If options is supplied, then TolX will apply to the transformed % variables. All other FMINSEARCH parameters should be unaffected. % % Variables which are constrained by both a lower and an upper % bound will use a sin transformation. Those constrained by % only a lower or an upper bound will use a quadratic % transformation, and unconstrained variables will be left alone. % % Variables may be fixed by setting their respective bounds equal. % In this case, the problem will be reduced in size for FMINSEARCH. % % The bounds are inclusive inequalities, which admit the % boundary values themselves, but will not permit ANY function % evaluations outside the bounds. These constraints are strictly % followed. % % If your problem has an EXCLUSIVE (strict) constraint which will % not admit evaluation at the bound itself, then you must provide % a slightly offset bound. An example of this is a function which % contains the log of one of its parameters. If you constrain the % variable to have a lower bound of zero, then FMINSEARCHBND may % try to evaluate the function exactly at zero. % % % Example usage: % rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2; % % fminsearch(rosen,[3 3]) % unconstrained % ans = % 1.0000 1.0000 % % fminsearchbnd(rosen,[3 3],[2 2],[]) % constrained % ans = % 2.0000 4.0000 % % See test_main.m for other examples of use. % % % See also: fminsearch, fminspleas % % % Author: John D'Errico % E-mail: [email protected] % Release: 4 % Release date: 7/23/06 % size checks xsize = size(x0); x0 = x0(:); n=length(x0); if (nargin<3) || isempty(LB) LB = repmat(-inf,n,1); else LB = LB(:); end if (nargin<4) || isempty(UB) UB = repmat(inf,n,1); else UB = UB(:); end if (n~=length(LB)) || (n~=length(UB)) error 'x0 is incompatible in size with either LB or UB.' end % set default options if necessary if (nargin<5) || isempty(options) options = optimset('fminsearch'); end % stuff into a struct to pass around params.args = varargin; params.LB = LB; params.UB = UB; params.fun = fun; params.n = n; % note that the number of parameters may actually vary if % a user has chosen to fix one or more parameters params.xsize = xsize; params.OutputFcn = []; % 0 --> unconstrained variable % 1 --> lower bound only % 2 --> upper bound only % 3 --> dual finite bounds % 4 --> fixed variable params.BoundClass = zeros(n,1); for i=1:n k = isfinite(LB(i)) + 2*isfinite(UB(i)); params.BoundClass(i) = k; if (k==3) && (LB(i)==UB(i)) params.BoundClass(i) = 4; end end % transform starting values into their unconstrained % surrogates. Check for infeasible starting guesses. x0u = x0; k=1; for i = 1:n switch params.BoundClass(i) case 1 % lower bound only if x0(i)<=LB(i) % infeasible starting value. Use bound. x0u(k) = 0; else x0u(k) = sqrt(x0(i) - LB(i)); end % increment k k=k+1; case 2 % upper bound only if x0(i)>=UB(i) % infeasible starting value. use bound. x0u(k) = 0; else x0u(k) = sqrt(UB(i) - x0(i)); end % increment k k=k+1; case 3 % lower and upper bounds if x0(i)<=LB(i) % infeasible starting value x0u(k) = -pi/2; elseif x0(i)>=UB(i) % infeasible starting value x0u(k) = pi/2; else x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1; % shift by 2*pi to avoid problems at zero in fminsearch % otherwise, the initial simplex is vanishingly small x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k)))); end % increment k k=k+1; case 0 % unconstrained variable. x0u(i) is set. x0u(k) = x0(i); % increment k k=k+1; case 4 % fixed variable. drop it before fminsearch sees it. % k is not incremented for this variable. end end % if any of the unknowns were fixed, then we need to shorten % x0u now. if k<=n x0u(k:n) = []; end % were all the variables fixed? if isempty(x0u) % All variables were fixed. quit immediately, setting the % appropriate parameters, then return. % undo the variable transformations into the original space x = xtransform(x0u,params); % final reshape x = reshape(x,xsize); % stuff fval with the final value fval = feval(params.fun,x,params.args{:}); % fminsearchbnd was not called exitflag = 0; output.iterations = 0; output.funcCount = 1; output.algorithm = 'fminsearch'; output.message = 'All variables were held fixed by the applied bounds'; % return with no call at all to fminsearch return end % Check for an outputfcn. If there is any, then substitute my % own wrapper function. if ~isempty(options.OutputFcn) params.OutputFcn = options.OutputFcn; options.OutputFcn = @outfun_wrapper; end % now we can call fminsearch, but with our own % intra-objective function. [xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params); % undo the variable transformations into the original space x = xtransform(xu,params); % final reshape to make sure the result has the proper shape x = reshape(x,xsize); % Use a nested function as the OutputFcn wrapper function stop = outfun_wrapper(x,varargin); % we need to transform x first xtrans = xtransform(x,params); % then call the user supplied OutputFcn stop = params.OutputFcn(xtrans,varargin{1:(end-1)}); end end % mainline end % ====================================== % ========= begin subfunctions ========= % ====================================== function fval = intrafun(x,params) % transform variables, then call original function % transform xtrans = xtransform(x,params); % and call fun fval = feval(params.fun,reshape(xtrans,params.xsize),params.args{:}); end % sub function intrafun end % ====================================== function xtrans = xtransform(x,params) % converts unconstrained variables into their original domains xtrans = zeros(params.xsize); % k allows some variables to be fixed, thus dropped from the % optimization. k=1; for i = 1:params.n switch params.BoundClass(i) case 1 % lower bound only xtrans(i) = params.LB(i) + x(k).^2; k=k+1; case 2 % upper bound only xtrans(i) = params.UB(i) - x(k).^2; k=k+1; case 3 % lower and upper bounds xtrans(i) = (sin(x(k))+1)/2; xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i); % just in case of any floating point problems xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i))); k=k+1; case 4 % fixed variable, bounds are equal, set it at either bound xtrans(i) = params.LB(i); case 0 % unconstrained variable. xtrans(i) = x(k); k=k+1; end end end % sub function xtransform end
github
Eden-Kramer-Lab/ParametricContinuousPhaseEstimation-master
fminsearchcon.m
.m
ParametricContinuousPhaseEstimation-master/ParametricContinuousPhase/fminsearchcon.m
11,330
utf_8
c52011ee59580c69f3872d1b59630088
function [x,fval,exitflag,output]=fminsearchcon(fun,x0,LB,UB,A,b,nonlcon,options,varargin) % FMINSEARCHCON: Extension of FMINSEARCHBND with general inequality constraints % usage: x=FMINSEARCHCON(fun,x0) % usage: x=FMINSEARCHCON(fun,x0,LB) % usage: x=FMINSEARCHCON(fun,x0,LB,UB) % usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b) % usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b,nonlcon) % usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b,nonlcon,options) % usage: x=FMINSEARCHCON(fun,x0,LB,UB,A,b,nonlcon,options,p1,p2,...) % usage: [x,fval,exitflag,output]=FMINSEARCHCON(fun,x0,...) % % arguments: % fun, x0, options - see the help for FMINSEARCH % % x0 MUST be a feasible point for the linear and nonlinear % inequality constraints. If it is not inside the bounds % then it will be moved to the nearest bound. If x0 is % infeasible for the general constraints, then an error will % be returned. % % LB - lower bound vector or array, must be the same size as x0 % % If no lower bounds exist for one of the variables, then % supply -inf for that variable. % % If no lower bounds at all, then LB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % UB - upper bound vector or array, must be the same size as x0 % % If no upper bounds exist for one of the variables, then % supply +inf for that variable. % % If no upper bounds at all, then UB may be left empty. % % Variables may be fixed in value by setting the corresponding % lower and upper bounds to exactly the same value. % % A,b - (OPTIONAL) Linear inequality constraint array and right % hand side vector. (Note: these constraints were chosen to % be consistent with those of fmincon.) % % A*x <= b % % nonlcon - (OPTIONAL) general nonlinear inequality constraints % NONLCON must return a set of general inequality constraints. % These will be enforced such that nonlcon is always <= 0. % % nonlcon(x) <= 0 % % % Notes: % % If options is supplied, then TolX will apply to the transformed % variables. All other FMINSEARCH parameters should be unaffected. % % Variables which are constrained by both a lower and an upper % bound will use a sin transformation. Those constrained by % only a lower or an upper bound will use a quadratic % transformation, and unconstrained variables will be left alone. % % Variables may be fixed by setting their respective bounds equal. % In this case, the problem will be reduced in size for FMINSEARCH. % % The bounds are inclusive inequalities, which admit the % boundary values themselves, but will not permit ANY function % evaluations outside the bounds. These constraints are strictly % followed. % % If your problem has an EXCLUSIVE (strict) constraint which will % not admit evaluation at the bound itself, then you must provide % a slightly offset bound. An example of this is a function which % contains the log of one of its parameters. If you constrain the % variable to have a lower bound of zero, then FMINSEARCHCON may % try to evaluate the function exactly at zero. % % Inequality constraints are enforced with an implicit penalty % function approach. But the constraints are tested before % any function evaluations are ever done, so the actual objective % function is NEVER evaluated outside of the feasible region. % % % Example usage: % rosen = @(x) (1-x(1)).^2 + 105*(x(2)-x(1).^2).^2; % % Fully unconstrained problem % fminsearchcon(rosen,[3 3]) % ans = % 1.0000 1.0000 % % lower bound constrained % fminsearchcon(rosen,[3 3],[2 2],[]) % ans = % 2.0000 4.0000 % % x(2) fixed at 3 % fminsearchcon(rosen,[3 3],[-inf 3],[inf,3]) % ans = % 1.7314 3.0000 % % simple linear inequality: x(1) + x(2) <= 1 % fminsearchcon(rosen,[0 0],[],[],[1 1],.5) % % ans = % 0.6187 0.3813 % % general nonlinear inequality: sqrt(x(1)^2 + x(2)^2) <= 1 % fminsearchcon(rosen,[0 0],[],[],[],[],@(x) norm(x)-1) % ans = % 0.78633 0.61778 % % Of course, any combination of the above constraints is % also possible. % % See test_main.m for other examples of use. % % % See also: fminsearch, fminspleas, fminsearchbnd % % % Author: John D'Errico % E-mail: [email protected] % Release: 1.0 % Release date: 12/16/06 % size checks xsize = size(x0); x0 = x0(:); n=length(x0); if (nargin<3) || isempty(LB) LB = repmat(-inf,n,1); else LB = LB(:); end if (nargin<4) || isempty(UB) UB = repmat(inf,n,1); else UB = UB(:); end if (n~=length(LB)) || (n~=length(UB)) error 'x0 is incompatible in size with either LB or UB.' end % defaults for A,b if (nargin<5) || isempty(A) A = []; end if (nargin<6) || isempty(b) b = []; end nA = []; nb = []; if (isempty(A)&&~isempty(b)) || (isempty(b)&&~isempty(A)) error 'Sizes of A and b are incompatible' elseif ~isempty(A) nA = size(A); b = b(:); nb = size(b,1); if nA(1)~=nb error 'Sizes of A and b are incompatible' end if nA(2)~=n error 'A is incompatible in size with x0' end end % defaults for nonlcon if (nargin<7) || isempty(nonlcon) nonlcon = []; end % test for feasibility of the initial value % against any general inequality constraints if ~isempty(A) if any(A*x0>b) error 'Infeasible starting values (linear inequalities failed).' end end if ~isempty(nonlcon) if any(feval(nonlcon,(reshape(x0,xsize)),varargin{:})>0) error 'Infeasible starting values (nonlinear inequalities failed).' end end % set default options if necessary if (nargin<8) || isempty(options) options = optimset('fminsearch'); end % stuff into a struct to pass around params.args = varargin; params.LB = LB; params.UB = UB; params.fun = fun; params.n = n; params.xsize = xsize; params.OutputFcn = []; params.A = A; params.b = b; params.nonlcon = nonlcon; % 0 --> unconstrained variable % 1 --> lower bound only % 2 --> upper bound only % 3 --> dual finite bounds % 4 --> fixed variable params.BoundClass = zeros(n,1); for i=1:n k = isfinite(LB(i)) + 2*isfinite(UB(i)); params.BoundClass(i) = k; if (k==3) && (LB(i)==UB(i)) params.BoundClass(i) = 4; end end % transform starting values into their unconstrained % surrogates. Check for infeasible starting guesses. x0u = x0; k=1; for i = 1:n switch params.BoundClass(i) case 1 % lower bound only if x0(i)<=LB(i) % infeasible starting value. Use bound. x0u(k) = 0; else x0u(k) = sqrt(x0(i) - LB(i)); end % increment k k=k+1; case 2 % upper bound only if x0(i)>=UB(i) % infeasible starting value. use bound. x0u(k) = 0; else x0u(k) = sqrt(UB(i) - x0(i)); end % increment k k=k+1; case 3 % lower and upper bounds if x0(i)<=LB(i) % infeasible starting value x0u(k) = -pi/2; elseif x0(i)>=UB(i) % infeasible starting value x0u(k) = pi/2; else x0u(k) = 2*(x0(i) - LB(i))/(UB(i)-LB(i)) - 1; % shift by 2*pi to avoid problems at zero in fminsearch % otherwise, the initial simplex is vanishingly small x0u(k) = 2*pi+asin(max(-1,min(1,x0u(k)))); end % increment k k=k+1; case 0 % unconstrained variable. x0u(i) is set. x0u(k) = x0(i); % increment k k=k+1; case 4 % fixed variable. drop it before fminsearch sees it. % k is not incremented for this variable. end end % if any of the unknowns were fixed, then we need to shorten % x0u now. if k<=n x0u(k:n) = []; end % were all the variables fixed? if isempty(x0u) % All variables were fixed. quit immediately, setting the % appropriate parameters, then return. % undo the variable transformations into the original space x = xtransform(x0u,params); % final reshape x = reshape(x,xsize); % stuff fval with the final value fval = feval(params.fun,x,params.args{:}); % fminsearchbnd was not called exitflag = 0; output.iterations = 0; output.funcCount = 1; output.algorithm = 'fminsearch'; output.message = 'All variables were held fixed by the applied bounds'; % return with no call at all to fminsearch return end % Check for an outputfcn. If there is any, then substitute my % own wrapper function. if ~isempty(options.OutputFcn) params.OutputFcn = options.OutputFcn; options.OutputFcn = @outfun_wrapper; end % now we can call fminsearch, but with our own % intra-objective function. [xu,fval,exitflag,output] = fminsearch(@intrafun,x0u,options,params); % undo the variable transformations into the original space x = xtransform(xu,params); % final reshape x = reshape(x,xsize); % Use a nested function as the OutputFcn wrapper function stop = outfun_wrapper(x,varargin); % we need to transform x first xtrans = xtransform(x,params); % then call the user supplied OutputFcn stop = params.OutputFcn(xtrans,varargin{1:(end-1)}); end end % mainline end % ====================================== % ========= begin subfunctions ========= % ====================================== function fval = intrafun(x,params) % transform variables, test constraints, then call original function % transform xtrans = xtransform(x,params); % test constraints before the function call % First, do the linear inequality constraints, if any if ~isempty(params.A) % Required: A*xtrans <= b if any(params.A*xtrans(:) > params.b) % linear inequality constraints failed. Just return inf. fval = inf; return end end % resize xtrans to be the correct size for the nonlcon % and objective function calls xtrans = reshape(xtrans,params.xsize); % Next, do the nonlinear inequality constraints if ~isempty(params.nonlcon) % Required: nonlcon(xtrans) <= 0 cons = feval(params.nonlcon,xtrans,params.args{:}); if any(cons(:) > 0) % nonlinear inequality constraints failed. Just return inf. fval = inf; return end end % we survived the general inequality constraints. Only now % do we evaluate the objective function. % append any additional parameters to the argument list fval = feval(params.fun,xtrans,params.args{:}); end % sub function intrafun end % ====================================== function xtrans = xtransform(x,params) % converts unconstrained variables into their original domains xtrans = zeros(1,params.n); % k allows some variables to be fixed, thus dropped from the % optimization. k=1; for i = 1:params.n switch params.BoundClass(i) case 1 % lower bound only xtrans(i) = params.LB(i) + x(k).^2; k=k+1; case 2 % upper bound only xtrans(i) = params.UB(i) - x(k).^2; k=k+1; case 3 % lower and upper bounds xtrans(i) = (sin(x(k))+1)/2; xtrans(i) = xtrans(i)*(params.UB(i) - params.LB(i)) + params.LB(i); % just in case of any floating point problems xtrans(i) = max(params.LB(i),min(params.UB(i),xtrans(i))); k=k+1; case 4 % fixed variable, bounds are equal, set it at either bound xtrans(i) = params.LB(i); case 0 % unconstrained variable. xtrans(i) = x(k); k=k+1; end end end % sub function xtransform end
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
submit.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex2/ex2/submit.m
1,605
utf_8
9b63d386e9bd7bcca66b1a3d2fa37579
function submit() addpath('./lib'); conf.assignmentSlug = 'logistic-regression'; conf.itemName = 'Logistic Regression'; conf.partArrays = { ... { ... '1', ... { 'sigmoid.m' }, ... 'Sigmoid Function', ... }, ... { ... '2', ... { 'costFunction.m' }, ... 'Logistic Regression Cost', ... }, ... { ... '3', ... { 'costFunction.m' }, ... 'Logistic Regression Gradient', ... }, ... { ... '4', ... { 'predict.m' }, ... 'Predict', ... }, ... { ... '5', ... { 'costFunctionReg.m' }, ... 'Regularized Logistic Regression Cost', ... }, ... { ... '6', ... { 'costFunctionReg.m' }, ... 'Regularized Logistic Regression Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))']; y = sin(X(:,1) + X(:,2)) > 0; if partId == '1' out = sprintf('%0.5f ', sigmoid(X)); elseif partId == '2' out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y)); elseif partId == '3' [cost, grad] = costFunction([0.25 0.5 -0.5]', X, y); out = sprintf('%0.5f ', grad); elseif partId == '4' out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X)); elseif partId == '5' out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1)); elseif partId == '6' [cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1); out = sprintf('%0.5f ', grad); end end
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
submitWithConfiguration.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex2/ex2/lib/submitWithConfiguration.m
3,734
utf_8
84d9a81848f6d00a7aff4f79bdbb6049
function submitWithConfiguration(conf) addpath('./lib/jsonlab'); parts = parts(conf); fprintf('== Submitting solutions | %s...\n', conf.itemName); tokenFile = 'token.mat'; if exist(tokenFile, 'file') load(tokenFile); [email token] = promptToken(email, token, tokenFile); else [email token] = promptToken('', '', tokenFile); end if isempty(token) fprintf('!! Submission Cancelled\n'); return end try response = submitParts(conf, email, token, parts); catch e = lasterror(); fprintf( ... '!! Submission failed: unexpected error: %s\n', ... e.message); fprintf('!! Please try again later.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); else showFeedback(parts, response); save(tokenFile, 'email', 'token'); end end function [email token] = promptToken(email, existingToken, tokenFile) if (~isempty(email) && ~isempty(existingToken)) prompt = sprintf( ... 'Use token from last successful submission (%s)? (Y/n): ', ... email); reenter = input(prompt, 's'); if (isempty(reenter) || reenter(1) == 'Y' || reenter(1) == 'y') token = existingToken; return; else delete(tokenFile); end end email = input('Login (email address): ', 's'); token = input('Token: ', 's'); end function isValid = isValidPartOptionIndex(partOptions, i) isValid = (~isempty(i)) && (1 <= i) && (i <= numel(partOptions)); end function response = submitParts(conf, email, token, parts) body = makePostBody(conf, email, token, parts); submissionUrl = submissionUrl(); params = {'jsonBody', body}; responseBody = urlread(submissionUrl, 'post', params); response = loadjson(responseBody); end function body = makePostBody(conf, email, token, parts) bodyStruct.assignmentSlug = conf.assignmentSlug; bodyStruct.submitterEmail = email; bodyStruct.secret = token; bodyStruct.parts = makePartsStruct(conf, parts); opt.Compact = 1; body = savejson('', bodyStruct, opt); end function partsStruct = makePartsStruct(conf, parts) for part = parts partId = part{:}.id; fieldName = makeValidFieldName(partId); outputStruct.output = conf.output(partId); partsStruct.(fieldName) = outputStruct; end end function [parts] = parts(conf) parts = {}; for partArray = conf.partArrays part.id = partArray{:}{1}; part.sourceFiles = partArray{:}{2}; part.name = partArray{:}{3}; parts{end + 1} = part; end end function showFeedback(parts, response) fprintf('== \n'); fprintf('== %43s | %9s | %-s\n', 'Part Name', 'Score', 'Feedback'); fprintf('== %43s | %9s | %-s\n', '---------', '-----', '--------'); for part = parts score = ''; partFeedback = ''; partFeedback = response.partFeedbacks.(makeValidFieldName(part{:}.id)); partEvaluation = response.partEvaluations.(makeValidFieldName(part{:}.id)); score = sprintf('%d / %3d', partEvaluation.score, partEvaluation.maxScore); fprintf('== %43s | %9s | %-s\n', part{:}.name, score, partFeedback); end evaluation = response.evaluation; totalScore = sprintf('%d / %d', evaluation.score, evaluation.maxScore); fprintf('== --------------------------------\n'); fprintf('== %43s | %9s | %-s\n', '', totalScore, ''); fprintf('== \n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
savejson.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex2/ex2/lib/jsonlab/savejson.m
17,462
utf_8
861b534fc35ffe982b53ca3ca83143bf
function json=savejson(rootname,obj,varargin) % % json=savejson(rootname,obj,filename) % or % json=savejson(rootname,obj,opt) % json=savejson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a JSON (JavaScript % Object Notation) string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09 % % $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array). % filename: a string for the file name to save the output JSON data. % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.FloatFormat ['%.10g'|string]: format to show each numeric element % of a 1D/2D array; % opt.ArrayIndent [1|0]: if 1, output explicit data array with % precedent indentation; if 0, no indentation % opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [0|1]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern % to represent +/-Inf. The matched pattern is '([-+]*)Inf' % and $1 represents the sign. For those who want to use % 1e999 to represent Inf, they can set opt.Inf to '$11e999' % opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern % to represent NaN % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSONP='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. % opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a string in the JSON format (see http://json.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % savejson('jmesh',jsonmesh) % savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); if(jsonopt('Compact',0,opt)==1) whitespaces=struct('tab','','newline','','sep',','); end if(~isfield(opt,'whitespaces_')) opt.whitespaces_=whitespaces; end nl=whitespaces.newline; json=obj2json(rootname,obj,rootlevel,opt); if(rootisarray) json=sprintf('%s%s',json,nl); else json=sprintf('{%s%s%s}\n',nl,json,nl); end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=sprintf('%s(%s);%s',jsonp,json,nl); end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) if(jsonopt('SaveBinary',0,opt)==1) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); else fid = fopen(opt.FileName, 'wt'); fwrite(fid,json,'char'); end fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2json(name,item,level,varargin) if(iscell(item)) txt=cell2json(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2json(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2json(name,item,level,varargin{:}); else txt=mat2json(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2json(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); nl=ws.newline; if(len>1) if(~isempty(name)) txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; else txt=sprintf('%s[%s',padding0,nl); end elseif(len==0) if(~isempty(name)) txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; else txt=sprintf('%s[]',padding0); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end %if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=struct2json(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding0=repmat(ws.tab,1,level); padding2=repmat(ws.tab,1,level+1); padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); nl=ws.newline; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding0,nl); end end for j=1:dim(2) if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); else txt=sprintf('%s%s{%s',txt,padding1,nl); end if(~isempty(names)) for e=1:length(names) txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); if(e<length(names)) txt=sprintf('%s%s',txt,','); end txt=sprintf('%s%s',txt,nl); end end txt=sprintf('%s%s}',txt,padding1); if(i<dim(1)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(dim(1)>1) txt=sprintf('%s%s%s]',txt,nl,padding2); end if(j<dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end end if(len>1) txt=sprintf('%s%s%s]',txt,nl,padding0); end %%------------------------------------------------------------------------- function txt=str2json(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(~isempty(name)) if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end else if(len>1) txt=sprintf('%s[%s',padding1,nl); end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len if(isoct) val=regexprep(item(e,:),'\\','\\'); val=regexprep(val,'"','\"'); val=regexprep(val,'^"','\"'); else val=regexprep(item(e,:),'\\','\\\\'); val=regexprep(val,'"','\\"'); val=regexprep(val,'^"','\\"'); end val=escapejsonstring(val); if(len==1) obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; if(isempty(name)) obj=['"',val,'"']; end txt=sprintf('%s%s%s%s',txt,padding1,obj); else txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); end if(e==len) sep=''; end txt=sprintf('%s%s',txt,sep); end if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end %%------------------------------------------------------------------------- function txt=mat2json(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); padding1=repmat(ws.tab,1,level); padding0=repmat(ws.tab,1,level+1); nl=ws.newline; sep=ws.sep; if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) if(isempty(name)) txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); else txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); end else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); else numtxt=matdata2json(item,level+1,varargin{:}); end if(isempty(name)) txt=sprintf('%s%s',padding1,numtxt); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); else txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); end end return; end dataformat='%s%s%s%s%s'; if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); end txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); if(size(item,1)==1) % Row vector, store only column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([iy(:),data'],level+2,varargin{:}), nl); elseif(size(item,2)==1) % Column vector, store only row indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,data],level+2,varargin{:}), nl); else % General case, store row and column indices. txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([ix,iy,data],level+2,varargin{:}), nl); end else if(isreal(item)) txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json(item(:)',level+2,varargin{:}), nl); else txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); end end txt=sprintf('%s%s%s',txt,padding1,'}'); %%------------------------------------------------------------------------- function txt=matdata2json(mat,level,varargin) ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); ws=jsonopt('whitespaces_',ws,varargin{:}); tab=ws.tab; nl=ws.newline; if(size(mat,1)==1) pre=''; post=''; level=level-1; else pre=sprintf('[%s',nl); post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); end if(isempty(mat)) txt='null'; return; end floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); %if(numel(mat)>1) formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; %else % formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; %end if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) formatstr=[repmat(tab,1,level) formatstr]; end txt=sprintf(formatstr,mat'); txt(end-length(nl):end)=[]; if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) txt=regexprep(txt,'1','true'); txt=regexprep(txt,'0','false'); end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],\n[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end txt=[pre txt post]; if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function newstr=escapejsonstring(str) newstr=str; isoct=exist('OCTAVE_VERSION','builtin'); if(isoct) vv=sscanf(OCTAVE_VERSION,'%f'); if(vv(1)>=3.8) isoct=0; end end if(isoct) escapechars={'\a','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},escapechars{i}); end else escapechars={'\a','\b','\f','\n','\r','\t','\v'}; for i=1:length(escapechars); newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); end end
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
loadjson.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex2/ex2/lib/jsonlab/loadjson.m
18,732
ibm852
ab98cf173af2d50bbe8da4d6db252a20
function data = loadjson(fname,varargin) % % data=loadjson(fname,opt) % or % data=loadjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2011/09/09, including previous works from % % Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 % created on 2009/11/02 % François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 % created on 2009/03/22 % Joel Feenstra: % http://www.mathworks.com/matlabcentral/fileexchange/20565 % created on 2008/07/03 % % $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a JSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.FastArrayParser [1|0 or integer]: if set to 1, use a % speed-optimized array parser when loading an % array object. The fast array parser may % collapse block arrays into a single large % array similar to rules defined in cell2mat; 0 to % use a legacy parser; if set to a larger-than-1 % value, this option will specify the minimum % dimension to enable the fast array parser. For % example, if the input is a 3D array, setting % FastArrayParser to 1 will return a 3D array; % setting to 2 will return a cell array of 2D % arrays; setting to 3 will return to a 2D cell % array of 1D vectors; setting to 4 will return a % 3D cell array. % opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') % dat=loadjson(['examples' filesep 'example1.json']) % dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); if(jsonopt('ShowProgress',0,opt)==1) opt.progressbar_=waitbar(0,'loading ...'); end jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end if(isfield(opt,'progressbar_')) close(opt.progressbar_); end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=data(j).x0x5F_ArraySize_; if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; if next_char ~= '}' while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end parse_char(':'); val = parse_value(varargin{:}); eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' break; end parse_char(','); end end parse_char('}'); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim2=[]; arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); pbar=jsonopt('progressbar_',-1,varargin{:}); if next_char ~= ']' if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); arraystr=['[' inStr(pos:endpos)]; arraystr=regexprep(arraystr,'"_NaN_"','NaN'); arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); arraystr(arraystr==sprintf('\n'))=[]; arraystr(arraystr==sprintf('\r'))=[]; %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D astr=inStr((e1l+1):(e1r-1)); astr=regexprep(astr,'"_NaN_"','NaN'); astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); astr(astr==sprintf('\n'))=[]; astr(astr==sprintf('\r'))=[]; astr(astr==' ')=''; if(isempty(find(astr=='[', 1))) % array is 2D dim2=length(sscanf(astr,'%f,',[1 inf])); end else % array is 1D astr=arraystr(2:end-1); astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); if(nextidx>=length(astr)-1) object=obj; pos=endpos; parse_char(']'); return; end end if(~isempty(dim2)) astr=arraystr; astr(astr=='[')=''; astr(astr==']')=''; astr(astr==' ')=''; [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); if(nextidx>=length(astr)-1) object=reshape(obj,dim2,numel(obj)/dim2)'; pos=endpos; parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end return; end end arraystr=regexprep(arraystr,'\]\s*,','];'); else arraystr='['; end try if(isoct && regexp(arraystr,'"','once')) error('Octave eval can produce empty cells for JSON-like input'); end object=eval(arraystr); pos=endpos; catch while 1 newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); val = parse_value(newopt); object{end+1} = val; if next_char == ']' break; end parse_char(','); end end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end parse_char(']'); if(pbar>0) waitbar(pos/length(inStr),pbar,'loading ...'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr len esc index_esc len_esc % len, ns = length(inStr), keyboard if inStr(pos) ~= '"' error_pos('String starting with " expected at position %d'); else pos = pos + 1; end str = ''; while pos <= len while index_esc <= len_esc && esc(index_esc) < pos index_esc = index_esc + 1; end if index_esc > len_esc str = [str inStr(pos:len)]; pos = len + 1; break; else str = [str inStr(pos:esc(index_esc)-1)]; pos = esc(index_esc); end nstr = length(str); switch inStr(pos) case '"' pos = pos + 1; if(~isempty(str)) if(strcmp(str,'_Inf_')) str=Inf; elseif(strcmp(str,'-_Inf_')) str=-Inf; elseif(strcmp(str,'_NaN_')) str=NaN; end end return; case '\' if pos+1 > len error_pos('End of file reached right after escape character'); end pos = pos + 1; switch inStr(pos) case {'"' '\' '/'} str(nstr+1) = inStr(pos); pos = pos + 1; case {'b' 'f' 'n' 'r' 't'} str(nstr+1) = sprintf(['\' inStr(pos)]); pos = pos + 1; case 'u' if pos+4 > len error_pos('End of file reached in escaped unicode character'); end str(nstr+(1:6)) = inStr(pos-1:pos+4); pos = pos + 5; end otherwise % should never happen str(nstr+1) = inStr(pos), keyboard pos = pos + 1; end end error_pos('End of file while expecting end of inStr'); %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct currstr=inStr(pos:end); numstr=0; if(isoct~=0) numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); [num, one] = sscanf(currstr, '%f', 1); delta=numstr+1; else [num, one, err, delta] = sscanf(currstr, '%f', 1); if ~isempty(err) error_pos('Error reading number at position %d'); end end pos = pos + delta-1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; pbar=jsonopt('progressbar_',-1,varargin{:}); if(pbar>0) waitbar(pos/len,pbar,'loading ...'); end switch(inStr(pos)) case '"' val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'-','0','1','2','3','4','5','6','7','8','9'} val = parse_number(varargin{:}); return; case 't' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') val = true; pos = pos + 4; return; end case 'f' if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') val = false; pos = pos + 5; return; end case 'n' if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') val = []; pos = pos + 4; return; end end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
loadubjson.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex2/ex2/lib/jsonlab/loadubjson.m
15,574
utf_8
5974e78e71b81b1e0f76123784b951a4
function data = loadubjson(fname,varargin) % % data=loadubjson(fname,opt) % or % data=loadubjson(fname,'param1',value1,'param2',value2,...) % % parse a JSON (JavaScript Object Notation) file or string % % authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/01 % % $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % fname: input file name, if fname contains "{}" or "[]", fname % will be interpreted as a UBJSON string % opt: a struct to store parsing options, opt can be replaced by % a list of ('param',value) pairs - the param string is equivallent % to a field in opt. opt can have the following % fields (first in [.|.] is the default) % % opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat % for each element of the JSON data, and group % arrays based on the cell2mat rules. % opt.IntEndian [B|L]: specify the endianness of the integer fields % in the UBJSON input data. B - Big-Endian format for % integers (as required in the UBJSON specification); % L - input integer fields are in Little-Endian order. % % output: % dat: a cell array, where {...} blocks are converted into cell arrays, % and [...] are converted to arrays % % examples: % obj=struct('string','value','array',[1 2 3]); % ubjdata=saveubjson('obj',obj); % dat=loadubjson(ubjdata) % dat=loadubjson(['examples' filesep 'example1.ubj']) % dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % global pos inStr len esc index_esc len_esc isoct arraytoken fileendian systemendian if(regexp(fname,'[\{\}\]\[]','once')) string=fname; elseif(exist(fname,'file')) fid = fopen(fname,'rb'); string = fread(fid,inf,'uint8=>char')'; fclose(fid); else error('input file does not exist'); end pos = 1; len = length(string); inStr = string; isoct=exist('OCTAVE_VERSION','builtin'); arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); jstr=regexprep(inStr,'\\\\',' '); escquote=regexp(jstr,'\\"'); arraytoken=sort([arraytoken escquote]); % String delimiters and escape chars identified to improve speed: esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); index_esc = 1; len_esc = length(esc); opt=varargin2struct(varargin{:}); fileendian=upper(jsonopt('IntEndian','B',opt)); [os,maxelem,systemendian]=computer; jsoncount=1; while pos <= len switch(next_char) case '{' data{jsoncount} = parse_object(opt); case '[' data{jsoncount} = parse_array(opt); otherwise error_pos('Outer level structure must be an object or an array'); end jsoncount=jsoncount+1; end % while jsoncount=length(data); if(jsoncount==1 && iscell(data)) data=data{1}; end if(~isempty(data)) if(isstruct(data)) % data can be a struct array data=jstruct2array(data); elseif(iscell(data)) data=jcell2array(data); end end %% function newdata=parse_collection(id,data,obj) if(jsoncount>0 && exist('data','var')) if(~iscell(data)) newdata=cell(1); newdata{1}=data; data=newdata; end end %% function newdata=jcell2array(data) len=length(data); newdata=data; for i=1:len if(isstruct(data{i})) newdata{i}=jstruct2array(data{i}); elseif(iscell(data{i})) newdata{i}=jcell2array(data{i}); end end %%------------------------------------------------------------------------- function newdata=jstruct2array(data) fn=fieldnames(data); newdata=data; len=length(data); for i=1:length(fn) % depth-first for j=1:len if(isstruct(getfield(data(j),fn{i}))) newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); end end end if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) newdata=cell(len,1); for j=1:len ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); iscpx=0; if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) if(data(j).x0x5F_ArrayIsComplex_) iscpx=1; end end if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) if(data(j).x0x5F_ArrayIsSparse_) if(~isempty(strmatch('x0x5F_ArraySize_',fn))) dim=double(data(j).x0x5F_ArraySize_); if(iscpx && size(ndata,2)==4-any(dim==1)) ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); end if isempty(ndata) % All-zeros sparse ndata=sparse(dim(1),prod(dim(2:end))); elseif dim(1)==1 % Sparse row vector ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); elseif dim(2)==1 % Sparse column vector ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); else % Generic sparse array. ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); end else if(iscpx && size(ndata,2)==4) ndata(:,3)=complex(ndata(:,3),ndata(:,4)); end ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); end end elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) if(iscpx && size(ndata,2)==2) ndata=complex(ndata(:,1),ndata(:,2)); end ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); end newdata{j}=ndata; end if(len==1) newdata=newdata{1}; end end %%------------------------------------------------------------------------- function object = parse_object(varargin) parse_char('{'); object = []; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); % TODO pos=pos+2; end if(next_char == '#') pos=pos+1; count=double(parse_number()); end if next_char ~= '}' num=0; while 1 str = parseStr(varargin{:}); if isempty(str) error_pos('Name of value at position %d cannot be empty'); end %parse_char(':'); val = parse_value(varargin{:}); num=num+1; eval( sprintf( 'object.%s = val;', valid_field(str) ) ); if next_char == '}' || (count>=0 && num>=count) break; end %parse_char(','); end end if(count==-1) parse_char('}'); end %%------------------------------------------------------------------------- function [cid,len]=elem_info(type) id=strfind('iUIlLdD',type); dataclass={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; if(id>0) cid=dataclass{id}; len=bytelen(id); else error_pos('unsupported type at position %d'); end %%------------------------------------------------------------------------- function [data adv]=parse_block(type,count,varargin) global pos inStr isoct fileendian systemendian [cid,len]=elem_info(type); datastr=inStr(pos:pos+len*count-1); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end id=strfind('iUIlLdD',type); if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,cid)); end data=typecast(newdata,cid); adv=double(len*count); %%------------------------------------------------------------------------- function object = parse_array(varargin) % JSON array is written in row-major order global pos inStr isoct parse_char('['); object = cell(0, 1); dim=[]; type=''; count=-1; if(next_char == '$') type=inStr(pos+1); pos=pos+2; end if(next_char == '#') pos=pos+1; if(next_char=='[') dim=parse_array(varargin{:}); count=prod(double(dim)); else count=double(parse_number()); end end if(~isempty(type)) if(count>=0) [object adv]=parse_block(type,count,varargin{:}); if(~isempty(dim)) object=reshape(object,dim); end pos=pos+adv; return; else endpos=matching_bracket(inStr,pos); [cid,len]=elem_info(type); count=(endpos-pos)/len; [object adv]=parse_block(type,count,varargin{:}); pos=pos+adv; parse_char(']'); return; end end if next_char ~= ']' while 1 val = parse_value(varargin{:}); object{end+1} = val; if next_char == ']' break; end %parse_char(','); end end if(jsonopt('SimplifyCell',0,varargin{:})==1) try oldobj=object; object=cell2mat(object')'; if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) object=oldobj; elseif(size(object,1)>1 && ndims(object)==2) object=object'; end catch end end if(count==-1) parse_char(']'); end %%------------------------------------------------------------------------- function parse_char(c) global pos inStr len skip_whitespace; if pos > len || inStr(pos) ~= c error_pos(sprintf('Expected %c at position %%d', c)); else pos = pos + 1; skip_whitespace; end %%------------------------------------------------------------------------- function c = next_char global pos inStr len skip_whitespace; if pos > len c = []; else c = inStr(pos); end %%------------------------------------------------------------------------- function skip_whitespace global pos inStr len while pos <= len && isspace(inStr(pos)) pos = pos + 1; end %%------------------------------------------------------------------------- function str = parseStr(varargin) global pos inStr esc index_esc len_esc % len, ns = length(inStr), keyboard type=inStr(pos); if type ~= 'S' && type ~= 'C' && type ~= 'H' error_pos('String starting with S expected at position %d'); else pos = pos + 1; end if(type == 'C') str=inStr(pos); pos=pos+1; return; end bytelen=double(parse_number()); if(length(inStr)>=pos+bytelen-1) str=inStr(pos:pos+bytelen-1); pos=pos+bytelen; else error_pos('End of file while expecting end of inStr'); end %%------------------------------------------------------------------------- function num = parse_number(varargin) global pos inStr len isoct fileendian systemendian id=strfind('iUIlLdD',inStr(pos)); if(isempty(id)) error_pos('expecting a number at position %d'); end type={'int8','uint8','int16','int32','int64','single','double'}; bytelen=[1,1,2,4,8,4,8]; datastr=inStr(pos+1:pos+bytelen(id)); if(isoct) newdata=int8(datastr); else newdata=uint8(datastr); end if(id<=5 && fileendian~=systemendian) newdata=swapbytes(typecast(newdata,type{id})); end num=typecast(newdata,type{id}); pos = pos + bytelen(id)+1; %%------------------------------------------------------------------------- function val = parse_value(varargin) global pos inStr len true = 1; false = 0; switch(inStr(pos)) case {'S','C','H'} val = parseStr(varargin{:}); return; case '[' val = parse_array(varargin{:}); return; case '{' val = parse_object(varargin{:}); if isstruct(val) if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) val=jstruct2array(val); end elseif isempty(val) val = struct; end return; case {'i','U','I','l','L','d','D'} val = parse_number(varargin{:}); return; case 'T' val = true; pos = pos + 1; return; case 'F' val = false; pos = pos + 1; return; case {'Z','N'} val = []; pos = pos + 1; return; end error_pos('Value expected at position %d'); %%------------------------------------------------------------------------- function error_pos(msg) global pos inStr len poShow = max(min([pos-15 pos-1 pos pos+20],len),1); if poShow(3) == poShow(2) poShow(3:4) = poShow(2)+[0 -1]; % display nothing after end msg = [sprintf(msg, pos) ': ' ... inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ]; error( ['JSONparser:invalidFormat: ' msg] ); %%------------------------------------------------------------------------- function str = valid_field(str) global isoct % From MATLAB doc: field names must begin with a letter, which may be % followed by any combination of letters, digits, and underscores. % Invalid characters will be converted to underscores, and the prefix % "x0x[Hex code]_" will be added if the first character is not a letter. pos=regexp(str,'^[^A-Za-z]','once'); if(~isempty(pos)) if(~isoct) str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once'); else str=sprintf('x0x%X_%s',char(str(1)),str(2:end)); end end if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' ))) return; end if(~isoct) str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_'); else pos=regexp(str,'[^0-9A-Za-z_]'); if(isempty(pos)) return; end str0=str; pos0=[0 pos(:)' length(str)]; str=''; for i=1:length(pos) str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))]; end if(pos(end)~=length(str)) str=[str str0(pos0(end-1)+1:pos0(end))]; end end %str(~isletter(str) & ~('0' <= str & str <= '9')) = '_'; %%------------------------------------------------------------------------- function endpos = matching_quote(str,pos) len=length(str); while(pos<len) if(str(pos)=='"') if(~(pos>1 && str(pos-1)=='\')) endpos=pos; return; end end pos=pos+1; end error('unmatched quotation mark'); %%------------------------------------------------------------------------- function [endpos e1l e1r maxlevel] = matching_bracket(str,pos) global arraytoken level=1; maxlevel=level; endpos=0; bpos=arraytoken(arraytoken>=pos); tokens=str(bpos); len=length(tokens); pos=1; e1l=[]; e1r=[]; while(pos<=len) c=tokens(pos); if(c==']') level=level-1; if(isempty(e1r)) e1r=bpos(pos); end if(level==0) endpos=bpos(pos); return end end if(c=='[') if(isempty(e1l)) e1l=bpos(pos); end level=level+1; maxlevel=max(maxlevel,level); end if(c=='"') pos=matching_quote(tokens,pos+1); end pos=pos+1; end if(endpos==0) error('unmatched "]"'); end
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
saveubjson.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex2/ex2/lib/jsonlab/saveubjson.m
16,123
utf_8
61d4f51010aedbf97753396f5d2d9ec0
function json=saveubjson(rootname,obj,varargin) % % json=saveubjson(rootname,obj,filename) % or % json=saveubjson(rootname,obj,opt) % json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) % % convert a MATLAB object (cell, struct or array) into a Universal % Binary JSON (UBJSON) binary string % % author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu) % created on 2013/08/17 % % $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ % % input: % rootname: the name of the root-object, when set to '', the root name % is ignored, however, when opt.ForceRootName is set to 1 (see below), % the MATLAB variable name will be used as the root name. % obj: a MATLAB object (array, cell, cell array, struct, struct array) % filename: a string for the file name to save the output UBJSON data % opt: a struct for additional options, ignore to use default values. % opt can have the following fields (first in [.|.] is the default) % % opt.FileName [''|string]: a file name to save the output JSON data % opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D % array in JSON array format; if sets to 1, an % array will be shown as a struct with fields % "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for % sparse arrays, the non-zero elements will be % saved to _ArrayData_ field in triplet-format i.e. % (ix,iy,val) and "_ArrayIsSparse_" will be added % with a value of 1; for a complex array, the % _ArrayData_ array will include two columns % (4 for sparse) to record the real and imaginary % parts, and also "_ArrayIsComplex_":1 is added. % opt.ParseLogical [1|0]: if this is set to 1, logical array elem % will use true/false rather than 1/0. % opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single % numerical element will be shown without a square % bracket, unless it is the root object; if 0, square % brackets are forced for any numerical arrays. % opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson % will use the name of the passed obj variable as the % root object name; if obj is an expression and % does not have a name, 'root' will be used; if this % is set to 0 and rootname is empty, the root level % will be merged down to the lower level. % opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), % for example, if opt.JSON='foo', the JSON data is % wrapped inside a function call as 'foo(...);' % opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson % back to the string form % % opt can be replaced by a list of ('param',value) pairs. The param % string is equivallent to a field in opt and is case sensitive. % output: % json: a binary string in the UBJSON format (see http://ubjson.org) % % examples: % jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... % 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... % 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... % 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... % 'MeshCreator','FangQ','MeshTitle','T6 Cube',... % 'SpecialData',[nan, inf, -inf]); % saveubjson('jsonmesh',jsonmesh) % saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') % % license: % BSD, see LICENSE_BSD.txt files for details % % -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) % if(nargin==1) varname=inputname(1); obj=rootname; if(isempty(varname)) varname='root'; end rootname=varname; else varname=inputname(2); end if(length(varargin)==1 && ischar(varargin{1})) opt=struct('FileName',varargin{1}); else opt=varargin2struct(varargin{:}); end opt.IsOctave=exist('OCTAVE_VERSION','builtin'); rootisarray=0; rootlevel=1; forceroot=jsonopt('ForceRootName',0,opt); if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) rootisarray=1; rootlevel=0; else if(isempty(rootname)) rootname=varname; end end if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) rootname='root'; end json=obj2ubjson(rootname,obj,rootlevel,opt); if(~rootisarray) json=['{' json '}']; end jsonp=jsonopt('JSONP','',opt); if(~isempty(jsonp)) json=[jsonp '(' json ')']; end % save to a file if FileName is set, suggested by Patrick Rapin if(~isempty(jsonopt('FileName','',opt))) fid = fopen(opt.FileName, 'wb'); fwrite(fid,json); fclose(fid); end %%------------------------------------------------------------------------- function txt=obj2ubjson(name,item,level,varargin) if(iscell(item)) txt=cell2ubjson(name,item,level,varargin{:}); elseif(isstruct(item)) txt=struct2ubjson(name,item,level,varargin{:}); elseif(ischar(item)) txt=str2ubjson(name,item,level,varargin{:}); else txt=mat2ubjson(name,item,level,varargin{:}); end %%------------------------------------------------------------------------- function txt=cell2ubjson(name,item,level,varargin) txt=''; if(~iscell(item)) error('input is not a cell'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); % let's handle 1D cell first if(len>1) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) '[']; name=''; else txt='['; end elseif(len==0) if(~isempty(name)) txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; else txt='Z'; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=struct2ubjson(name,item,level,varargin) txt=''; if(~isstruct(item)) error('input is not a struct'); end dim=size(item); if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now item=reshape(item,dim(1),numel(item)/dim(1)); dim=size(item); end len=numel(item); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end for j=1:dim(2) if(dim(1)>1) txt=[txt '[']; end for i=1:dim(1) names = fieldnames(item(i,j)); if(~isempty(name) && len==1) txt=[txt S_(checkname(name,varargin{:})) '{']; else txt=[txt '{']; end if(~isempty(names)) for e=1:length(names) txt=[txt obj2ubjson(names{e},getfield(item(i,j),... names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; end end txt=[txt '}']; end if(dim(1)>1) txt=[txt ']']; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=str2ubjson(name,item,level,varargin) txt=''; if(~ischar(item)) error('input is not a string'); end item=reshape(item, max(size(item),[1 0])); len=size(item,1); if(~isempty(name)) if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end else if(len>1) txt='['; end end isoct=jsonopt('IsOctave',0,varargin{:}); for e=1:len val=item(e,:); if(len==1) obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; if(isempty(name)) obj=['',S_(val),'']; end txt=[txt,'',obj]; else txt=[txt,'',['',S_(val),'']]; end end if(len>1) txt=[txt ']']; end %%------------------------------------------------------------------------- function txt=mat2ubjson(name,item,level,varargin) if(~isnumeric(item) && ~islogical(item)) error('input is not an array'); end if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) cid=I_(uint32(max(size(item)))); if(isempty(name)) txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; else if(isempty(item)) txt=[S_(checkname(name,varargin{:})),'Z']; return; else txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; end end else if(isempty(name)) txt=matdata2ubjson(item,level+1,varargin{:}); else if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); txt=[S_(checkname(name,varargin{:})) numtxt]; else txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; end end return; end if(issparse(item)) [ix,iy]=find(item); data=full(item(find(item))); if(~isreal(item)) data=[real(data(:)),imag(data(:))]; if(size(item,1)==1) % Kludge to have data's 'transposedness' match item's. % (Necessary for complex row vector handling below.) data=data'; end txt=[txt,S_('_ArrayIsComplex_'),'T']; end txt=[txt,S_('_ArrayIsSparse_'),'T']; if(size(item,1)==1) % Row vector, store only column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([iy(:),data'],level+2,varargin{:})]; elseif(size(item,2)==1) % Column vector, store only row indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,data],level+2,varargin{:})]; else % General case, store row and column indices. txt=[txt,S_('_ArrayData_'),... matdata2ubjson([ix,iy,data],level+2,varargin{:})]; end else if(isreal(item)) txt=[txt,S_('_ArrayData_'),... matdata2ubjson(item(:)',level+2,varargin{:})]; else txt=[txt,S_('_ArrayIsComplex_'),'T']; txt=[txt,S_('_ArrayData_'),... matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; end end txt=[txt,'}']; %%------------------------------------------------------------------------- function txt=matdata2ubjson(mat,level,varargin) if(isempty(mat)) txt='Z'; return; end if(size(mat,1)==1) level=level-1; end type=''; hasnegtive=(mat<0); if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) if(isempty(hasnegtive)) if(max(mat(:))<=2^8) type='U'; end end if(isempty(type)) % todo - need to consider negative ones separately id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); if(isempty(find(id))) error('high-precision data is not yet supported'); end key='iIlL'; type=key(find(id)); end txt=[I_a(mat(:),type,size(mat))]; elseif(islogical(mat)) logicalval='FT'; if(numel(mat)==1) txt=logicalval(mat+1); else txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; end else if(numel(mat)==1) txt=['[' D_(mat) ']']; else txt=D_a(mat(:),'D',size(mat)); end end %txt=regexprep(mat2str(mat),'\s+',','); %txt=regexprep(txt,';',sprintf('],[')); % if(nargin>=2 && size(mat,1)>1) % txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); % end if(any(isinf(mat(:)))) txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); end if(any(isnan(mat(:)))) txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); end %%------------------------------------------------------------------------- function newname=checkname(name,varargin) isunpack=jsonopt('UnpackHex',1,varargin{:}); newname=name; if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) return end if(isunpack) isoct=jsonopt('IsOctave',0,varargin{:}); if(~isoct) newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); else pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); if(isempty(pos)) return; end str0=name; pos0=[0 pend(:)' length(name)]; newname=''; for i=1:length(pos) newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; end if(pos(end)~=length(name)) newname=[newname str0(pos0(end-1)+1:pos0(end))]; end end end %%------------------------------------------------------------------------- function val=S_(str) if(length(str)==1) val=['C' str]; else val=['S' I_(int32(length(str))) str]; end %%------------------------------------------------------------------------- function val=I_(num) if(~isinteger(num)) error('input is not an integer'); end if(num>=0 && num<255) val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; return; end key='iIlL'; cid={'int8','int16','int32','int64'}; for i=1:4 if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; return; end end error('unsupported integer'); %%------------------------------------------------------------------------- function val=D_(num) if(~isfloat(num)) error('input is not a float'); end if(isa(num,'single')) val=['d' data2byte(num,'uint8')]; else val=['D' data2byte(num,'uint8')]; end %%------------------------------------------------------------------------- function data=I_a(num,type,dim,format) id=find(ismember('iUIlL',type)); if(id==0) error('unsupported integer array'); end % based on UBJSON specs, all integer types are stored in big endian format if(id==1) data=data2byte(swapbytes(int8(num)),'uint8'); blen=1; elseif(id==2) data=data2byte(swapbytes(uint8(num)),'uint8'); blen=1; elseif(id==3) data=data2byte(swapbytes(int16(num)),'uint8'); blen=2; elseif(id==4) data=data2byte(swapbytes(int32(num)),'uint8'); blen=4; elseif(id==5) data=data2byte(swapbytes(int64(num)),'uint8'); blen=8; end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; end data=['[' data(:)']; else data=reshape(data,blen,numel(data)/blen); data(2:blen+1,:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function data=D_a(num,type,dim,format) id=find(ismember('dD',type)); if(id==0) error('unsupported float array'); end if(id==1) data=data2byte(single(num),'uint8'); elseif(id==2) data=data2byte(double(num),'uint8'); end if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) format='opt'; end if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) cid=I_(uint32(max(dim))); data=['$' type '#' I_a(dim,cid(1)) data(:)']; else data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; end data=['[' data]; else data=reshape(data,(id*4),length(data)/(id*4)); data(2:(id*4+1),:)=data; data(1,:)=type; data=data(:)'; data=['[' data(:)' ']']; end %%------------------------------------------------------------------------- function bytes=data2byte(varargin) bytes=typecast(varargin{:}); bytes=bytes(:)';
github
mridulnagpal/Andrew-Ng-ML-Course-Assignments-master
submit.m
.m
Andrew-Ng-ML-Course-Assignments-master/machine-learning-ex4/ex4/submit.m
1,635
utf_8
ae9c236c78f9b5b09db8fbc2052990fc
function submit() addpath('./lib'); conf.assignmentSlug = 'neural-network-learning'; conf.itemName = 'Neural Networks Learning'; conf.partArrays = { ... { ... '1', ... { 'nnCostFunction.m' }, ... 'Feedforward and Cost Function', ... }, ... { ... '2', ... { 'nnCostFunction.m' }, ... 'Regularized Cost Function', ... }, ... { ... '3', ... { 'sigmoidGradient.m' }, ... 'Sigmoid Gradient', ... }, ... { ... '4', ... { 'nnCostFunction.m' }, ... 'Neural Network Gradient (Backpropagation)', ... }, ... { ... '5', ... { 'nnCostFunction.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(3 * sin(1:1:30), 3, 10); Xm = reshape(sin(1:32), 16, 2) / 5; ym = 1 + mod(1:16,4)'; t1 = sin(reshape(1:2:24, 4, 3)); t2 = cos(reshape(1:2:40, 4, 5)); t = [t1(:) ; t2(:)]; if partId == '1' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); elseif partId == '2' [J] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); elseif partId == '3' out = sprintf('%0.5f ', sigmoidGradient(X)); elseif partId == '4' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 0); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; elseif partId == '5' [J, grad] = nnCostFunction(t, 2, 4, 4, Xm, ym, 1.5); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; end end