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
rossimattia/light-field-super-resolution-master
lc1c2.m
.m
light-field-super-resolution-master/lc1c2.m
2,809
utf_8
2cb0985cfde92e5980cbb393c8b8f752
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [ZB, lmin, lmax, c1min, c1max, c2min, c2max] = lc1c2(ZA, direction) % LC1C2 converts the input light field from RGB to LC1C2 if direction is % 'forward', and viceversa if direction is 'backward'. % % INPUT: % ZA - the input light field. % direction - a string specifing the conversion type. % % OUTPUT: % ZB - the transformed light field. % lmin - the minimum value of the L channel for R, G, and B, in [0,1]. % lmax - the maximun value of the L channel for R, G, and B, in [0,1]. % c1min - the minimum value of the C1 channel for R, G, and B, in [0,1]. % c1max - the maximun value of the C1 channel for R, G, and B, in [0,1]. % c2min - the minimum value of the C2 channel for R, G, and B, in [0,1]. % c2max - the maximun value of the C2 channel for R, G, and B, in [0,1]. % ==== Trasformation matrices ============================================= % From RGB to LC1C2. MF = ... [ ... 1/4 1/2 1/4; ... -1/4 1/2 -1/4; ... -1/4 0.0 1/4 ... ]; % From LC1C2 to RGB. MB = ... [ ... 1.0 -1.0 -2.0; ... 1.0 1.0 0.0; ... 1.0 -1.0 2.0 ... ]; % Set the boundary values. lmin = 0; lmax = 1; c1min = -1/2; c1max = 1/2; c2min = -1/4; c2max = 1/4; % ==== Light field dimensions ============================================= % Angular resolution. vRes = size(ZA, 1); hRes = size(ZA, 2); % Spatial resolution. yRes = size(ZA{1, 1}, 1); xRes = size(ZA{1, 1}, 2); % Check that the input views have 3 channels. if (size(ZA{1, 1}, 3) ~= 3) error('Input views must have 3 channels !!!\n\n'); end % Select the correct transformation matrix. switch direction case 'forward' M = MF; case 'backward' M = MB; otherwise error('Bad input arguments !!!\n\n'); end % Perform the transformation ... % Vectorize ZA. zA = lf2col(ZA); % Store the 3 vectorized light fields as the 3 columns of aux. aux = reshape(zA, [], 3); % Transform the 3 columns of aux. aux = aux * (M'); % Note that the previous line is equivalent to: % aux = (M * (aux'))'; % Arrange the tranformed (and vectorized) light field into a 2D cell array of views. ZB = col2lf( ... aux(:), ... vRes, hRes, ... yRes, xRes, 3 ... ); end
github
rossimattia/light-field-super-resolution-master
psnrfr.m
.m
light-field-super-resolution-master/psnrfr.m
1,095
utf_8
63c482a4498723630c581c282420c089
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function P = psnrfr(A, B, peak, frame) % PSNRFR computes the PSNR of image A with reference to image B, but it % removes a frame around the image before the computation. % % INPUT: % A - the image to evaluate, % B - the reference image, % peak - the maximum pixel value (e.g., 0 and 255), % frame - the number of pixels to remove from the border. % % OUTPUT: % P - the PSNR. % ========================================================================= aux1 = A((1 + frame):(end - frame), (1 + frame):(end - frame), :); aux2 = B((1 + frame):(end - frame), (1 + frame):(end - frame), :); P = psnr(double(aux1), double(aux2), peak); end
github
rossimattia/light-field-super-resolution-master
lf2col.m
.m
light-field-super-resolution-master/lf2col.m
1,007
utf_8
4a7d4b7e99d8a0246e5ceb3d3cc1fca6
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function z = lf2col(Z) % LF2COL vectorizes the input light field Z. The 2D cell array Z is scanned % in column major order, and the same for its views Z{t,s}. % If the light field views have more than one channel, then all the light % fields (one for each channel) are vectorized separately, and then the % vectorized light fields are stacked together. % % INPUT: % Z - a light field. % % OUTPUT: % z - the vectorized light field. % ========================================================================= aux = cell2mat(Z(:)'); z = aux(:); end
github
rossimattia/light-field-super-resolution-master
blurmat.m
.m
light-field-super-resolution-master/blurmat.m
1,939
utf_8
c2a87fb10acdb46bebdd93ec0aeb8e13
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function B = blurmat(height, width, factor) % BLURMAT builds a matrix that permits to implement image blurring as a % matrix/vector multiplication. The blurring consists in a box kernel. % % INPUT: % height - the image height. % width - the image width. % factor - the size of the (factor x factor) blurring kernel. % % OUTPUT: % B - the blur matrix. % % The blurring of an image is defined as the convolution of the image with % a 2D box kernel. Since 2D box kernels are separable, convolution of a % (height x width) image X with a 2D box kernel can be implemented by first % filtering the columns of X with a 1D box kernel, and then its rows with % the same kernel. % % Let Bc be the filtering matrix for the columns, and let Br be the one for % the rows. Then X can be filtered as follows: % Y = (Br*(Bc*X)')' = (Br * X' * Bc')' = Bc * X * Br' % % In vectorized form we have Y(:) = kron(Br, Bc) * X(:), hence B = kron(Br, Bc). % % Note that the matrices Bc and Br may be different, despite implementing % the same kernel, as image X may not be square. % ==== Compute the blur matrix ============================================ % Compute Bc and Br. Bc = avgmtx(height, factor); Br = avgmtx(width, factor); % Compute the blur matrix B. B = kron(Br, Bc); end function mtx = avgmtx(n, factor) kernel = zeros((2 * (factor - 1)) + 1, 1); kernel(factor:end) = 1 / factor; diags = -(factor - 1):1:(factor - 1); D = repmat(kernel', [n, 1]); mtx = spdiags(D, diags, n, n); end
github
rossimattia/light-field-super-resolution-master
psnrlf.m
.m
light-field-super-resolution-master/psnrlf.m
1,370
utf_8
4c46dc0d7cbf0d5675f32ad1da2dabc7
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function P = psnrlf(Z1, Z2, peak, frame) % PSNRLF computes the PSNR of the light field V1 with reference to the light field V2. % % INPUT: % Z1 - the light field to evaluate, % Z2 - the reference light field, % peak - the maximum pixel value (e.g., 0 and 255), % frame - the number of pixels to remove from the border. % % OUTPUT: % P - a 2D matrix with P(i,j) the PSNR of the view V1{i,j}. % ========================================================================= % Angular resolution. vRes = size(Z1, 1); hRes = size(Z1, 2); P = zeros(vRes, hRes); for s = 1:1:hRes for t = 1:1:vRes % Remove the border. aux1 = Z1{t, s}((1 + frame):(end - frame), (1 + frame):(end - frame), :); aux2 = Z2{t, s}((1 + frame):(end - frame), (1 + frame):(end - frame), :); % Compute the PSNR. P(t, s) = psnr(double(aux1), double(aux2), peak); end end end
github
rossimattia/light-field-super-resolution-master
crop.m
.m
light-field-super-resolution-master/crop.m
2,003
utf_8
5a3dcceb9cf126f648639bfb7e1f3e9b
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function ZCR = crop(Z, vRange, hRange, yRange, xRange) % CROP reduces the angular and/or spatial resolution of the input light % field by cropping the number of views (angular cropping) and/or the views % area (spatial cropping). % % INPUT: % Z - the light field to be cropped. % vRange - a two element vector with the starting and ending vertical angular cropping indexes. % hRange - a two element vector with the starting and ending horizontal angular cropping indexes. % yRange - a two element vector with the starting and ending vertical spatial cropping indexes. % xRange - a two element vector with the starting and ending horizontal spatial cropping indexes. % % OUTPUT: % ZCR - the cropped light field. % ==== Auxiliary variables ================================================ % Compute the (selection) vectors for angular cropping. vSelec = vRange(1):1:vRange(2); hSelec = hRange(1):1:hRange(2); % Compute the (selection) vectors for spatial cropping. ySelec = yRange(1):1:yRange(2); xSelec = xRange(1):1:xRange(2); % ==== Copy the input light field ========================================= ZCR = Z; % ==== Perform the angular cropping ======================================= if ~(isempty(vSelec) || isempty(hSelec)) ZCR = ZCR(vSelec, hSelec); end % ==== Perform the spatial cropping ======================================= if ~(isempty(ySelec) || isempty(xSelec)) M = size(ZCR, 1) * size(ZCR, 2); for u = 1:1:M ZCR{u} = ZCR{u}(ySelec, xSelec, :); end end end
github
rossimattia/light-field-super-resolution-master
split.m
.m
light-field-super-resolution-master/split.m
2,303
utf_8
600c57c8231202bf27c695576ba7b8e1
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [zSub, yCoord, xCoord] = split(Z, yResSub, xResSub, overlap) % SPLIT divides the input light field into sub light fields. % % INPUT: % Z - a light field. % yResSub - the vertical spatial resolution of a sub light field. % xResSub - the horizontal spatial resolution of a sub light field. % overlap - the pixel overlap between sub light fields. % % OUTPUT: % zSub - the sub light fields in vectorized form. % yCoord - the vertical spatial coordinate of the top left pixel of each sub light field. % xCoord - the horizontal spatial coordinate of the top left pixel of each sub light field. % ========================================================================= % Light field Z angular resolution. vRes = size(Z, 1); hRes = size(Z, 2); M = vRes * hRes; % Light field Z spatial resolution. yRes = size(Z{1, 1}, 1); xRes = size(Z{1, 1}, 2); % Compute the VERTICAL extraction coordinates for each view. yStep = yResSub - overlap; y = [(1:yStep:(yRes - yResSub)), (yRes - yResSub + 1)]; % Compute the HORIZONTAL extraction coordinates for each view. xStep = xResSub - overlap; x = [(1:xStep:(xRes - xResSub)), (xRes - xResSub + 1)]; % Compute ALL the sub light field coordinates (in a view). [X, Y] = meshgrid(x, y); yCoord = Y(:); xCoord = X(:); % Compute the number of sub light fields. subNum = length(yCoord); % Allocate the space for the (vectorized) sub light fields. zSub = zeros(yResSub * xResSub * M, subNum); % Stack all the views, proceding in column major order. stack = cell2mat( reshape(Z, [1, 1, M]) ); % Extract the sub light fields. ptr = 1; aux = zeros(yResSub, xResSub, M); for k = 1:1:subNum aux(:, :, :) = stack( ... yCoord(k):(yCoord(k) + yResSub - 1), ... xCoord(k):(xCoord(k) + xResSub - 1), ... :); zSub(:, ptr) = aux(:); ptr = ptr + 1; end end
github
rossimattia/light-field-super-resolution-master
decimat.m
.m
light-field-super-resolution-master/decimat.m
1,756
utf_8
26507b373b8ab7de4aa7de056b990ae0
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [D, newHeight, newWidth] = decimat(height, width, factor) % DECIMAT builds a matrix that permits to implement image decimation as a % matrix/vector multiplication. % % INPUT: % height - the image height. % width - the image width. % factor - the decimation factor (sampling rate). % % OUTPUT: % B - the decimation matrix. % % The decimation of an (height x width) image X can be carried out on the % rows and the columns separately. % % Let Dc be the decimation matrix for the columns, and let Dr be the one % for the rows. Then X can be decimated as follows: % Y = (Dr*(Dc*X)')' = (Dr * X' * Dc')' = Dc * X * Dr' % % In vectorized form we have Y(:) = kron(Dr, Dc) * X(:), hence D = kron(Dr, Dc). % ==== Compute the decimation matrix ====================================== % Compute Dc and Dr. Dc = decimtx1D(height, factor); Dr = decimtx1D(width, factor); % Compute the decimation matrix D. D = kron(Dr, Dc); newHeight = size(Dc, 1); newWidth= size(Dr, 1); end function mtx = decimtx1D(n, factor) height = ceil(double(n) / factor); width = n; rows = zeros(height, 1); cols = zeros(height, 1); counter = 1; for k = 1:1:height rows(k) = k; cols(k) = counter; counter = counter + factor; end mtx = sparse(rows, cols, ones(height, 1), height, width); end
github
rossimattia/light-field-super-resolution-master
ppm.m
.m
light-field-super-resolution-master/ppm.m
2,856
utf_8
bf9675b230471590d35d0289073e95cb
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [x, history] = ppm(P, q, r, beta, iters, init) % PPM solves the following problem using the Proximal Point Method: % % minimize_x (0.5 * x' * P * x) + (q' * x) + r % % INPUT: % P - a nxn positive semi definite matrix (double). % q - a nx1 vector (double). % r - a scalar (double). % beta - the proximal constant (double). % iters - the desired number of iterations. % init - the initial guess for the minimizer (double), or an empty array []. % % OUTPUT: % x - the computed minimizer (a nx1 vector of doubles). % history - a structure containing the objective value, and the residual % norm of x at each iteration. % ========================================================================= tStart = tic; % ==== Global constants =================================================== % QUIET = 1 suppresses any screen output. QUIET = 1; % Absolute tolerance. EPS_ABS = 1e-4; % ==== PPM solver ========================================================= % Size of P. n = size(P, 1); % Allocate the solver variables. x = zeros(n, 1); x_old = zeros(n, 1); % Allocate the struct history. history.objval = zeros(iters, 1); history.r_norm = zeros(iters, 1); if ~QUIET fprintf('%3s\t%10s\t%10s\n', 'iter', 'r norm', 'objective'); end % Compute the threshold for the stopping condition. threshold = EPS_ABS * sqrt(n); % Precompute the matrix P + ((1/beta) * I) with I the identity matrix. A = P + ((1 / beta) * speye(n)); for k = 1:1:iters % Updates x. if (k == 1) && (~isempty(init)) x(:) = init; else [x(:), pcgFlag] = pcg(A, (x / beta) - q); % if (pcgFlag ~= 0) % error('ERROR: pcg did not converge !!!\n\n'); % end end % Check the objective function value. history.objval(k) = objfun(P, q, r, x); % Compute the residual. history.r_norm(k) = norm(x - x_old); if ~QUIET fprintf('%3d\t%10.4f\t%10.2f\n', k, history.r_norm(k), history.objval(k)); end % Evaluate the stopping criterion. if (history.r_norm(k) < threshold) break; end % Save the current value of x. x_old(:) = x; end if ~QUIET tElapsed = toc(tStart); fprintf('\n>>> ppm <<< time: %f\n', tElapsed); end end function val = objfun(P, q, r, x) val = (0.5 * x' * P * x) + (q' * x) + r; end
github
rossimattia/light-field-super-resolution-master
super.m
.m
light-field-super-resolution-master/super.m
8,367
utf_8
06b04661004034a0a1796a4c4826521f
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [ZInit, ZHR, ZInit_L, ZHR_L] = super( ... ZLR, ... factor, ... yResSubLR, xResSubLR, ... overlapLR, ... patRad, intSigma, dispMax, ... lambda0, lambda1, lambda2, ... innerCycles, outerCycles, ... warpMode, ... guessFlag, ... poolSize, ... alpha ... ) % SUPER super resolves the input light field. It divides the Low Resolution % input light field into different sub light fields and super-resolves their % luminances via GBSUPER. The super-resolved luminance of the different % sub light fields are merged to produce the lumianance of the complete % super-resolved light field. The chrominances of the input Low Resolution % light field are simpy up-sampled via bilinear interpolation. % % INPUT: % ZLR - the low resolution light field to super-resolve (double [0,1]). % factor - the super-resolution factor (integer). % yResSubLR - the vertical spatial resolution of a Low Resolution sub light field. % xResSubLR - the horizontal spatial resolution of a Low Resolution sub light field. % overlap - the pixel overlap between sub light fields. % patRad - the size of the (patRad x patRad) patch used in the graph construction. % intSigma - the standard deviation value used in the graph construction. % dispMax - the maximum assumed disparity value. % lambda0 - the weight of the data fidelity term. % lambda1 - the weight of the warping term. % lambda2 - the weight of the graph-based regularizer. % innerCycles - the maximum number of iteration to be performed by the solver. % outerCycles - the number of iterations of the GB super-resolution algorithm. % warpMode - 0 for the Direct warping matrix construction, and 1 for the % SQuare-constraint matrix construction. % guessFlag - 0 to initialize the solver with a zero light field, and 1 to % initialize the solver with ZInit. % poolSize - the number of threads activated by PARFOR. % alpha - the Tukey window parameter (the window is used in the merging phase). % % OUTPUT: % ZInit - the RGB bilinear up-sampled version of ZLR (uint8 [0,255]). % ZHR - the RGB Graph-Based super-resolved version of ZLR (uint8 [0,255]). % ZInit_L - the luminance of ZInit (double [0,1]). % ZHR_L - the luminance of ZHR (double [0,1]). % % Note that ZInit_L and ZHR_L are the light field luminances obtained from % the up-sampling and super-resolution of ZLR, respectively. They are NOT % extracted from ZInit and ZHR, as these two are in the uint8 data type, % therefore they have undergone a quantization step. % % Note that this function assumes that the views in Z have dimensions which % are multiple of the super-resolution factor. % ==== Light field dimensions ============================================= % Angular resolution. vRes = size(ZLR, 1); hRes = size(ZLR, 2); M = vRes * hRes; % Spatial resolution (LR). yResLR = size(ZLR{1, 1}, 1); xResLR = size(ZLR{1, 1}, 2); % Spatial resolution (HR). yResHR = factor * yResLR; xResHR = factor * xResLR; % ==== RGB to LC1C2 ======================================================= % Turn ZLR from RGB to LC1C2. [aux, lmin, lmax, c1min, c1max, c2min, c2max] = lc1c2(ZLR, 'forward'); % Separate the channels L, C1, and C2 ... aux = reshape(lf2col(aux), [], 3); ZLR_L = col2lf( ... aux(:, 1), ... vRes, hRes, ... yResLR, xResLR, 1 ... ); ZLR_C1 = col2lf( ... aux(:, 2), ... vRes, hRes, ... yResLR, xResLR, 1 ... ); ZLR_C2 = col2lf( ... aux(:, 3), ... vRes, hRes, ... yResLR, xResLR, 1 ... ); % ==== Compute an initial estimate of the HR light field ================== % Perform interpolation of each view, separately. aux = zeros(yResHR, xResHR); ZInit_L = cell(vRes, hRes); ZInit_C1 = cell(vRes, hRes); ZInit_C2 = cell(vRes, hRes); for u = 1:1:M aux(:, :) = upsample(ZLR_L{u}, factor, 'linear'); aux(aux < lmin) = lmin; aux(aux > lmax) = lmax; ZInit_L{u} = aux; aux(:, :) = upsample(ZLR_C1{u}, factor, 'linear'); aux(aux < c1min) = c1min; aux(aux > c1max) = c1max; ZInit_C1{u} = aux; aux(:, :) = upsample(ZLR_C2{u}, factor, 'linear'); aux(aux < c2min) = c2min; aux(aux > c2max) = c2max; ZInit_C2{u} = aux; end % ==== Split ZLR_L into sub light fields ================================== % Sub-light-field spatial resolution (HR). yResSubHR = factor * yResSubLR; xResSubHR = factor * xResSubLR; overlapHR = factor * overlapLR; % Split ZLR_L. [zSubLR, ~, ~] = split(ZLR_L, yResSubLR, xResSubLR, overlapLR); % Split the initial estimate ZInit_L. [zSubInit, yCoord, xCoord] = ... split(ZInit_L, yResSubHR, xResSubHR, overlapHR); % Number of sub-light-fields. subNum = size(zSubLR, 2); fprintf('Number of SUB-LIGHT-FIELDS: %d\n', subNum); % ==== Sub-light-field blur and decimation matrices ======================= % Blur. auxB = blurmat(yResSubHR, xResSubHR, factor); B = kron(speye(M, M), auxB); % Decimation. auxD = decimat(yResSubHR, xResSubHR, factor); D = kron(speye(M, M), auxD); % ==== Super-resolve ZLR_L ================================================ % Super-resolve each LR sub-light-field, separately. aux = cell(subNum, 1); if poolSize > 1 % PARALLEL COMPUTING ... % Initialize the pool. p = parpool(poolSize); parfor k = 1:1:subNum aux{k} = ... gbsuper( ... col2lf(zSubLR(:, k), vRes, hRes, yResSubLR, xResSubLR, 1), ... col2lf(zSubInit(:, k), vRes, hRes, yResSubHR, xResSubHR, 1), ... B, D, ... patRad, intSigma, dispMax, ... lambda0, lambda1, lambda2, ... lmin, lmax, ... innerCycles, outerCycles, ... warpMode, ... guessFlag); end % Terminate the pool. delete(p); else % SEQUENTIAL COMPUTING ... for k = 1:1:subNum aux{k} = ... gbsuper( ... col2lf(zSubLR(:, k), vRes, hRes, yResSubLR, xResSubLR, 1), ... col2lf(zSubInit(:, k), vRes, hRes, yResSubHR, xResSubHR, 1), ... B, D, ... patRad, intSigma, dispMax, ... lambda0, lambda1, lambda2, ... lmin, lmax, ... innerCycles, outerCycles, ... warpMode, ... guessFlag); end end % Vectorize all the super-resolved sub-light-fields. zSubHR = zeros(size(zSubInit, 1), subNum); for k = 1:1:subNum zSubHR(:, k) = lf2col(aux{k}); end % Merge the super-resolved sub-light-fields. ZHR_L = merge( ... zSubHR, ... vRes, hRes, ... yResHR, xResHR, ... yResSubHR, xResSubHR, ... yCoord, xCoord, ... alpha ... ); % ==== Upsamples ZLR_C1 and ZLR_C2 ==================================== % Perform interpolation of each view, separately. aux = zeros(yResHR, xResHR); ZHR_C1 = cell(vRes, hRes); ZHR_C2 = cell(vRes, hRes); for u = 1:1:M aux(:, :) = upsample(ZLR_C1{u}, factor, 'cubic'); aux(aux < c1min) = c1min; aux(aux > c1max) = c1max; ZHR_C1{u} = aux; aux(:, :) = upsample(ZLR_C2{u}, factor, 'cubic'); aux(aux < c2min) = c2min; aux(aux > c2max) = c2max; ZHR_C2{u} = aux; end % ==== LC1C2 to RGB ======================================================= % Process ZInit ... % Organize the channels L, C1, and C2 of ZInit into a single light field. ZInit = col2lf( ... cat(1, lf2col(ZInit_L), lf2col(ZInit_C1), lf2col(ZInit_C2)), ... vRes, hRes, ... yResHR, xResHR, 3 ... ); % Converts ZInit from LC1C2 to RGB. ZInit = lc1c2(ZInit, 'backward'); % Process ZHR ... % Organize channel L, C1, and C2 of ZHR into a single light field. ZHR = col2lf( ... cat(1, lf2col(ZHR_L), lf2col(ZHR_C1), lf2col(ZHR_C2)), ... vRes, hRes, ... yResHR, xResHR, 3 ... ); % Convert ZHR from LC1C2 to RGB. ZHR = lc1c2(ZHR, 'backward'); end
github
rossimattia/light-field-super-resolution-master
lf2grid.m
.m
light-field-super-resolution-master/lf2grid.m
1,186
utf_8
8df882ce23e800d6d040f671ccfde7ad
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [] = lf2grid(Z, path) % LF2GRID receives a light field and saves it a set of PNG images named % according to the reference system adopted in the HCI light field dataset. % % INPUT: % Z - a light field. % path - the destination path. % ========================================================================= % Angular resolution. vRes = size(Z, 1); hRes = size(Z, 2); % Create the output folder (in the case that it does not exist yet). mkdir(path); % Write each view to a PNG file, according to the HCI dataset convention. for s = 1:1:hRes for t = 1:1:vRes name = sprintf([path, 'out_%02d_%02d.png'], s - 1, t - 1); imwrite(Z{vRes - t + 1, hRes - s + 1}, name); end end end
github
rossimattia/light-field-super-resolution-master
col2lf.m
.m
light-field-super-resolution-master/col2lf.m
1,406
utf_8
2effc6971bcd2d6e35de61e43fe313a0
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function Z = col2lf(z, vRes, hRes, yRes, xRes, channels) % COL2LF reverts the operation performed by function LF2COL. % % INPUT: % z - the vectorized light field. % vRes - the light field vertical angular resolution. % hRes - the light field horizontal angular resolution. % yRes - the light field vertical spatial resolution. % xRes - the light field horizontal spatial resolution. % channels - the number of channels in each view. % % OUTPUT: % Z - the input light field stored as a (vRes x hRes) cell array of % (yRes x xRes x channels) views. % ========================================================================= % Number of views. M = vRes * hRes; % Perform the reshaping. aux = reshape(z, yRes, (length(z) / channels) / yRes, channels); if (channels > 1) aux = mat2cell(aux, yRes, ones(M, 1) * xRes, channels); else aux = mat2cell(aux, yRes, ones(M, 1) * xRes); end Z = reshape(aux, vRes, hRes); end
github
rossimattia/light-field-super-resolution-master
gbsuper.m
.m
light-field-super-resolution-master/gbsuper.m
5,376
utf_8
d3dd7a1f2be7dc9c83473e293bb4b220
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function ZEst = gbsuper( ... ZLR, ZInit, ... B, D, ... patRad, intSigma, dispMax, ... lambda0, lambda1, lambda2, ... lb, ub, ... innerCycles, outerCycles, ... warpMode, ... guessFlag) % GBSUPER super-resolves the input low resolution light field. % % INPUT: % ZLR - the low resolution light field to super-resolve (double [0,1]). % ZInit - an initial guess on the high resolution light field (double [0,1]). % B - the blur matrix. % D - the decimation matrix. % patRad - the size of the (patRad x patRad) patch used in the graph construction. % intSigma - the standard deviation value used in the graph construction. % dispMax - the maximum assumed disparity value. % lambda0 - the weight of the data fidelity term. % lambda1 - the weight of the warping term. % lambda2 - the weight of the graph-based regularizer. % lb - the pixel value lower bound used in the solver. % ub - the pixel value upper bound used in the solver. % innerCycles - the maximum number of iteration to be performed by the solver. % outerCycles - the number of iterations of the GB super-resolution algorithm. % warpMode - 0 for the Direct warping matrix construction, and 1 for % the SQuare-constraint matrix construction. % guessFlag - 0 to initialized the solver with a zero light field, and 1 to % initialize the solver with ZInit. % % OUTPUT: % ZEst - the super resolved light field (double [0,1]). % ==== Solver's fixed parameters ========================================== beta = 1.0; % ==== Sub light field dimensions ========================================= % Angular resolution. vRes = size(ZInit, 1); hRes = size(ZInit, 2); M = vRes * hRes; % Spatial resolution (HR). yRes = size(ZInit{1, 1}, 1); xRes = size(ZInit{1, 1}, 2); N = yRes * xRes; % ==== Perform super resolution =========================================== % Precompute the fixed problem terms. zLR = lf2col(ZLR); % Start the minimization. zHist = zeros(N * M, outerCycles); ZGuess = ZInit; for k = 1:1:outerCycles fprintf('ITER. %d\n', k); % Compute the inter-views graph and the warping matrices. fprintf('Computing inter-views graph, and warping ...\n'); [WA, WB] = intergraph(ZGuess, patRad, intSigma, dispMax); % Make WA symmetric. E = spones(WA); mask = and(E, E'); WA = WA .* mask; % Consider switching to "or". % If the inter-views term is active, then compute L ... if (lambda2 > 0) L = stdlap(WA); % otherwise, set L to zero. else L = sparse(M * N, M * N); end % Compute the objective function terms ... A = D * B; At = A'; AA = At * A; sumHAFHAF = sparse(M * N, M * N); sumHAFH = sparse(M * N, size(D, 1)); for u = 1:1:M colSta = ((u - 1) * N) + 1; colEnd = ((u - 1) * N) + N; % Compute F, the portion of WB (or WA) responsible for the warping % of the view Z{u} to all its (NON DIAGONAL) neighboring views. switch warpMode case 'SQ' F = WB; case 'DR' F = WA; otherwise error('Invalid warping mode !!!\n\n'); end F(:, 1:(colSta - 1)) = 0; F(:, (colEnd + 1):end) = 0; % Normalize F. auxDiag = sum(F, 2); mask = (auxDiag ~= 0); auxDiag(mask) = 1 ./ auxDiag(mask); % warning: division by 0 leads to Inf values. F = spdiags(auxDiag, 0, M * N, M * N) * F; Ft = F'; H = warpmask(F, B, D, vRes, hRes); H = blkdiag(H{:}); HH = H' * H; sumHAFHAF = sumHAFHAF + (Ft * At * HH * A * F); sumHAFH = sumHAFH + (Ft * At * HH); end P = 2 * (... (lambda0 * AA) ... + (lambda1 * sumHAFHAF) ... + (lambda2 * L) ... ); q = (- 2) * ( ... (lambda0 * At) ... + (lambda1 * sumHAFH) ... ) * zLR; r = 0; % If guessFlag == true, initialize the solver with ZInit. if guessFlag zGuess = lf2col(ZGuess); else zGuess = []; end % Call the solver. fprintf('Minimizing the objective function ...\n'); [aux, ~] = ppm(P, q, r, beta, innerCycles, zGuess); % Project the estimated light field into [lb,ub]^(N*M). aux(aux < lb) = lb; aux(aux > ub) = ub; % Save the estimated light field. zHist(:, k) = aux; % Update the estimate for the next iteration. ZGuess = col2lf(zHist(:, k), vRes, hRes, yRes, xRes, 1); end % Arrange the light field in a (vRes x hRes) cell array. ZEst = col2lf(zHist(:, end), vRes, hRes, yRes, xRes, 1); end
github
rossimattia/light-field-super-resolution-master
upsample.m
.m
light-field-super-resolution-master/upsample.m
1,929
utf_8
be135aad06ea8c8c8203a8c063d9879a
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function B = upsample(A, factor, method) % UPSAMPLE up-samples the input image A by the value factor. % The interpolation assumes that each input pixel has been obtained as the % average of a (factor x factor) patch of pixels. % % INPUT: % A - a gray scale image (double [0,1]). % factor - the upsampling factor (integer), % method - a string specifing the interpolation method to be used. % % OUTPUT: % B - the up-sampled image. % ==== Check input parameters ============================================= if (round(factor) - factor) ~= 0 error('The upsampling factor must be integer !!!\n\n'); end % ==== Dimensions ========================================================= % Input image resolution. yResLR = size(A, 1); xResLR = size(A, 2); % Output image resolution. yResHR = yResLR * factor; xResHR = xResLR * factor; % ==== Perform the interpolation ========================================== % Compute the query coordinates. [Xq, Yq] = meshgrid(1:1:xResHR, 1:1:yResHR); % Compute the coordinates of the available samples. firstX = (1 + factor) / 2; firstY = firstX; lastX = firstX + (factor * (xResLR - 1)); lastY = firstY + (factor * (yResLR - 1)); [X, Y] = meshgrid( ... (firstX - factor):factor:(lastX + factor), ... (firstY - factor):factor:(lastY + factor) ... ); % Create a 1 pixel frame around A. aux = padarray(A, [1, 1], 'symmetric', 'both'); % Perform the interpolation. B = interp2(X, Y, aux, Xq, Yq, method, 0); end
github
rossimattia/light-field-super-resolution-master
merge.m
.m
light-field-super-resolution-master/merge.m
3,178
utf_8
0992c1b1b7d2fd7580d346eea694798d
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function Z = merge(zSub, vRes, hRes, yRes, xRes, yResSub, xResSub, yCoord, xCoord, alpha) % MERGE stiches all the input sub light fields into one single light field. % Each sub light field view is weighted with a Tukey window and multiple % estimates of the same pixel are average. % % INPUT: % zSub - sub light fields in vectorized form. % vRes - the vertical angular resolution of the full light field. % hRes - the horizontal angular resolution of the full light field. % yRes - the vertical spatial resolution of the full light field. % xRes - the horizontal spatial resolution of the full light field. % yResSub - the vertical spatial resolution of a sub light field. % xResSub - the horizontal spatial resolution of a sub light field. % yCoord - the vertical spatial coordinates of the sub light fields. % xCoord - the horizontal spatial coordinates of the sub light fields. % alpha - the Tukey window parameter. % % OUTPUT: % Z - the full light field with spatial resolution (yRes x xRes). % ========================================================================= % Number of views. M = vRes * hRes; % Number of sub light fields. subNum = size(zSub, 2); % Allocate a view stack and a normalization one, as some pixels may have % multiple estimates due to the overlapping. stack = zeros(yRes, xRes, M); wei = zeros(yRes, xRes, M); % Build the merging window. % We build a window which is one pixel larger on each side, and then we % crop it in order to have a (yRes x xRes) window with no zeros at the borders. win = tukeywin(yResSub + 2, alpha) * tukeywin(xResSub + 2, alpha)'; win = win(2:(end - 1), 2:(end - 1)); % Filter each sub light fields with the merging window. This will limit % the border effects when merging the different sub light fields. aux = reshape(zSub, yResSub, xResSub, []); aux = bsxfun(@times, aux, win); % Merge the sub light fields, stored as a stack of view. counter = 0; for k = 1:1:subNum stack( ... yCoord(k):(yCoord(k) + yResSub - 1), ... xCoord(k):(xCoord(k) + xResSub - 1), ... :) = stack( ... yCoord(k):(yCoord(k) + yResSub - 1), ... xCoord(k):(xCoord(k) + xResSub - 1), ... :) + aux(:, :, (counter + 1):(counter + M)); wei( ... yCoord(k):(yCoord(k) + yResSub - 1), ... xCoord(k):(xCoord(k) + xResSub - 1), ... :) = ... bsxfun( ... @plus, ... wei(yCoord(k):(yCoord(k) + yResSub - 1), xCoord(k):(xCoord(k) + xResSub - 1), :), ... win); counter = counter + M; end % Perform the normalization. stack(:, :, :) = stack ./ wei; % Arrange the light field in a "vRes x hRes" cell array. Z = col2lf(stack(:), vRes, hRes, yRes, xRes, 1); end
github
rossimattia/light-field-super-resolution-master
plotlf.m
.m
light-field-super-resolution-master/plotlf.m
4,831
utf_8
3bc68461c55592b205c0193ab55ff25f
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [] = plotlf(varargin) % PLOTLF arranges the input light field view in a single image and plots it. % In addition, it can plot (over the light field) the weights of the edges % from a given pixel (t,s,y,x) to its neighbors. % % INPUT: % varargin{1} - a light field, either gray scale or RGB. % varargin{2} - the maximum intensity value in the light field. % varargin{3} - an adjacency matrix of a graph on the light field. % varargin{4} - the vertical angular coordinate of the pixel of interest. % varargin{5} - the horizontal angular coordinate of the pixel of interest. % varargin{6} - the vertical spatial coordinate of the pixel of interest. % varargin{7} - the horizontal spatial coordinate of the pixel of interest. % % The input light field can be in any format (e.g., double, uint8, uint16). % It will be converted in double [0,1] and plotted. % ==== Constants ========================================================== LEVELS = 2000; SPACE = 1; % ==== Check the number of input arguments ================================ if (nargin ~= 2) && (nargin ~= 7) error('Wrong input argument number !!!\n\n'); end % ==== Read the input light field ========================================= % Read the light field and the peak value. Z = varargin{1}; peak = varargin{2}; % Angular resolution. vRes = size(Z, 1); hRes = size(Z, 2); % Spatial resolution. yRes = size(Z{1, 1}, 1); xRes = size(Z{1, 1}, 2); N = yRes * xRes; % Channels number (grays scale or RGB). channels = size(Z{1, 1}, 3); % ==== Processe the light field =========================================== % Scale Z to [0,1] and extend it to RGB (if Z is gray scale). Zrgb = cell(vRes, hRes); if (channels == 1) || (channels == 3) Zrgb(:, :, :) = col2lf( ... repmat(double(lf2col(Z)) / peak, [4 - channels, 1]), ... vRes, hRes, ... yRes, xRes, 3 ... ); else error('Input light field in neither gray scale nor RGB !!!\n\m'); end % ==== Processe the adjacency matrix ====================================== % If an adjacency matrix is provided too ... if (nargin > 2) % Read the adjacency matrix. W = varargin{3}; % Read the nodes whose connections we want to plot. t = varargin{4}; s = varargin{5}; y = varargin{6}; x = varargin{7}; % Compute the node linear index in the vectorised light field. k = ... N * ( sub2ind([vRes, hRes], t, s) - 1 ) + ... sub2ind([yRes, xRes], y, x); % Extract the "k"-th row of "W". wei = full(W(k, :))'; % Define a colormap. map = zeros(LEVELS, 3); map(:, 1) = linspace(0, 1, LEVELS); % Turn wei values into colormap indexes. auxMax = max(wei); if auxMax > 0 wei = round( ... ((LEVELS - 1) * (wei ./ auxMax)) + 1 ... ); else % Avoid division by zero in the case auxMax is zero. wei = ones(length(wei)); end % Convert wei from indexes of map rows to RGB values. wei = ind2rgb(wei, map); % Arrange wei RGB values into an RGB light field. Wrgb = col2lf(wei(:), vRes, hRes, yRes, xRes, 3); % Merges Zrgb and Wrgb ... % Vectorizes Zrgb and Wrgb. auxZ = lf2col(Zrgb); auxW = lf2col(Wrgb); % Detect those pixels that are connected (i.e., NON zero weight) to pixel k. aux = reshape(auxW, [], 3); aux = sum(aux, 2); mask = (aux > 0); % In Zrgb, replace the connected pixels with the corresponding weights of "Wrgb". mask = repmat(mask, [3, 1]); % mask extension to the 3 color channels. auxZ(mask) = auxW(mask); % Rearrange auxZ as a light field. Zrgb(:, :) = col2lf(auxZ, vRes, hRes, yRes, xRes, 3); end % ==== Stitche together all the views in Zrgb ============================ % Allocate the background. I = zeros(vRes * (yRes + SPACE) + SPACE, hRes * (xRes + SPACE) + SPACE, 3); % Place the views on the background I. vOff = 1; hOff = 1; for s = 1:1:hRes for t = 1:1:vRes I((vOff + 1):(vOff + yRes), (hOff + 1):(hOff + xRes), :) = Zrgb{t, s}; vOff = vOff + yRes + SPACE; end vOff = SPACE; hOff = hOff + xRes + SPACE; end % ==== Plot the stitched viwes ============================================ imshow(I); end
github
rossimattia/light-field-super-resolution-master
stdlap.m
.m
light-field-super-resolution-master/stdlap.m
999
utf_8
ddea561bef99c4f03a31a1c0b01c8f47
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function L = stdlap(W) % STDLAP computes the combinatorial Laplacian associated to the input similarity matrix. % The Laplacian is defined as L = D-W, with D the graph degree matrix. % D is diagonal with D(i,i) equal to sum(W(i, :)). % % INPUT: % W - a similarity matrix. % % OUTPUT: % L - the Laplacian matrix. % ========================================================================= % Compute the degree matrix "D". diagonal = sum(W, 2); n = length(diagonal); D = spdiags(diagonal, 0, n, n); % Compute the Laplacian. L = D - W; end
github
rossimattia/light-field-super-resolution-master
intergraph.m
.m
light-field-super-resolution-master/intergraph.m
12,278
utf_8
f784f75d4f1004b7a92cb4517939f219
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [WA, WB] = intergraph(V, patRad, intSigma, dispMax) % INTERGRAPH computes the graph adjacency matrix used in the graph-based % regularizer and a graph adjacency matrix containing the square-constraint % warping matrices as sub matrices. % % INPUT: % V - a light field. % patRad - the size of the (patRad x patRad) patch to be used in both the % graph and warping matrices construction. % intSigma - the standard deviation value used in the graph construction. % dispMax - the maximum assumed disparity value. % % OUTPUT: % WA - the graph adjacency matrix associated to the regularizer. % WB - the graph adjacency matrix associated to the square-constraint warping matrices. % % Neither WA nor WB is made symmetric. % ==== Light field parameters ============================================= % Angular resolution. vRes = size(V, 1); hRes = size(V, 2); M = vRes * hRes; % Spatial resolution. yRes = size(V{1, 1}, 1); xRes = size(V{1, 1}, 2); N = yRes * xRes; % ==== Compute the weights ================================================ % We process the views in V sequentially. We center a 3x3 window on the % central view, and we compute the weights between the central view and the % other 8 views in the window (the neighboring views). % Compute the coordinates for the views in the window, with the current % view (the one that we are processing) in the middle, at (0,0). [S, T] = meshgrid((-1):1:1); S = S(:); T = T(:); % Remove the coordinate (0,0). mask = ((S == 0) & (T == 0)); S = S(~mask); T = T(~mask); % In the graph WA, each pixel in a view will have at most 2 connections to each % one of the 4 horizontal/vertical neighboring views, and at most 4 connections % to each one of the 4 diagonal neighboring views. At most 24 connections in total. weiA = zeros(N * 24 * M, 3); counterA = 0; % In graph WB, each pixel in a view will have at most 2 adjacent connections % to the 4 horizontal/vertical neighboring views, and the connections lie on % a (virtual) square, ideally defined by disparity. At most 8 connections in total. weiB = zeros(N * 8 * M, 3); counterB = 0; % Note that WB (like WA) is tiled with NxN matrices WBij that record the % connections between a pixel in view i (the rows of WBij) and a pixel in % view j (the columns of Wij). Normalizing the rows of matrix WBij, makes % it a warping matrix from view j to view i. % The total number of integer disparities. dispNum = (2 * dispMax) + 1; % dispScore(i,j) will contain the sum of the weights from the i-th pixel % of V{t,s} to the pixels of the neighboring views in the square associated % to disparity j. dispScore = zeros(N, dispNum); % dispScoreCounter(i,j) stores the number of weights that contributed to % dispScore(i,j), for normalization purposes. dispScoreCounter = zeros(N, dispNum); % Auxiliary linear array. auxLin = (1:1:N)'; % Start computing WA and WB ... for u = 1:1:M % The number of neighboring views. neigNum = length(S); % Initialize the cell array for the weights storage. % >>> Consider initializing each cell with a fixed size vector, and a counter !!! neigWei = cell(neigNum, 1); % Compute the coordinates of the view we are processing. [t, s] = ind2sub([vRes, hRes], u); % Compute WA connections from V{t,s} to its neighborhood, and the % square-constraint disparity ranges for the pixels in V{t,s}. for k = 1:1:neigNum % We want to compare views V{t,s} and V{tp,sp}. tp = t + T(k); sp = s + S(k); % Note that (tp,sp) cannot be (t,s), cause the pair (T(k),S(k)) % equal to (0,0) has been removed. % If (tp,sp) is a valid coordinate, then ... if (tp >= 1) && (tp <= vRes) && (sp >= 1) && (sp <= hRes) % Compute the linear coordinate of (tp,sp). up = sub2ind([vRes, hRes], tp, sp); % If V{tp,sp} is NOT a DIAGONAL neighboring view, then ... if ((tp == t) || (sp == s)) % Compute the searching window: a (1 x dispNum) window % for horizontal neighboring views, and (dispNum x 1) for % vertical ones. offset.X = (- sign(S(k))) * ((- dispMax):1:dispMax)'; offset.Y = (- sign(T(k))) * ((- dispMax):1:dispMax)'; % Note that a pixel of V{t,s} has a disparity d with reference % to the left view, but -d with reference to the right one. % Multiplication by -sign(S(k)) and -sign(T(k)) is made % necessary by this fact. % In WA each pixel has (at most) 2 connections to each % horizontal/vertical neighboring views. cntNum = 2; % otherwise ... else % Create a mask to select diagonals -1, 0, and 1. % mask = triu(ones(dispNum), -1) - triu(ones(dispNum), 2); % mask = logical(mask); mask = (ones(dispNum) ~= 0); % Compute the searching window: a diagonal window with the % shape defined by "mask". [X, Y] = meshgrid((- dispMax):1:dispMax); X = X(:); Y = Y(:); offset.X = (- sign(S(k))) * X(mask(:)); offset.Y = (- sign(T(k))) * Y(mask(:)); % In WA each pixel has 4 connections to each diagonal % neighboring view. cntNum = 4; end % Compute the weights between the two views. neigWei{k} = nlm(V{t, s}, V{tp, sp}, patRad, intSigma, offset); % Extract the cntNum best matches for each pixel in V{t,s} ... auxMax = reshape(neigWei{k}(:, 3), N, []); for z = 1:1:cntNum % Find the best (highest weight) connection for each pixel. [~, idx] = max(auxMax, [], 2); % Set to zero the found connections, in order to make them % no longer valid for selection at the next iteration. auxMax(sub2ind(size(auxMax), auxLin, idx)) = 0; % Extract the best connection for each pixel. auxWei = ... neigWei{k}( ... ((idx - 1) * N) + auxLin, ... : ... ); % Detect the non valid connections. These may be connections % to pixels outside the view support, or connections already % selected in a previous iteration. mask = (auxWei(:, 3) ~= 0); maskNum = sum(mask); % Store the best (and valid) connections in weiA. weiA((counterA + 1):(counterA + maskNum), :) = ... cat(2, ... ((u - 1) * N) + auxWei(mask, 1), ... ((up - 1) * N) + auxWei(mask, 2), ... auxWei(mask, 3) ... ); counterA = counterA + maskNum; end % If V{tp,sp} is NOT a DIAGONAL neighboring view, then ... if ((tp == t) || (sp == s)) % Update the square-constraint scores ... auxWei = reshape(neigWei{k}(:, 3), N, []); mask = (auxWei ~= 0); dispScore(mask) = dispScore(mask) + auxWei(mask); dispScoreCounter(mask) = dispScoreCounter(mask) + 1; end end end % Normalize the square-constraint scores. mask = (dispScoreCounter ~= 0); dispScore(mask) = dispScore(mask) ./ dispScoreCounter(mask); % Compute the square-constraint disparity range at each pixel. [idx1, idx2] = sqconstr(dispScore); % Resets dispScore and dispScoreCounter, for the view V{t,s} to % process at the next iteration. dispScore = dispScore * 0; dispScoreCounter = dispScoreCounter * 0; % Compute the warping matrix from V{t,s} to each view in its neighborhood ... for k = 1:1:neigNum % We want to build the warping matrix from V{tp,sp} to V{t,s}. tp = t + T(k); sp = s + S(k); % If view (tp,sp) is valid (hence neigWei{k} is not empty) and it % is NOT a DIAGONAL view, then ... if (~isempty(neigWei{k})) && ((tp == t) || (sp == s)) % Compute the linear coordinate of (tp,sp). up = sub2ind([vRes, hRes], tp, sp); % Extract the weights associated to idx1 for each pixel. aux1 = neigWei{k}( ... ((idx1 - 1) * N) + auxLin, ... : ... ); % Extract the weights associated to idx2 for each pixel. aux2 = neigWei{k}( ... ((idx2 - 1) * N) + auxLin, ... : ... ); % Normalize the (at most) 2 weights associated to each pixel. % auxNorm = (aux1(:, 3) + aux2(:, 3)); % mask = (auxNorm ~= 0); % aux1(mask, 3) = aux1(mask, 3) ./ auxNorm(mask); % aux2(mask, 3) = aux2(mask, 3) ./ auxNorm(mask); % Detect the non zero weights. mask1 = (aux1(:, 3) ~= 0); mask2 = (aux2(:, 3) ~= 0); % Compute the number of nonzero weights for each pixel. mask1Num = sum(mask1); mask2Num = sum(mask2); % Store the non zero weigths associated to idx1. weiB((counterB + 1):(counterB + mask1Num), :) = ... cat(2, ... ((u - 1) * N) + aux1(mask1, 1), ... ((up - 1) * N) + aux1(mask1, 2), ... aux1(mask1, 3) ... ); counterB = counterB + mask1Num; % Store the non-zero weights associated to idx2. weiB((counterB + 1):(counterB + mask2Num), :) = ... cat(2, ... ((u - 1) * N) + aux2(mask2, 1), ... ((up - 1) * N) + aux2(mask2, 2), ... aux2(mask2, 3) ... ); counterB = counterB + mask2Num; end end end % Remove empty cells. weiA(counterA:end, :) = []; weiB(counterB:end, :) = []; % Build WA. WA = sparse( ... weiA(:, 1), ... weiA(:, 2), ... weiA(:, 3), ... M * N, M * N ... ); % Build WB. WB = sparse( ... weiB(:, 1), ... weiB(:, 2), ... weiB(:, 3), ... M * N, M * N ... ); end function [idx1, idx2] = sqconstr(dispScore) dispNum = size(dispScore, 2); % dispMax = (dispNum - 1) / 2; [~, idx1] = max(dispScore, [], 2); % disp1 = idx1 - (dispMax + 1); idxLeft = max(1, idx1 - 1); idxRight = min(dispNum, idx1 + 1); maskLeft = (idxLeft == idx1); maskRight = (idxRight == idx1); auxLin = (1:1:length(idx1))'; left = sub2ind(size(dispScore), auxLin, idxLeft); right = sub2ind(size(dispScore), auxLin, idxRight); diff = dispScore(left) - dispScore(right); mask = (diff > 0); idx2 = zeros(size(idx1)); idx2(mask) = idxLeft(mask); idx2(~mask) = idxRight(~mask); idx2(maskLeft) = idxRight(maskLeft); idx2(maskRight) = idxLeft(maskRight); % disp2 = zeros(size(disp1)); % disp2(mask) = idxLeft(mask) - (dispMax + 1); % disp2(~mask) = idxRight(mask) - (dispMax + 1); % disp2(maskLeft) = idxRight(maskLeft) - (dispMax + 1); % disp2(maskRight) = idxLeft(maskRight) - (dispMax + 1); end
github
rossimattia/light-field-super-resolution-master
high2low.m
.m
light-field-super-resolution-master/high2low.m
3,181
utf_8
490ef4877ae6c00fe162f4635a9ebf22
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function [ZLR, ZHR] = high2low(Z, factor, sigmaNoise) % HIGH2LOW down-samples the light field views in Z by factor and adds % Gaussian random noise with standard deviation sigmaNoise. % % INPUT: % Z - the light field to down-sample. % factor - the down-sampling factor. % sigmaNoise - the Gaussian noise standard deviation. % % OUTPUT: % ZLR - the low resolution light field. % ZHR - the high resolution light field cropped such that its spatial % dimensions are multiple of the down-sampling factor. % % The output low resolution light field is to be considered the low resolution % version of the OUTPUT high resolution light field, and NOT of the INPUT % one, as only the output high resolution light field is properly cropped. % ==== Check the input type =============================================== if ~isa(lf2col(Z), 'uint8') error('Input light field must have uint8 views !!!\n\n'); end % ==== Ligth field parameters ============================================= % Angular resolution. vRes = size(Z, 1); hRes = size(Z, 2); % Spatial resolution. yRes = size(Z{1, 1}, 1); xRes = size(Z{1, 1}, 2); % Channels number (gray scale or RGB). channels = size(Z{1, 1}, 3); % ==== Crop Z ============================================================= % Each view of Z is cropped at the right and bottom sides, such that their % dimensions are multiples of factor. % Compute the LR dimensions of the views. yResLR = floor(yRes / factor); xResLR = floor(xRes / factor); % New spatial resolution. yResHR = factor * yResLR; xResHR = factor * xResLR; % Perform the cropping. ZHR = cell(vRes, hRes); for s = 1:1:hRes for t = 1:1:vRes ZHR{t, s} = Z{t, s}(1:yResHR, 1:xResHR, :); end end % ==== Blur and Decimate "ZHR" ========================================== % Blur matrix for a single view and channel. B = blurmat(yResHR, xResHR, factor); % Decimation matrix for a single view and channel. D = decimat(yResHR, xResHR, factor); % Blurring and decimation matrix for a single view and channel. DB = D * B; % Blurring and decimation matrix for a single view and ALL its channels. DBch = kron(speye(channels), DB); % ZLR will contain the Low Resolution (LR) views. ZLR = cell(vRes, hRes); % Number of pixels in each LR view. n = yResLR * xResLR * channels; % Blur, decimate, and add noise to each view, separately. for s = 1:1:hRes for t = 1:1:vRes auxLR = (DBch * double(ZHR{t, s}(:))) + (sigmaNoise * 255 * randn(n, 1)); auxLR = uint8(round(auxLR)); ZLR{t, s} = reshape( ... auxLR, ... yResLR, ... xResLR, ... channels ... ); end end end
github
rossimattia/light-field-super-resolution-master
readstf.m
.m
light-field-super-resolution-master/readstf.m
1,255
utf_8
424072ab3ada3cf18c345c9ac8d3ebbe
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function Z = readstf(path) % READSTF reads the STANFORD light field specified in the input folder and % it arranges it in a 2D cell array adopting the reference system described % in the README. % % INPUT: % path - the name of a folder containing the light field views. % % OUTPUT: % Z - a light field in the format described in the README. % ========================================================================= % Each STANFORD light field is a 16x16 grid of views. vRes = 17; hRes = 17; % Parametrized name of a view. str = [path, 'view_%02d_%02d.png']; % Read the views paying attention to STANFORD reference system. Z = cell(vRes, hRes); for t = 1:1:vRes for s = 1:1:hRes name = sprintf(str, vRes - t, s - 1); Z{t, s} = imread(name); end end end
github
rossimattia/light-field-super-resolution-master
warpmask.m
.m
light-field-super-resolution-master/warpmask.m
1,956
utf_8
d39b7a20045286a76b0866fc01e260b1
% ========================================================================= % ========================================================================= % % Author: % Mattia Rossi ([email protected]) % Signal Processing Laboratory 4 (LTS4) % Ecole Polytechnique Federale de Lausanne (Switzerland) % % ========================================================================= % ========================================================================= function H = warpmask(W, B, D, vRes, hRes) % WARPMASK computes the visibility masks for the warping. Let us assume that % the matrix W corresponds to the j-th view. Then W contains all the warping % matrices Wij (warping from the j-th view to the i-th one) stacked along % the second dimension, for all the views i in the light field. WARPMASK % computes a mask for each Wij and stores it in H{i}. The masks handle % exclusively the dis/occlusions caused by the view borders. % % INPUT: % W - a matrix containing the warping matrices (stacked along the second dimension) % from a given light field view to all the others. % B - the blur matrix for the whole light field. % D - the decimation matrix for the whole light field. % vRes - the light field vertical angular resolution. % hRes - the light field horizontal angular resolution. % % OUTPUT: % H - a 1D cell array containing a mask matrix in each cell. % ========================================================================= % Number of views. M = vRes * hRes; % Compute the warping mask (at Low Resolution) for all the warpings Wij. % The computed masks are in vectorized form. S = sum(W, 2); S = spones(S); S = D * B * S; S(S < 1) = 0; % Number of pixels at each LR view. NLR = size(D, 1) / M; % From the warping mask, create the corresponding diagonal matrices. H = cell(M, 1); for u = 1:1:M H{u} = spdiags( ... S((((u - 1) * NLR) + 1):(u * NLR)), ... 0, ... NLR, NLR ... ); end end
github
Stanford-STAGES/sleep-staging-master
load_signal.m
.m
sleep-staging-master/matlab_training_data_scripts/load_signal.m
6,256
utf_8
640c59c8395b2817463097637c5ad833
function c_sig = load_signal(filepath,fs) filepath hdr = loadHDR(filepath); ind = zeros(13,1); for i=1:13 try ind(i) = find(get_alternative_name(i,hdr.label)); end end test1 = (sum(ind([1 3]))==0 & (sum(ind([2 4]))==0 | sum(ind(9:10))==0)); test2 = (sum(ind([5 7]))==0 & (sum(ind([6 8]))==0 | sum(ind(9:10))==0)); test3 = prod(ind(11:13))==0; if any([test1 test2 test3]) c_sig = []; hdr.label disp('Wrong channels') return end loaded = ind~=0; [~,rec] = loadEDF(filepath,ind(loaded)); %% Re-reference if ind(2)~=0 if ind(9)~=0 rec{2-sum(~loaded(1:2-1))} = rec{2-sum(~loaded(1:2-1))} - rec{9-sum(~loaded(1:9-1))}; elseif ind(10) ~=0 rec{2-sum(~loaded(1:2-1))} = rec{2-sum(~loaded(1:2-1))} - rec{10-sum(~loaded(1:10-1))}; else rec(2-sum(~loaded(1:2-1))) = []; loaded(2) = 0; end end if ind(4)~=0 if ind(10)~=0 rec{4-sum(~loaded(1:4-1))} = rec{4-sum(~loaded(1:4-1))} - rec{10-sum(~loaded(1:10-1))}; elseif ind(9) ~=0 rec{4-sum(~loaded(1:4-1))} = rec{4-sum(~loaded(1:4-1))} - rec{9-sum(~loaded(1:9-1))}; else rec(4-sum(~loaded(1:4-1))) = []; loaded(4) = 0; end end if ind(6)~=0 if ind(9)~=0 rec{6-sum(~loaded(1:6-1))} = rec{6-sum(~loaded(1:6-1))} - rec{9-sum(~loaded(1:9-1))}; elseif ind(10) ~=0 rec{6-sum(~loaded(1:6-1))} = rec{6-sum(~loaded(1:6-1))} - rec{10-sum(~loaded(1:10-1))}; else rec(6-sum(~loaded(1:6-1))) = []; loaded(6) = 0; end end if ind(8)~=0 if ind(10)~=0 rec{8-sum(~loaded(1:8-1))} = rec{8-sum(~loaded(1:8-1))} - rec{10-sum(~loaded(1:10-1))}; elseif ind(10) ~=0 rec{8-sum(~loaded(1:8-1))} = rec{8-sum(~loaded(1:8-1))} - rec{9-sum(~loaded(1:9-1))}; else rec(8-sum(~loaded(1:8-1))) = []; loaded(8) = 0; end end if ind(9)~=0 rec{9-sum(~loaded(1:9-1))} = []; end if ind(10)~=0 rec{10-sum(~loaded(1:10-1))} = []; end rec(cellfun(@isempty,rec)) = []; loaded(9:10) = 0; %% sig = cell(sum(loaded),1); cFs = hdr.fs(ind(loaded)); for i = 1:length(rec) ind = find(isnan(rec{i})|isinf(rec{i})); rec{i}(ind) = 0; SRC = dsp.SampleRateConverter('Bandwidth',50,'InputSampleRate',cFs(i),... 'OutputSampleRate',fs,'StopbandAttenuation',30); sig{i} = SRC.step(rec{i}); sig{i} = sig{i}(1:length(sig{i})-rem(length(sig{i}),fs*30)); end noise = get_noise(sig,fs,loaded); c_noise = Inf(13,1); c_noise(loaded) = noise; c_sig = cell(13,1); c_sig(loaded) = sig; rem1 = 1:4; [~,eegRem1] = min(c_noise(1:4)); rem1(eegRem1) = []; rem2 = 5:8; [~,eegRem2] = min(c_noise(5:8)); rem2(eegRem2) = []; c_sig([rem1,rem2]) = []; c_sig(3:4) = []; end function synonym = get_alternative_name(ch,labels) dict{1} = {'C3M2','C3-M2','C3-A2','C3A1','C3A2','C3M','C3-A1','C3-M1',... 'EEG C3-A2','C3/A2','C3_A2','C3-x','C3x','C3'}; dict{2} = {'C3','EEG C3'}; dict{3} = {'C4M1','C4-M1','C4-A1','C4A1','C4M','C4-A2','C4-M1','EEG C4-A1','C4/A1','C4_A1','C4x','C4-x','C4'}; dict{4} = {'C4','EEG C4'}; dict{5} = {'O1M2','O1-M2','O1M2','O1-A2',... 'O1A2','O1M','O1A2','O1AVG','O1-M2','O1-A2','O1-M1','EEG O1-A2','O1/A2','O1_A2','O1-x','O1x','O1'}; dict{6} = {'O1','EEG O1'}; dict{7} = {'O2M1','O2-M1','O2M1','O2-A1',... 'O2A1','O2M','O2A1','O2AVG','O2-M1','O2-A2','O2-M2','EEG O2-A1','O2_A1','O2-x','O2x','O2'}; dict{8} = {'O2','EEG O2'}; dict{9} = {'A2','M2','EEG M2'}; dict{10} = {'A1','M1','EEG M1','A1/A2'}; dict{11} = {'LEOG','LEOG-M2','','LEOGx','LOCA2','LEOGM2','LEOC-x','LOC','LOC-A2',... 'L-EOG','EOG-L','EOG Left','Lt.','LOC-Cz','LOCA2','LEOG-x','Lt. Eye (E1)','EOG Au-hor-L','EOG Au-hor','EOG Au-li',... 'EOG EOG L','LOC-x','EOG_L'}; dict{12} = {'REOG','REOG-M1','REOGx','ROCA1','ROCM1','REOGM1','REOC-x','ROC-M1',... 'ROC','ROC-A1','R-EOG','EOG-R','EOG Right','Rt.','ROC-Cz','ROCA2','REOG-x','ROC-A2','Rt. Eye (E2)','EOG Au-hor-R',... 'Unspec Auhor','EOG Au_re','EOG EOG R','Unspec Au-hor#2','EOG Au-hor#2','ROC-x','EOG_R'}; dict{13} = {'Chin1Chin2','Chin1-Chin2','Chin EMG','Chin','CHIN EMG','Subm','Chin_L',... 'Chin_R','CHINEMG','ChinCtr','ChinL','ChinR','Chin2EMG','ChinEMG','Chin-L',... 'Chin-Ctr','Chin-R','EMG EMG Chin','EMG1-EMG2','EMG Ment1','EMG Ment2','EMG Ment3','Unspec subment',... 'EMG Chin1','EMG Chin2','EMG Chin3','EMG_SM'}; for d = dict{ch} synonym = strcmp(d,labels); if sum(synonym)>0 break end end end function hjorth = extract_hjort(fs,dim,slide,input) %Length of first dimension dim = dim*fs; %Specify overlap of segments in samples slide = slide*fs; %Creates 2D array of overlapping segments D = buffer(input,dim,dim-slide,'nodelay'); D(:,end) = []; %Extract Hjorth for each segment dD = diff(D,1); ddD = diff(dD,1); mD2 = mean(D.^2); mdD2 = mean(dD.^2); mddD2 = mean(ddD.^2); top = sqrt(mddD2 ./ mdD2); mobility = sqrt(mdD2 ./ mD2); activity = mD2; complexity = top./mobility; hjorth = [activity;complexity;mobility]; [~,b] = find(isnan(hjorth)); hjorth(:,unique(b)) = 0; hjorth = log(hjorth+eps); end function noise = get_noise(channels,fs,loaded) load('noiseM.mat') noise = zeros(length(channels),1); dist = [1 1 1 1 2 2 2 2 0 0 3 4 5]; dist = dist(loaded); for i=1:length(channels) M = extract_hjort(fs,5*60,5*60,channels{i}); M = num2cell(M,1); noise(i) = mean(cellfun(@(x) sqrt((x-noiseM.meanV{dist(i)})'*(noiseM.covM{dist(i)})^-1*(x-noiseM.meanV{dist(i)})),M)); end end
github
iamsakil/BoundaryTrackingMATLAB-master
boundarytrack.m
.m
BoundaryTrackingMATLAB-master/boundarytrack.m
1,577
utf_8
c9d676fc728fd87e3a9580a25b5d30f5
% r,c = positions of boundary % H,W = image height and width % figN = figure number for result display (0 for no display) % [tr,tc] = consecutive set of tracked boundary points function [tr,tc] = boundarytrack(r,c,H,W,figN) % next direction offsets % 1 2 3 % 8 x 4 % 7 6 5 mr = [-1,-1,-1,0,1,1,1,0]; mc = [-1,0,1,1,1,0,-1,-1]; % set up visited array (keep track of where we have already tracked) n = length(r); visited=zeros(H,W); for i = 1 : n visited(r(i),c(i)) = 1; end % set up tracked output tmpr = zeros(n,1); tmpc = zeros(n,1); count = 1; tmpr(1) = r(1); tmpc(1) = c(1); visited(tmpr(count),tmpc(count)) = 0; % find first connected point clockwise lastdir = 1; % arbitrary start notdone = 1; while notdone % find next untracked point notdone = 0; for i = 1 : 8 % try all 8 directions nextdir = lastdir + 4 + i; % get next direction to try while nextdir > 8 nextdir = nextdir - 8; end % see if nextdir is a boundary point nr = tmpr(count)+mr(nextdir); nc = tmpc(count)+mc(nextdir); if visited(nr,nc) == 1 % it is a boundary point, so track to it lastdir = nextdir; notdone = 1; count = count + 1; tmpr(count) = nr; tmpc(count) = nc; visited(nr,nc) = 0; break end end end tr = tmpr(1:count); tc = tmpc(1:count); % display result - ? if figN > 0 figure(figN) plot(tc,tr) axis([0,W,0,H]) axis ij end
github
teenagerold/FPGA_SDR-mars-board-master
mnco_model.m
.m
FPGA_SDR-mars-board-master/SDRrceeiver/mnco_model.m
1,345
utf_8
837483ceb2c31f737ddeeaae252ed98c
% Altera NCO version 13.1 % function [s,c] = mnco_model(phi_inc_i,phase_mod_i,freq_mod_i) % input : phi_inc_i : phase increment input (required) % phase_mod_i : phase modulation input(optional) % freq_mod_i : frequency modulation input(optional) % output : s : sine wave output % c : cosine wave output function [s,c] = mnco_model(phi_inc_i,phase_mod_i,freq_mod_i) addpath d:/software/quartus/ip/altera/nco/lib/ip_toolbench/../; if(nargin==0) fprintf('Error using mnco_model : Not enough input arguments\n'); else N=length(phi_inc_i); end if(nargin==1) phase_mod_i=zeros(1,N); freq_mod_i=zeros(1,N); elseif(nargin==2) if(length(phase_mod_i)~=N) fprintf('Error using mnco_model : input vector length mismatch\n'); else freq_mod_i=zeros(1,N); end elseif(nargin==3) if((length(phase_mod_i)~=N)|length(freq_mod_i)~=N) fprintf('Error using mnco_model : input vector length mismatch\n'); end else fprintf('Error using mnco_model : Incorrect number of input arguments\n'); end N=length(phi_inc_i); numch = 1.0; apr = 32.0; apri = 10.0; mpr = 10.0; aprp = 16.0; aprf = 32.0; dpri = 5.0; arch = 3.0; wantFmod = 0.0; wantPmod = 0.0; dual = 1.0; [s,c] = Sncomodel(phi_inc_i,phase_mod_i,freq_mod_i,wantFmod,wantPmod,numch,apr,mpr,apri,aprp,aprf,dpri,arch,dual,N);
github
teenagerold/FPGA_SDR-mars-board-master
mcic_fir_comp_coeff.m
.m
FPGA_SDR-mars-board-master/SDRrceeiver/mcic_fir_comp_coeff.m
8,343
utf_8
b1c5d49a50e23e4a249456c06af998c4
%% ================================================================================ %% Legal Notice: Copyright (C) 1991-2008 Altera Corporation %% Any megafunction design, and related net list (encrypted or decrypted), %% support information, device programming or simulation file, and any other %% associated documentation or information provided by Altera or a partner %% under Altera's Megafunction Partnership Program may be used only to %% program PLD devices (but not masked PLD devices) from Altera. Any other %% use of such megafunction design, net list, support information, device %% programming or simulation file, or any other related documentation or %% information is prohibited for any other purpose, including, but not %% limited to modification, reverse engineering, de-compiling, or use with %% any other silicon devices, unless such use is explicitly licensed under %% a separate agreement with Altera or a megafunction partner. Title to %% the intellectual property, including patents, copyrights, trademarks, %% trade secrets, or maskworks, embodied in any such megafunction design, %% net list, support information, device programming or simulation file, or %% any other related documentation or information provided by Altera or a %% megafunction partner, remains with Altera, the megafunction partner, or %% their respective licensors. No other licenses, including any licenses %% needed under any third party's intellectual property, are provided herein. %% ================================================================================ %% %% Generated by: CIC 13.1 Build 162 October, 2013 %% Generated on: 2017-9-1 21:04:42 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % mcic_fir_comp_coeff genearats CIC compensation filter coefficients % using frequency sampling method. % % mcic_fir_comp_coeff(L, Fs, Fc, plot, is_fxp, B) calculates compensation % filter coefficients and saves the coefficients to a file. % % L - FIR filter length (= number of taps = number of coefficients) % Fs - FIR filter sample rate in Hz before decimation % Fc - FIR filter cutoff frequency in Hz % plot - True or false to draw filter responses graphically % is_fxp - Indicating if the coefficients should be saved as fixed point or floating point numbers % B - Number of bits to represent the coefficients if is_fxp is true % % Examples: % mcic_fir_comp_coeff(31,80e6,4e6,true,true,16); % mcic_fir_comp_coeff(31,80e6,4e6,true,false) function mcic_fir_comp_coeff(L, Fs, Fc, plot, is_fxp, B) try % Validate number of input arguments error(nargchk(0, 6, nargin)); %%%%%% CIC filter parameters %%%%%% R = 200; %% Decimation factor M = 2; %% Differential Delay N = 5; %% Number of Stages %%%%%% User Parameters %%%%%% % Check if Signal Processing Toolbox is in the Matlab installation if (isempty(which('fir2'))) error('Matlab Signal Processing Toolbox isn''t installed on your machine. Please contact Altera for help.'); end %% Get user parameters: B, L, Fs, Fc if they aren't passed as arguments. if(nargin < 1) %% Filter length: it must be an odd number, otherwise it'll be increased by 1. L = input('Number of filter coefficients (31 as default): '); if isempty(L) L = 31; end end if mod(L,2) == 0 fprintf('FIR filter length must be an odd number. %d is used instead.\n',L+1); L = L+1; end if(nargin < 2) %% FIR filter sample rate in Hz before decimation Fs = input('FIR filter sample rate in Hz before decimation (80e6 as default): '); if isempty(Fs) Fs = 80e6; end end if(nargin < 3) %% FIR filter cutoff frequency in Hz Fc = input('FIR filter cutoff frequency in Hz (4e6 as default): '); if isempty(Fc) Fc = 4e6; end end if (nargin < 4) plot_res = input('Do you want to plot filter responses? Y/N [N]:','s'); if isempty(plot_res) plot_res = 'N'; end if upper(plot_res) == 'Y' plot = true; else plot = false; end end if(nargin < 5) fxp_coeff = input('Do you want to write out coefficients as fixed point numbers? Y/N [Y]:','s'); if isempty(fxp_coeff) fxp_coeff = 'Y'; end if upper(fxp_coeff) == 'Y' is_fxp = true; else is_fxp = false; end end if(is_fxp && nargin < 6) %% Number of bits to represent fixed point filter coefficients B = input('Number of bits to represent the filter coefficients (16 as default): '); if isempty(B) B = 16; end end Fo = R*Fc/Fs; %% Normalized Cutoff freq; 0<Fo<=0.5/M; %% Fo should be less than 1/(4M) for good performance % Fo = 0.5/M; %% use Fo=0.5 if we don't care responses outside passband %%%%%%% CIC Compensator Design using fir2.m %%%%%% p = 2e3; %% Granulatiry s = 0.25/p; %% Stepsize fp = [0:s:Fo]; %% Passband frequency samples fs = (Fo+s):s:0.5; %% Stopband frequency samples f = [fp fs]*2; %% Noramlized frequency samples; 0<=f<=1; Mp = ones(1,length(fp)); %% Passband response; Mp(1)=1 Mp(2:end) = abs( M*R*sin(pi*fp(2:end)/R)./sin(pi*M*fp(2:end))).^N; %% Inverse sinc Mf = [Mp zeros(1,length(fs))]; f(end) = 1; h = fir2(L-1,f,Mf); %% Filter order = filter length (L) - 1 h = h/max(h); %% Floating point coefficients, scaled it to 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Output filter coefficients to a file for Altera FIR Compiler % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% filename = 'mcic_fir_comp_coeff.txt'; fid = fopen(filename, 'wt'); if (fid == -1) errMsg = sprintf('Can''t Open file %s for writing.\n', FileName); error(errMsg); end; if (is_fxp) % coefficients are fixed point hz = fix(h*(2^(B-1)-1)); %% Quantization of filter coefficients fprintf(fid, '%d\n', hz); %% fixed point coeff else fprintf(fid, '%.6f\n',h); %% floating point end fclose(fid); fprintf('The compensation filter coefficients have been saved to file ''%s''.\n',filename); % Change the following variable to 1 if you would like to plot the filter responses if (plot) if (is_fxp) plot_responses(R,M,N,hz,Fs,is_fxp); else plot_responses(R,M,N,h,Fs,is_fxp); end end; catch rethrow(lasterror); end; %% Function for ploting filter responses function plot_responses(R,M,N,res,Fs,is_fxp) try %%%%%%% Full resolution CIC filter response %%%%%%%% hrec = ones(1,R*M); tmph = hrec; for k=1:N-1 tmph = conv(hrec, tmph); end; hcic = tmph; hcic = hcic/max(hcic); %%%%%%% Total Response %%%%%%%%%%%%%%% resp = upsample(res, R); ht = conv(hcic, resp); %% Concatenation of CIC and fir2 FIR at high freqency no_data_points = 4096; %% Number of data points to plot in the figure [Hcic, wt] = freqz(hcic, 1, no_data_points, Fs); %% CIC Freq. Response [Hciccomp, wt] = freqz(resp, 1, no_data_points, Fs); %% CIC Comp. response using fir2 [Ht, wt] = freqz(ht, 1, no_data_points, Fs); %% Total response for CIC + Compensation fir2 warning off all; %% Turn the 'Log by zero' warning off Mcic = 20*log10(abs(Hcic)/(abs(Hcic(1)))); %% CIC Freq. Response Mciccomp = 20*log10(abs(Hciccomp)/(abs(Hciccomp(1))));%% CIC Comp. response using fir2 Mt = 20*log10(abs(Ht)/(abs(Ht(1)))); %% Total response for CIC + Compensation fir2 warning on; %% Turn warnings on figure; plot(wt, Mcic, wt, Mciccomp, wt, Mt); if (is_fxp) % coefficients are fixed point legend('CIC','CIC Comp','Total Response (Fixed Point)'); else % floating point legend('CIC','CIC Comp','Total Response (Floating Point)'); end ymax = max(Mciccomp)+1; ylim([-100 ymax]); title('CIC and its Compensation Filter Responses'); grid; xlabel('Frequency Hz'); ylabel('Filter Magnitude Response dB'); catch rethrow(lasterror); end;
github
matthewberger/tfgan-master
fast_tsne.m
.m
tfgan-master/renderer/bh_tsne/fast_tsne.m
4,820
utf_8
ea635b52c1f372c46c31b2b389a87b27
function mappedX = fast_tsne(X, no_dims, initial_dims, perplexity, theta) %FAST_TSNE Runs the C++ implementation of Barnes-Hut t-SNE % % mappedX = fast_tsne(X, no_dims, initial_dims, perplexity, theta) % % Runs the C++ implementation of Barnes-Hut-SNE. The high-dimensional % datapoints are specified in the NxD matrix X. The dimensionality of the % datapoints is reduced to initial_dims dimensions using PCA (default = 50) % before t-SNE is performed. Next, t-SNE reduces the points to no_dims % dimensions. The perplexity of the input similarities may be specified % through the perplexity variable (default = 30). The variable theta sets % the trade-off parameter between speed and accuracy: theta = 0 corresponds % to standard, slow t-SNE, while theta = 1 makes very crude approximations. % Appropriate values for theta are between 0.1 and 0.7 (default = 0.5). % The function returns the two-dimensional data points in mappedX. % % NOTE: The function is designed to run on large (N > 5000) data sets. It % may give poor performance on very small data sets (it is better to use a % standard t-SNE implementation on such data). % Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are met: % 1. Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % 2. Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in the % documentation and/or other materials provided with the distribution. % 3. All advertising materials mentioning features or use of this software % must display the following acknowledgement: % This product includes software developed by the Delft University of Technology. % 4. Neither the name of the Delft University of Technology nor the names of % its contributors may be used to endorse or promote products derived from % this software without specific prior written permission. % % THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS % OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES % OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO % EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, % SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, % PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR % BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING % IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY % OF SUCH DAMAGE. if ~exist('no_dims', 'var') || isempty(no_dims) no_dims = 2; end if ~exist('initial_dims', 'var') || isempty(initial_dims) initial_dims = 50; end if ~exist('perplexity', 'var') || isempty(perplexity) perplexity = 30; end if ~exist('theta', 'var') || isempty(theta) theta = 0.5; end % Perform the initial dimensionality reduction using PCA X = double(X); X = bsxfun(@minus, X, mean(X, 1)); covX = X' * X; [M, lambda] = eig(covX); [~, ind] = sort(diag(lambda), 'descend'); if initial_dims > size(M, 2) initial_dims = size(M, 2); end M = M(:,ind(1:initial_dims)); X = X * M; clear covX M lambda % Run the fast diffusion SNE implementation write_data(X, no_dims, theta, perplexity); tic, system('./bh_tsne'); toc [mappedX, landmarks, costs] = read_data; landmarks = landmarks + 1; % correct for Matlab indexing delete('data.dat'); delete('result.dat'); end % Writes the datafile for the fast t-SNE implementation function write_data(X, no_dims, theta, perplexity) [n, d] = size(X); h = fopen('data.dat', 'wb'); fwrite(h, n, 'integer*4'); fwrite(h, d, 'integer*4'); fwrite(h, theta, 'double'); fwrite(h, perplexity, 'double'); fwrite(h, no_dims, 'integer*4'); fwrite(h, X', 'double'); fclose(h); end % Reads the result file from the fast t-SNE implementation function [X, landmarks, costs] = read_data h = fopen('result.dat', 'rb'); n = fread(h, 1, 'integer*4'); d = fread(h, 1, 'integer*4'); X = fread(h, n * d, 'double'); landmarks = fread(h, n, 'integer*4'); costs = fread(h, n, 'double'); % this vector contains only zeros X = reshape(X, [d n])'; fclose(h); end
github
frederikgeth/PowerModelsReliability.jl-master
case118_scopf.m
.m
PowerModelsReliability.jl-master/test/data/case118_scopf.m
58,773
utf_8
61213536e0c5fd662c0fc60e57414d54
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% %%%%% %%%% NICTA Energy System Test Case Archive (NESTA) - v0.6.1 %%%%% %%%% Optimal Power Flow - Typical Operation %%%%% %%%% 26 - November - 2016 %%%%% %%%% %%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Power flow data for IEEE 118 bus test case. % Please see CASEFORMAT for details on the case file format. % (ieee118cdf.txt) on 20-Sep-2004 by cdf2matp, rev. 1.11 % % Converted from IEEE CDF file from: % http://www.ee.washington.edu/research/pstca/ % % With base_kV data take from the PSAP format file from the same site, % added manually on 10-Mar-2006. % % CDF Header: % 08/25/93 UW ARCHIVE 100.0 1961 W IEEE 118 Bus Test Case % function mpc = case118_scopf mpc.version = '2'; mpc.baseMVA = 100.0; %% bus data % bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin mpc.bus = [ 1 2 51.0 27.0 0.0 0.0 1 1.03313 -32.79829 138.0 1 1.06000 0.94000; 2 1 20.0 9.0 0.0 0.0 1 1.04476 -31.43391 138.0 1 1.06000 0.94000; 3 1 39.0 10.0 0.0 0.0 1 1.03885 -32.29547 138.0 1 1.06000 0.94000; 4 2 39.0 12.0 0.0 0.0 1 1.05719 -30.64013 138.0 1 1.06000 0.94000; 5 1 0.0 0.0 0.0 -40.0 1 1.05562 -30.42957 138.0 1 1.06000 0.94000; 6 2 52.0 22.0 0.0 0.0 1 1.05524 -31.14479 138.0 1 1.06000 0.94000; 7 1 19.0 2.0 0.0 0.0 1 1.05615 -30.84911 138.0 1 1.06000 0.94000; 8 2 28.0 0.0 0.0 0.0 1 1.04474 -28.85812 345.0 1 1.06000 0.94000; 9 1 0.0 0.0 0.0 0.0 1 1.06000 -28.92750 345.0 1 1.06000 0.94000; 10 2 0.0 0.0 0.0 0.0 1 1.03529 -28.82050 345.0 1 1.06000 0.94000; 11 1 70.0 23.0 0.0 0.0 1 1.05162 -30.76612 138.0 1 1.06000 0.94000; 12 2 47.0 10.0 0.0 0.0 1 1.05999 -30.04186 138.0 1 1.06000 0.94000; 13 1 34.0 16.0 0.0 0.0 1 1.03910 -31.57015 138.0 1 1.06000 0.94000; 14 1 14.0 1.0 0.0 0.0 1 1.05645 -30.51913 138.0 1 1.06000 0.94000; 15 2 90.0 30.0 0.0 0.0 1 1.04944 -30.35121 138.0 1 1.06000 0.94000; 16 1 25.0 10.0 0.0 0.0 1 1.05302 -30.17322 138.0 1 1.06000 0.94000; 17 1 11.0 3.0 0.0 0.0 1 1.06000 -28.29202 138.0 1 1.06000 0.94000; 18 2 60.0 34.0 0.0 0.0 1 1.05264 -30.09584 138.0 1 1.06000 0.94000; 19 2 45.0 25.0 0.0 0.0 1 1.04789 -30.27721 138.0 1 1.06000 0.94000; 20 1 18.0 3.0 0.0 0.0 1 1.03471 -28.79835 138.0 1 1.06000 0.94000; 21 1 14.0 8.0 0.0 0.0 1 1.02936 -26.88590 138.0 1 1.06000 0.94000; 22 1 10.0 5.0 0.0 0.0 1 1.03326 -24.02807 138.0 1 1.06000 0.94000; 23 1 7.0 3.0 0.0 0.0 1 1.05205 -18.62826 138.0 1 1.06000 0.94000; 24 2 13.0 0.0 0.0 0.0 1 1.05682 -17.50102 138.0 1 1.06000 0.94000; 25 2 0.0 0.0 0.0 0.0 1 1.06000 -12.69922 138.0 1 1.06000 0.94000; 26 2 0.0 0.0 0.0 0.0 1 1.02524 -12.31737 345.0 1 1.06000 0.94000; 27 2 71.0 13.0 0.0 0.0 1 1.04142 -25.04041 138.0 1 1.06000 0.94000; 28 1 17.0 7.0 0.0 0.0 1 1.03325 -26.56574 138.0 1 1.06000 0.94000; 29 1 24.0 4.0 0.0 0.0 1 1.03199 -27.45759 138.0 1 1.06000 0.94000; 30 1 0.0 0.0 0.0 0.0 1 1.02883 -24.89177 345.0 1 1.06000 0.94000; 31 2 43.0 27.0 0.0 0.0 1 1.03444 -27.36116 138.0 1 1.06000 0.94000; 32 2 59.0 23.0 0.0 0.0 1 1.04234 -25.60297 138.0 1 1.06000 0.94000; 33 1 23.0 9.0 0.0 0.0 1 1.04644 -29.73962 138.0 1 1.06000 0.94000; 34 2 59.0 26.0 0.0 14.0 1 1.05777 -27.93122 138.0 1 1.06000 0.94000; 35 1 33.0 9.0 0.0 0.0 1 1.05520 -28.33563 138.0 1 1.06000 0.94000; 36 2 31.0 17.0 0.0 0.0 1 1.05573 -28.34858 138.0 1 1.06000 0.94000; 37 1 0.0 0.0 0.0 -25.0 1 1.06000 -27.47810 138.0 1 1.06000 0.94000; 38 1 0.0 0.0 0.0 0.0 1 1.00989 -23.11262 345.0 1 1.06000 0.94000; 39 1 27.0 11.0 0.0 0.0 1 1.03411 -29.53573 138.0 1 1.06000 0.94000; 40 2 66.0 23.0 0.0 0.0 1 1.02963 -29.95140 138.0 1 1.06000 0.94000; 41 1 37.0 10.0 0.0 0.0 1 1.01757 -29.83569 138.0 1 1.06000 0.94000; 42 2 96.0 23.0 0.0 0.0 1 1.01043 -26.88647 138.0 1 1.06000 0.94000; 43 1 18.0 7.0 0.0 0.0 1 1.02843 -26.31390 138.0 1 1.06000 0.94000; 44 1 16.0 8.0 0.0 10.0 1 1.00429 -21.41768 138.0 1 1.06000 0.94000; 45 1 53.0 22.0 0.0 10.0 1 0.99592 -18.65546 138.0 1 1.06000 0.94000; 46 2 28.0 10.0 0.0 10.0 1 1.01212 -15.50406 138.0 1 1.06000 0.94000; 47 1 34.0 0.0 0.0 0.0 1 1.01972 -11.98215 138.0 1 1.06000 0.94000; 48 1 20.0 11.0 0.0 15.0 1 1.02043 -13.08165 138.0 1 1.06000 0.94000; 49 2 87.0 30.0 0.0 0.0 1 1.02323 -11.80917 138.0 1 1.06000 0.94000; 50 1 17.0 4.0 0.0 0.0 1 1.01133 -15.01813 138.0 1 1.06000 0.94000; 51 1 17.0 8.0 0.0 0.0 1 0.99379 -19.02717 138.0 1 1.06000 0.94000; 52 1 18.0 5.0 0.0 0.0 1 0.98829 -20.33167 138.0 1 1.06000 0.94000; 53 1 23.0 11.0 0.0 0.0 1 0.99145 -22.26595 138.0 1 1.06000 0.94000; 54 2 113.0 32.0 0.0 0.0 1 1.01028 -22.16971 138.0 1 1.06000 0.94000; 55 2 63.0 22.0 0.0 0.0 1 1.01049 -22.53067 138.0 1 1.06000 0.94000; 56 2 84.0 18.0 0.0 0.0 1 1.00978 -22.23337 138.0 1 1.06000 0.94000; 57 1 12.0 3.0 0.0 0.0 1 1.00607 -19.58747 138.0 1 1.06000 0.94000; 58 1 12.0 3.0 0.0 0.0 1 0.99809 -20.68386 138.0 1 1.06000 0.94000; 59 2 277.0 113.0 0.0 0.0 1 1.04823 -20.01733 138.0 1 1.06000 0.94000; 60 1 78.0 3.0 0.0 0.0 1 1.05498 -15.19733 138.0 1 1.06000 0.94000; 61 2 0.0 0.0 0.0 0.0 1 1.06000 -14.58431 138.0 1 1.06000 0.94000; 62 2 77.0 14.0 0.0 0.0 1 1.04635 -13.62156 138.0 1 1.06000 0.94000; 63 1 0.0 0.0 0.0 0.0 1 1.01792 -15.38992 345.0 1 1.06000 0.94000; 64 1 0.0 0.0 0.0 0.0 1 1.02901 -12.87730 345.0 1 1.06000 0.94000; 65 2 0.0 0.0 0.0 0.0 1 1.02987 -6.98042 345.0 1 1.06000 0.94000; 66 2 39.0 18.0 0.0 0.0 1 1.06000 -2.98216 138.0 1 1.06000 0.94000; 67 1 28.0 7.0 0.0 0.0 1 1.04383 -8.66117 138.0 1 1.06000 0.94000; 68 1 0.0 0.0 0.0 0.0 1 1.02062 -5.69946 345.0 1 1.06000 0.94000; 69 3 0.0 0.0 0.0 0.0 1 1.06000 0.00000 138.0 1 1.06000 0.94000; 70 2 66.0 20.0 0.0 0.0 1 1.03170 -10.14942 138.0 1 1.06000 0.94000; 71 1 0.0 0.0 0.0 0.0 1 1.03547 -11.05503 138.0 1 1.06000 0.94000; 72 2 12.0 0.0 0.0 0.0 1 1.04425 -14.80433 138.0 1 1.06000 0.94000; 73 2 6.0 0.0 0.0 0.0 1 1.03745 -11.22651 138.0 1 1.06000 0.94000; 74 2 68.0 27.0 0.0 12.0 1 1.01048 -10.62644 138.0 1 1.06000 0.94000; 75 1 47.0 11.0 0.0 0.0 1 1.01395 -9.25550 138.0 1 1.06000 0.94000; 76 2 68.0 36.0 0.0 0.0 1 0.99960 -10.91934 138.0 1 1.06000 0.94000; 77 2 61.0 28.0 0.0 0.0 1 1.04410 -6.87285 138.0 1 1.06000 0.94000; 78 1 71.0 26.0 0.0 0.0 1 1.03970 -7.20945 138.0 1 1.06000 0.94000; 79 1 39.0 32.0 0.0 20.0 1 1.04174 -7.04886 138.0 1 1.06000 0.94000; 80 2 130.0 26.0 0.0 0.0 1 1.06000 -5.24129 138.0 1 1.06000 0.94000; 81 1 0.0 0.0 0.0 0.0 1 1.01451 -5.50728 345.0 1 1.06000 0.94000; 82 1 54.0 27.0 0.0 20.0 1 1.03483 -7.93386 138.0 1 1.06000 0.94000; 83 1 20.0 10.0 0.0 10.0 1 1.03737 -7.34853 138.0 1 1.06000 0.94000; 84 1 11.0 7.0 0.0 0.0 1 1.04085 -5.87420 138.0 1 1.06000 0.94000; 85 2 24.0 15.0 0.0 0.0 1 1.04907 -4.87492 138.0 1 1.06000 0.94000; 86 1 21.0 10.0 0.0 0.0 1 1.04208 -6.23523 138.0 1 1.06000 0.94000; 87 2 0.0 0.0 0.0 0.0 1 1.05481 -6.33068 161.0 1 1.06000 0.94000; 88 1 48.0 10.0 0.0 0.0 1 1.04735 -2.48518 138.0 1 1.06000 0.94000; 89 2 0.0 0.0 0.0 0.0 1 1.06000 0.87743 138.0 1 1.06000 0.94000; 90 2 163.0 42.0 0.0 0.0 1 1.05126 -4.87373 138.0 1 1.06000 0.94000; 91 2 10.0 0.0 0.0 0.0 1 1.04436 -4.73340 138.0 1 1.06000 0.94000; 92 2 65.0 10.0 0.0 0.0 1 1.04495 -3.97188 138.0 1 1.06000 0.94000; 93 1 12.0 7.0 0.0 0.0 1 1.03499 -6.20851 138.0 1 1.06000 0.94000; 94 1 30.0 16.0 0.0 0.0 1 1.03344 -7.74757 138.0 1 1.06000 0.94000; 95 1 42.0 31.0 0.0 0.0 1 1.02300 -8.24044 138.0 1 1.06000 0.94000; 96 1 38.0 15.0 0.0 0.0 1 1.03266 -7.88686 138.0 1 1.06000 0.94000; 97 1 15.0 9.0 0.0 0.0 1 1.04162 -6.91133 138.0 1 1.06000 0.94000; 98 1 34.0 8.0 0.0 0.0 1 1.04955 -7.70927 138.0 1 1.06000 0.94000; 99 2 42.0 0.0 0.0 0.0 1 1.05160 -9.04319 138.0 1 1.06000 0.94000; 100 2 37.0 18.0 0.0 0.0 1 1.05328 -8.74860 138.0 1 1.06000 0.94000; 101 1 22.0 15.0 0.0 0.0 1 1.03690 -7.50844 138.0 1 1.06000 0.94000; 102 1 5.0 3.0 0.0 0.0 1 1.04121 -5.23894 138.0 1 1.06000 0.94000; 103 2 23.0 16.0 0.0 0.0 1 1.05037 -11.59117 138.0 1 1.06000 0.94000; 104 2 38.0 25.0 0.0 0.0 1 1.03709 -14.87455 138.0 1 1.06000 0.94000; 105 2 31.0 26.0 0.0 20.0 1 1.03457 -16.04051 138.0 1 1.06000 0.94000; 106 1 43.0 16.0 0.0 0.0 1 1.02649 -16.17588 138.0 1 1.06000 0.94000; 107 2 50.0 12.0 0.0 6.0 1 1.02208 -18.68691 138.0 1 1.06000 0.94000; 108 1 2.0 1.0 0.0 0.0 1 1.02796 -17.58242 138.0 1 1.06000 0.94000; 109 1 8.0 3.0 0.0 0.0 1 1.02564 -18.18553 138.0 1 1.06000 0.94000; 110 2 39.0 30.0 0.0 6.0 1 1.02320 -19.47936 138.0 1 1.06000 0.94000; 111 2 0.0 0.0 0.0 0.0 1 1.02631 -19.53009 138.0 1 1.06000 0.94000; 112 2 68.0 13.0 0.0 0.0 1 1.00975 -21.98346 138.0 1 1.06000 0.94000; 113 2 6.0 0.0 0.0 0.0 1 1.05698 -28.02777 138.0 1 1.06000 0.94000; 114 1 8.0 3.0 0.0 0.0 1 1.03742 -25.85113 138.0 1 1.06000 0.94000; 115 1 22.0 7.0 0.0 0.0 1 1.03697 -25.85161 138.0 1 1.06000 0.94000; 116 2 184.0 0.0 0.0 0.0 1 1.01953 -6.10767 138.0 1 1.06000 0.94000; 117 1 20.0 8.0 0.0 0.0 1 1.04531 -31.38704 138.0 1 1.06000 0.94000; 118 1 33.0 15.0 0.0 0.0 1 1.00105 -10.44914 138.0 1 1.06000 0.94000; ]; %% load data %column_names% load_bus pref qref status qmax qmin pmax pmin prated qrated voll % mpc.load = [ % 1 51 27 1 27 0 51 0 51 27 5000; % 2 20 9 1 9 0 20 0 20 9 5000; % 3 39 10 1 10 0 39 0 39 10 5000; % 4 39 12 1 12 0 39 0 39 12 5000; % 5 0 0 1 0 0 0 0 0 0 5000; % 6 52 22 1 22 0 52 0 52 22 5000; % 7 19 2 1 2 0 19 0 19 2 5000; % 8 28 0 1 0 0 28 0 28 0 5000; % 9 0 0 1 0 0 0 0 0 0 5000; % 10 0 0 1 0 0 0 0 0 0 5000; % 11 70 23 1 23 0 70 0 70 23 5000; % 12 47 10 1 10 0 47 0 47 10 5000; % 13 34 16 1 16 0 34 0 34 16 5000; % 14 14 1 1 1 0 14 0 14 1 5000; % 15 90 30 1 30 0 90 0 90 30 5000; % 16 25 10 1 10 0 25 0 25 10 5000; % 17 11 3 1 3 0 11 0 11 3 5000; % 18 60 34 1 34 0 60 0 60 34 5000; % 19 45 25 1 25 0 45 0 45 25 5000; % 20 18 3 1 3 0 18 0 18 3 5000; % 21 14 8 1 8 0 14 0 14 8 5000; % 22 10 5 1 5 0 10 0 10 5 5000; % 23 7 3 1 3 0 7 0 7 3 5000; % 24 13 0 1 0 0 13 0 13 0 5000; % 25 0 0 1 0 0 0 0 0 0 5000; % 26 0 0 1 0 0 0 0 0 0 5000; % 27 71 13 1 13 0 71 0 71 13 5000; % 28 17 7 1 7 0 17 0 17 7 5000; % 29 24 4 1 4 0 24 0 24 4 5000; % 30 0 0 1 0 0 0 0 0 0 5000; % 31 43 27 1 27 0 43 0 43 27 5000; % 32 59 23 1 23 0 59 0 59 23 5000; % 33 23 9 1 9 0 23 0 23 9 5000; % 34 59 26 1 26 0 59 0 59 26 5000; % 35 33 9 1 9 0 33 0 33 9 5000; % 36 31 17 1 17 0 31 0 31 17 5000; % 37 0 0 1 0 0 0 0 0 0 5000; % 38 0 0 1 0 0 0 0 0 0 5000; % 39 27 11 1 11 0 27 0 27 11 5000; % 40 66 23 1 23 0 66 0 66 23 5000; % 41 37 10 1 10 0 37 0 37 10 5000; % 42 96 23 1 23 0 96 0 96 23 5000; % 43 18 7 1 7 0 18 0 18 7 5000; % 44 16 8 1 8 0 16 0 16 8 5000; % 45 53 22 1 22 0 53 0 53 22 5000; % 46 28 10 1 10 0 28 0 28 10 5000; % 47 34 0 1 0 0 34 0 34 0 5000; % 48 20 11 1 11 0 20 0 20 11 5000; % 49 87 30 1 30 0 87 0 87 30 5000; % 50 17 4 1 4 0 17 0 17 4 5000; % 51 17 8 1 8 0 17 0 17 8 5000; % 52 18 5 1 5 0 18 0 18 5 5000; % 53 23 11 1 11 0 23 0 23 11 5000; % 54 113 32 1 32 0 113 0 113 32 5000; % 55 63 22 1 22 0 63 0 63 22 5000; % 56 84 18 1 18 0 84 0 84 18 5000; % 57 12 3 1 3 0 12 0 12 3 5000; % 58 12 3 1 3 0 12 0 12 3 5000; % 59 277 113 1 113 0 277 0 277 113 5000; % 60 78 3 1 3 0 78 0 78 3 5000; % 61 0 0 1 0 0 0 0 0 0 5000; % 62 77 14 1 14 0 77 0 77 14 5000; % 63 0 0 1 0 0 0 0 0 0 5000; % 64 0 0 1 0 0 0 0 0 0 5000; % 65 0 0 1 0 0 0 0 0 0 5000; % 66 39 18 1 18 0 39 0 39 18 5000; % 67 28 7 1 7 0 28 0 28 7 5000; % 68 0 0 1 0 0 0 0 0 0 5000; % 69 0 0 1 0 0 0 0 0 0 5000; % 70 66 20 1 20 0 66 0 66 20 5000; % 71 0 0 1 0 0 0 0 0 0 5000; % 72 12 0 1 0 0 12 0 12 0 5000; % 73 6 0 1 0 0 6 0 6 0 5000; % 74 68 27 1 27 0 68 0 68 27 5000; % 75 47 11 1 11 0 47 0 47 11 5000; % 76 68 36 1 36 0 68 0 68 36 5000; % 77 61 28 1 28 0 61 0 61 28 5000; % 78 71 26 1 26 0 71 0 71 26 5000; % 79 39 32 1 32 0 39 0 39 32 5000; % 80 130 26 1 26 0 130 0 130 26 5000; % 81 0 0 1 0 0 0 0 0 0 5000; % 82 54 27 1 27 0 54 0 54 27 5000; % 83 20 10 1 10 0 20 0 20 10 5000; % 84 11 7 1 7 0 11 0 11 7 5000; % 85 24 15 1 15 0 24 0 24 15 5000; % 86 21 10 1 10 0 21 0 21 10 5000; % 87 0 0 1 0 0 0 0 0 0 5000; % 88 48 10 1 10 0 48 0 48 10 5000; % 89 0 0 1 0 0 0 0 0 0 5000; % 90 163 42 1 42 0 163 0 163 42 5000; % 91 10 0 1 0 0 10 0 10 0 5000; % 92 65 10 1 10 0 65 0 65 10 5000; % 93 12 7 1 7 0 12 0 12 7 5000; % 94 30 16 1 16 0 30 0 30 16 5000; % 95 42 31 1 31 0 42 0 42 31 5000; % 96 38 15 1 15 0 38 0 38 15 5000; % 97 15 9 1 9 0 15 0 15 9 5000; % 98 34 8 1 8 0 34 0 34 8 5000; % 99 42 0 1 0 0 42 0 42 0 5000; % 100 37 18 1 18 0 37 0 37 18 5000; % 101 22 15 1 15 0 22 0 22 15 5000; % 102 5 3 1 3 0 5 0 5 3 5000; % 103 23 16 1 16 0 23 0 23 16 5000; % 104 38 25 1 25 0 38 0 38 25 5000; % 105 31 26 1 26 0 31 0 31 26 5000; % 106 43 16 1 16 0 43 0 43 16 5000; % 107 50 12 1 12 0 50 0 50 12 5000; % 108 2 1 1 1 0 2 0 2 1 5000; % 109 8 3 1 3 0 8 0 8 3 5000; % 110 39 30 1 30 0 39 0 39 30 5000; % 111 0 0 1 0 0 0 0 0 0 5000; % 112 68 13 1 13 0 68 0 68 13 5000; % 113 6 0 1 0 0 6 0 6 0 5000; % 114 8 3 1 3 0 8 0 8 3 5000; % 115 22 7 1 7 0 22 0 22 7 5000; % 116 184 0 1 0 0 184 0 184 0 5000; % 117 20 8 1 8 0 20 0 20 8 5000; % 118 33 15 1 15 0 33 0 33 15 5000; % ]; %column_names% load_bus pref qref status qmax qmin pmax pmin prated qrated voll mpc.load = [ 1 51 27 1 27 0 51 51 51 27 5000; 2 20 9 1 9 0 20 20 20 9 5000; 3 39 10 1 10 0 39 39 39 10 5000; 4 39 12 1 12 0 39 39 39 12 5000; 5 0 0 1 0 0 0 0 0 0 5000; 6 52 22 1 22 0 52 52 52 22 5000; 7 19 2 1 2 0 19 19 19 2 5000; 8 28 0 1 0 0 28 28 28 0 5000; 9 0 0 1 0 0 0 0 0 0 5000; 10 0 0 1 0 0 0 0 0 0 5000; 11 70 23 1 23 0 70 70 70 23 5000; 12 47 10 1 10 0 47 47 47 10 5000; 13 34 16 1 16 0 34 34 34 16 5000; 14 14 1 1 1 0 14 14 14 1 5000; 15 90 30 1 30 0 90 90 90 30 5000; 16 25 10 1 10 0 25 25 25 10 5000; 17 11 3 1 3 0 11 11 11 3 5000; 18 60 34 1 34 0 60 60 60 34 5000; 19 45 25 1 25 0 45 45 45 25 5000; 20 18 3 1 3 0 18 18 18 3 5000; 21 14 8 1 8 0 14 14 14 8 5000; 22 10 5 1 5 0 10 10 10 5 5000; 23 7 3 1 3 0 7 7 7 3 5000; 24 13 0 1 0 0 13 13 13 0 5000; 25 0 0 1 0 0 0 0 0 0 5000; 26 0 0 1 0 0 0 0 0 0 5000; 27 71 13 1 13 0 71 71 71 13 5000; 28 17 7 1 7 0 17 17 17 7 5000; 29 24 4 1 4 0 24 24 24 4 5000; 30 0 0 1 0 0 0 0 0 0 5000; 31 43 27 1 27 0 43 43 43 27 5000; 32 59 23 1 23 0 59 59 59 23 5000; 33 23 9 1 9 0 23 23 23 9 5000; 34 59 26 1 26 0 59 59 59 26 5000; 35 33 9 1 9 0 33 33 33 9 5000; 36 31 17 1 17 0 31 31 31 17 5000; 37 0 0 1 0 0 0 0 0 0 5000; 38 0 0 1 0 0 0 0 0 0 5000; 39 27 11 1 11 0 27 27 27 11 5000; 40 66 23 1 23 0 66 66 66 23 5000; 41 37 10 1 10 0 37 37 37 10 5000; 42 96 23 1 23 0 96 96 96 23 5000; 43 18 7 1 7 0 18 18 18 7 5000; 44 16 8 1 8 0 16 16 16 8 5000; 45 53 22 1 22 0 53 53 53 22 5000; 46 28 10 1 10 0 28 28 28 10 5000; 47 34 0 1 0 0 34 34 34 0 5000; 48 20 11 1 11 0 20 20 20 11 5000; 49 87 30 1 30 0 87 87 87 30 5000; 50 17 4 1 4 0 17 17 17 4 5000; 51 17 8 1 8 0 17 17 17 8 5000; 52 18 5 1 5 0 18 18 18 5 5000; 53 23 11 1 11 0 23 23 23 11 5000; 54 113 32 1 32 0 113 113 113 32 5000; 55 63 22 1 22 0 63 63 63 22 5000; 56 84 18 1 18 0 84 84 84 18 5000; 57 12 3 1 3 0 12 12 12 3 5000; 58 12 3 1 3 0 12 12 12 3 5000; 59 277 113 1 113 0 277 277 277 113 5000; 60 78 3 1 3 0 78 78 78 3 5000; 61 0 0 1 0 0 0 0 0 0 5000; 62 77 14 1 14 0 77 77 77 14 5000; 63 0 0 1 0 0 0 0 0 0 5000; 64 0 0 1 0 0 0 0 0 0 5000; 65 0 0 1 0 0 0 0 0 0 5000; 66 39 18 1 18 0 39 39 39 18 5000; 67 28 7 1 7 0 28 28 28 7 5000; 68 0 0 1 0 0 0 0 0 0 5000; 69 0 0 1 0 0 0 0 0 0 5000; 70 66 20 1 20 0 66 66 66 20 5000; 71 0 0 1 0 0 0 0 0 0 5000; 72 12 0 1 0 0 12 12 12 0 5000; 73 6 0 1 0 0 6 6 6 0 5000; 74 68 27 1 27 0 68 68 68 27 5000; 75 47 11 1 11 0 47 47 47 11 5000; 76 68 36 1 36 0 68 68 68 36 5000; 77 61 28 1 28 0 61 61 61 28 5000; 78 71 26 1 26 0 71 71 71 26 5000; 79 39 32 1 32 0 39 39 39 32 5000; 80 130 26 1 26 0 130 130 130 26 5000; 81 0 0 1 0 0 0 0 0 0 5000; 82 54 27 1 27 0 54 54 54 27 5000; 83 20 10 1 10 0 20 20 20 10 5000; 84 11 7 1 7 0 11 11 11 7 5000; 85 24 15 1 15 0 24 24 24 15 5000; 86 21 10 1 10 0 21 21 21 10 5000; 87 0 0 1 0 0 0 0 0 0 5000; 88 48 10 1 10 0 48 48 48 10 5000; 89 0 0 1 0 0 0 0 0 0 5000; 90 163 42 1 42 0 163 163 163 42 5000; 91 10 0 1 0 0 10 10 10 0 5000; 92 65 10 1 10 0 65 65 65 10 5000; 93 12 7 1 7 0 12 12 12 7 5000; 94 30 16 1 16 0 30 30 30 16 5000; 95 42 31 1 31 0 42 42 42 31 5000; 96 38 15 1 15 0 38 38 38 15 5000; 97 15 9 1 9 0 15 15 15 9 5000; 98 34 8 1 8 0 34 34 34 8 5000; 99 42 0 1 0 0 42 42 42 0 5000; 100 37 18 1 18 0 37 37 37 18 5000; 101 22 15 1 15 0 22 22 22 15 5000; 102 5 3 1 3 0 5 5 5 3 5000; 103 23 16 1 16 0 23 23 23 16 5000; 104 38 25 1 25 0 38 38 38 25 5000; 105 31 26 1 26 0 31 31 31 26 5000; 106 43 16 1 16 0 43 43 43 16 5000; 107 50 12 1 12 0 50 50 50 12 5000; 108 2 1 1 1 0 2 2 2 1 5000; 109 8 3 1 3 0 8 8 8 3 5000; 110 39 30 1 30 0 39 39 39 30 5000; 111 0 0 1 0 0 0 0 0 0 5000; 112 68 13 1 13 0 68 68 68 13 5000; 113 6 0 1 0 0 6 6 6 0 5000; 114 8 3 1 3 0 8 8 8 3 5000; 115 22 7 1 7 0 22 22 22 7 5000; 116 184 0 1 0 0 184 184 184 0 5000; 117 20 8 1 8 0 20 20 20 8 5000; 118 33 15 1 15 0 33 33 33 15 5000; ]; %% generator data % bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf mpc.gen = [ 1 0 14.9997417255247 15 -5 1.03288369946984 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.24844800435941 0 0.00859136172144137 0; 4 0 48.0270218683761 300 -300 1.05695012382517 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.21793523850317 0 0 0; 6 0 27.1880857018100 50 -13 1.05499580425794 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.22335689938984 0 0 0; 8 0 -71.6682405352844 300 -300 1.04466682405503 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.21290118016473 0 0 0; 10 8.86071568344016e-06 -145.123394030959 200 -147 1.03536771828475 100 1 663 0 0 0 0 0 0 0 0 0 0 0 0 0 0.250612149624416 0 0; 12 286.999993156386 57.5003395511161 120 -35 1.05973944054506 100 1 287 0 0 0 0 0 0 0 0 0 0 0 0 0.323752692295418 0 0 0; 15 0 29.9942990485805 30 -10 1.04940836749001 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.23025666700981 0 0.00149476263972702 0; 18 0 43.4842966485054 50 -16 1.05267783100213 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.22514524876027 0 0 0; 19 0 23.9986608004092 24 -8 1.04788669601264 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.23087181065147 0 0.00221758848196707 0; 24 0 9.36215790837624 300 -300 1.05681894894829 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.12455966442146 0 0 0; 25 266.999987550377 -46.9997605040253 134 -47 1.05999996179115 100 1 267 0 0 0 0 0 0 0 0 0 0 0 0 0.178253297700177 0 0 0.00937191736763971; 26 286.792939498662 -25.0598375854770 226 -226 1.02523576433431 100 1 451 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 27 0 30.4924451513644 300 -300 1.04144000209556 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.19350168232165 0 0 0; 31 22.9999944080875 11.9994201377314 12 -12 1.03445766187313 100 1 23 0 0 0 0 0 0 0 0 0 0 0 0 0.397288046413249 0 0.00505725631804230 0; 32 0 35.9955105267097 42 -14 1.04236567171749 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.19733908170910 0 0 0; 34 0 23.9998142046791 24 -8 1.05774922366741 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.22060548968399 0 0.00943165250919168 0; 36 0 23.9998222354178 24 -8 1.05569982463604 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.22499774233106 0 0.00995128661362497 0; 40 0 49.9243479935188 300 -300 1.02959961799499 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.30163159775808 0 0 0; 42 0 26.3190858449638 300 -300 1.01040066581342 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.32237136628673 0 0 0; 46 1.05193460988788e-05 7.71995680986653 26 -26 1.01211143247386 100 1 51 0 0 0 0 0 0 0 0 0 0 0 0 0 0.210557078358170 0 0; 49 231.999989293540 -11.0636550417525 116 -85 1.02322304072397 100 1 232 0 0 0 0 0 0 0 0 0 0 0 0 0.207413586808980 0 0 0; 54 3.97148408283752e-05 55.7905020286754 75 -75 1.01030823522666 100 1 150 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0556029515191602 0 0; 55 0 22.9977061881480 23 -8 1.01051257238627 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.26358026733824 0 0.00146380253230816 0; 56 0 14.9968467913789 15 -8 1.00980383652585 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.26631259273624 0 0 0; 59 7.24166752665161e-06 140.999716910516 141 -60 1.04824020941918 100 1 282 0 0 0 0 0 0 0 0 0 0 0 0 0 0.305881613671974 0.0104037889214038 0; 61 1.03062279179409e-05 124.391093326423 126 -100 1.05999985743989 100 1 251 0 0 0 0 0 0 0 0 0 0 0 0 0 0.214790885177788 0 0; 62 0 -19.7847244444268 20 -20 1.04639459108837 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.00974104885317 0 0 0; 65 295.353980426645 119.758384391229 200 -67 1.02986509519456 100 1 608 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 66 829.461138674558 -66.9999484333984 200 -67 1.05999997121113 100 1 865 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0439390963463592; 69 880.999995292750 -114.499398075079 300 -300 1.05999997725914 100 1 881 0 0 0 0 0 0 0 0 0 0 0 0 0.471400767471870 0 0 0; 70 0 31.9990449186736 32 -10 1.03170086765134 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.08539374844583 0 0.00246809807332319 0; 72 0 -1.83538915763558 100 -100 1.04424751090098 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.11286968972446 0 0 0 73 0 5.03658464452433 100 -100 1.03744707964232 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.09197021091226 0 0 0 74 0 8.99978993414160 9 -6 1.01047857270712 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.09560881366347 0 0.0106525627918897 0; 76 0 22.9998669140759 23 -8 0.999595939249165 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.09276177940132 0 0.0167449810075151 0; 77 0 69.9989828171801 70 -20 1.04410294711087 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.02952379781969 0 0.00218630408960811 0; 80 445.773015434727 -0.203740114231859 280 -165 1.05999986881372 100 1 739 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 85 0 22.9998696583627 23 -8 1.04906666850228 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.886497795718862 0 0.0169195006981392 0; 87 4.61026159022512e-06 3.99984435729711 4 -4 1.05481336448442 100 1 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0.481678177131928 0.0140780248285474 0; 89 568.006174778810 -31.5618896595727 300 -210 1.05999995920182 100 1 845 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 90 0 76.2129632358894 300 -300 1.05125611369805 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.888889380549321 0 0 0; 91 0 -8.92468094997580 100 -100 1.04436121264209 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.957802785257935 0 0 0; 92 0 -2.99913339851926 9 -3 1.04495131124305 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.05654774525677 0 0 0.00252168234350669; 99 0 -0.197135510538153 100 -100 1.05160277956836 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.05987428624847 0 0 0; 100 186.388253896434 49.8154657011957 151 -50 1.05328008751790 100 1 301 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 103 97.9999945290567 29.9782682651573 40 -15 1.05037248550051 100 1 98 0 0 0 0 0 0 0 0 0 0 0 0 0.405745630001528 0 0 0; 104 0 22.9934955498827 23 -8 1.03707781338136 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.12873564924603 0 0.00139667325494156 0; 105 0 22.9553835237027 23 -8 1.03455274456496 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.14105132371377 0 0 0; 107 0 7.01988276955098 200 -200 1.02207426444085 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.17190932274677 0 0 0; 110 0 22.9986168840287 23 -8 1.02319321282162 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.17895861797322 0 0.00208936602433251 0; 111 9.81873410053662e-05 3.17606488116643 67 -67 1.02630415962014 100 1 133 0 0 0 0 0 0 0 0 0 0 0 0 0 0.0219266049270711 0 0; 112 0 16.4020683978294 1000 -100 1.00974179505731 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.21871290892915 0 0 0; 113 0 -3.79997987172122 200 -100 1.05702448475848 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1.20326883287322 0 0 0; 116 0 -19.8802030330715 1000 -1000 1.01952244228330 100 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.980488745738085 0 0 0; ]; %column_names% prated qrated pref qref mpc.gen_rated = [ 0 15 0 15; 0 300 0 48.4100000000000; 0 50 0 27.2540000000000; 0 300 0 -71.8670000000000; 663 200 0 -145.350000000000; 287 120 287 57.8300000000000; 0 30 0 30; 0 50 0 43.3310000000000; 0 24 0 24; 0 300 0 9.36500000000000; 267 134 267 -47; 451 226 286.801000000000 -25.0580000000000; 0 300 0 30.4800000000000; 23 12 23 12; 0 42 0 35.9790000000000; 0 24 0 24; 0 24 0 24; 0 300 0 49.9430000000000; 0 300 0 26.3210000000000; 51 26 0 7.72000000000000; 232 116 232 -11.0100000000000; 150 75 0 55.7060000000000; 0 23 0 23; 0 15 0 15; 282 141 0 141; 251 126 0 124.577000000000; 0 20 0 -19.9990000000000; 608 200 295.338000000000 119.802000000000; 865 200 829.470000000000 -67; 881 300 881 -114.523000000000; 0 32 0 32; 0 100 0 -1.83500000000000; 0 100 0 5.03600000000000; 0 9 0 9; 0 23 0 23; 0 70 0 70; 739 280 445.771000000000 -0.216000000000000; 0 23 0 23; 7 4 0 4; 845 300 568.006000000000 -31.5640000000000; 0 300 0 76.2140000000000; 0 100 0 -8.92300000000000; 0 9 0 -3; 0 100 0 -0.197000000000000; 301 151 186.388000000000 49.8030000000000; 98 40 98 29.9590000000000; 0 23 0 23; 0 23 0 23; 0 200 0 7.00500000000000; 0 23 0 23; 133 67 0 3.17300000000000; 0 1000 0 16.3990000000000; 0 200 0 -3.98400000000000; 0 1000 0 -19.8640000000000 ]; %% generator cost data % 2 startup shutdown n c(n-1) ... c0 mpc.gencost = [ 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.463389 0.000000; % NG 2 0.0 0.0 3 0.000000 0.889054 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.929688 0.000000; % NG 2 0.0 0.0 3 0.000000 1.118121 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.814446 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.513792 0.000000; % NG 2 0.0 0.0 3 0.000000 1.071413 0.000000; % NG 2 0.0 0.0 3 0.000000 1.324712 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.426207 0.000000; % NG 2 0.0 0.0 3 0.000000 1.245208 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.969762 0.000000; % NG 2 0.0 0.0 3 0.000000 0.865713 0.000000; % COW 2 0.0 0.0 3 0.000000 0.518513 0.000000; % COW 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.006636 0.000000; % COW 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.381184 0.000000; % NG 2 0.0 0.0 3 0.000000 0.793496 0.000000; % COW 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.066562 0.000000; % NG 2 0.0 0.0 3 0.000000 0.691193 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 1.200887 0.000000; % NG 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC 2 0.0 0.0 3 0.000000 0.000000 0.000000; % SYNC ]; %% branch data % fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax mpc.branch = [ 1 2 0.0303 0.0999 0.0254 151 151 151 0.0 0.0 1 -30.0 30.0; 1 3 0.0129 0.0424 0.01082 151 151 151 0.0 0.0 1 -30.0 30.0; 4 5 0.00176 0.00798 0.0021 176 176 176 0.0 0.0 1 -30.0 30.0; 3 5 0.0241 0.108 0.0284 175 175 175 0.0 0.0 1 -30.0 30.0; 5 6 0.0119 0.054 0.01426 176 176 176 0.0 0.0 1 -30.0 30.0; 6 7 0.00459 0.0208 0.0055 176 176 176 0.0 0.0 1 -30.0 30.0; 8 9 0.00244 0.0305 1.162 711 711 711 0.0 0.0 1 -30.0 30.0; 8 5 0.0 0.0267 0.0 1099 1099 1099 0.985 0.0 1 -30.0 30.0; 9 10 0.00258 0.0322 1.23 710 710 710 0.0 0.0 1 -30.0 30.0; 4 11 0.0209 0.0688 0.01748 151 151 151 0.0 0.0 1 -30.0 30.0; 5 11 0.0203 0.0682 0.01738 152 152 152 0.0 0.0 1 -30.0 30.0; 11 12 0.00595 0.0196 0.00502 151 151 151 0.0 0.0 1 -30.0 30.0; 2 12 0.0187 0.0616 0.01572 151 151 151 0.0 0.0 1 -30.0 30.0; 3 12 0.0484 0.16 0.0406 151 151 151 0.0 0.0 1 -30.0 30.0; 7 12 0.00862 0.034 0.00874 164 164 164 0.0 0.0 1 -30.0 30.0; 11 13 0.02225 0.0731 0.01876 151 151 151 0.0 0.0 1 -30.0 30.0; 12 14 0.0215 0.0707 0.01816 151 151 151 0.0 0.0 1 -30.0 30.0; 13 15 0.0744 0.2444 0.06268 115 115 115 0.0 0.0 1 -30.0 30.0; 14 15 0.0595 0.195 0.0502 144 144 144 0.0 0.0 1 -30.0 30.0; 12 16 0.0212 0.0834 0.0214 164 164 164 0.0 0.0 1 -30.0 30.0; 15 17 0.0132 0.0437 0.0444 151 151 151 0.0 0.0 1 -30.0 30.0; 16 17 0.0454 0.1801 0.0466 158 158 158 0.0 0.0 1 -30.0 30.0; 17 18 0.0123 0.0505 0.01298 167 167 167 0.0 0.0 1 -30.0 30.0; 18 19 0.01119 0.0493 0.01142 173 173 173 0.0 0.0 1 -30.0 30.0; 19 20 0.0252 0.117 0.0298 178 178 178 0.0 0.0 1 -30.0 30.0; 15 19 0.012 0.0394 0.0101 151 151 151 0.0 0.0 1 -30.0 30.0; 20 21 0.0183 0.0849 0.0216 177 177 177 0.0 0.0 1 -30.0 30.0; 21 22 0.0209 0.097 0.0246 178 178 178 0.0 0.0 1 -30.0 30.0; 22 23 0.0342 0.159 0.0404 178 178 178 0.0 0.0 1 -30.0 30.0; 23 24 0.0135 0.0492 0.0498 158 158 158 0.0 0.0 1 -30.0 30.0; 23 25 0.0156 0.08 0.0864 186 186 186 0.0 0.0 1 -30.0 30.0; 26 25 0.0 0.0382 0.0 768 768 768 0.96 0.0 1 -30.0 30.0; 25 27 0.0318 0.163 0.1764 177 177 177 0.0 0.0 1 -30.0 30.0; 27 28 0.01913 0.0855 0.0216 174 174 174 0.0 0.0 1 -30.0 30.0; 28 29 0.0237 0.0943 0.0238 165 165 165 0.0 0.0 1 -30.0 30.0; 30 17 0.0 0.0388 0.0 756 756 756 0.96 0.0 1 -30.0 30.0; 8 30 0.00431 0.0504 0.514 580 580 580 0.0 0.0 1 -30.0 30.0; 26 30 0.00799 0.086 0.908 340 340 340 0.0 0.0 1 -30.0 30.0; 17 31 0.0474 0.1563 0.0399 151 151 151 0.0 0.0 1 -30.0 30.0; 29 31 0.0108 0.0331 0.0083 146 146 146 0.0 0.0 1 -30.0 30.0; 23 32 0.0317 0.1153 0.1173 158 158 158 0.0 0.0 1 -30.0 30.0; 31 32 0.0298 0.0985 0.0251 151 151 151 0.0 0.0 1 -30.0 30.0; 27 32 0.0229 0.0755 0.01926 151 151 151 0.0 0.0 1 -30.0 30.0; 15 33 0.038 0.1244 0.03194 150 150 150 0.0 0.0 1 -30.0 30.0; 19 34 0.0752 0.247 0.0632 114 114 114 0.0 0.0 1 -30.0 30.0; 35 36 0.00224 0.0102 0.00268 176 176 176 0.0 0.0 1 -30.0 30.0; 35 37 0.011 0.0497 0.01318 175 175 175 0.0 0.0 1 -30.0 30.0; 33 37 0.0415 0.142 0.0366 154 154 154 0.0 0.0 1 -30.0 30.0; 34 36 0.00871 0.0268 0.00568 146 146 146 0.0 0.0 1 -30.0 30.0; 34 37 0.00256 0.0094 0.00984 159 159 159 0.0 0.0 1 -30.0 30.0; 38 37 0.0 0.0375 0.0 783 783 783 0.935 0.0 1 -30.0 30.0; 37 39 0.0321 0.106 0.027 151 151 151 0.0 0.0 1 -30.0 30.0; 37 40 0.0593 0.168 0.042 140 140 140 0.0 0.0 1 -30.0 30.0; 30 38 0.00464 0.054 0.422 542 542 542 0.0 0.0 1 -30.0 30.0; 39 40 0.0184 0.0605 0.01552 151 151 151 0.0 0.0 1 -30.0 30.0; 40 41 0.0145 0.0487 0.01222 152 152 152 0.0 0.0 1 -30.0 30.0; 40 42 0.0555 0.183 0.0466 151 151 151 0.0 0.0 1 -30.0 30.0; 41 42 0.041 0.135 0.0344 151 151 151 0.0 0.0 1 -30.0 30.0; 43 44 0.0608 0.2454 0.06068 117 117 117 0.0 0.0 1 -30.0 30.0; 34 43 0.0413 0.1681 0.04226 167 167 167 0.0 0.0 1 -30.0 30.0; 44 45 0.0224 0.0901 0.0224 166 166 166 0.0 0.0 1 -30.0 30.0; 45 46 0.04 0.1356 0.0332 153 153 153 0.0 0.0 1 -30.0 30.0; 46 47 0.038 0.127 0.0316 152 152 152 0.0 0.0 1 -30.0 30.0; 46 48 0.0601 0.189 0.0472 148 148 148 0.0 0.0 1 -30.0 30.0; 47 49 0.0191 0.0625 0.01604 150 150 150 0.0 0.0 1 -30.0 30.0; 42 49 0.0715 0.323 0.086 89 89 89 0.0 0.0 1 -30.0 30.0; 42 49 0.0715 0.323 0.086 89 89 89 0.0 0.0 1 -30.0 30.0; 45 49 0.0684 0.186 0.0444 138 138 138 0.0 0.0 1 -30.0 30.0; 48 49 0.0179 0.0505 0.01258 140 140 140 0.0 0.0 1 -30.0 30.0; 49 50 0.0267 0.0752 0.01874 140 140 140 0.0 0.0 1 -30.0 30.0; 49 51 0.0486 0.137 0.0342 140 140 140 0.0 0.0 1 -30.0 30.0; 51 52 0.0203 0.0588 0.01396 142 142 142 0.0 0.0 1 -30.0 30.0; 52 53 0.0405 0.1635 0.04058 166 166 166 0.0 0.0 1 -30.0 30.0; 53 54 0.0263 0.122 0.031 177 177 177 0.0 0.0 1 -30.0 30.0; 49 54 0.073 0.289 0.0738 99 99 99 0.0 0.0 1 -30.0 30.0; 49 54 0.0869 0.291 0.073 97 97 97 0.0 0.0 1 -30.0 30.0; 54 55 0.0169 0.0707 0.0202 169 169 169 0.0 0.0 1 -30.0 30.0; 54 56 0.00275 0.00955 0.00732 155 155 155 0.0 0.0 1 -30.0 30.0; 55 56 0.00488 0.0151 0.00374 146 146 146 0.0 0.0 1 -30.0 30.0; 56 57 0.0343 0.0966 0.0242 140 140 140 0.0 0.0 1 -30.0 30.0; 50 57 0.0474 0.134 0.0332 140 140 140 0.0 0.0 1 -30.0 30.0; 56 58 0.0343 0.0966 0.0242 140 140 140 0.0 0.0 1 -30.0 30.0; 51 58 0.0255 0.0719 0.01788 140 140 140 0.0 0.0 1 -30.0 30.0; 54 59 0.0503 0.2293 0.0598 125 125 125 0.0 0.0 1 -30.0 30.0; 56 59 0.0825 0.251 0.0569 112 112 112 0.0 0.0 1 -30.0 30.0; 56 59 0.0803 0.239 0.0536 117 117 117 0.0 0.0 1 -30.0 30.0; 55 59 0.04739 0.2158 0.05646 133 133 133 0.0 0.0 1 -30.0 30.0; 59 60 0.0317 0.145 0.0376 176 176 176 0.0 0.0 1 -30.0 30.0; 59 61 0.0328 0.15 0.0388 176 176 176 0.0 0.0 1 -30.0 30.0; 60 61 0.00264 0.0135 0.01456 186 186 186 0.0 0.0 1 -30.0 30.0; 60 62 0.0123 0.0561 0.01468 176 176 176 0.0 0.0 1 -30.0 30.0; 61 62 0.00824 0.0376 0.0098 176 176 176 0.0 0.0 1 -30.0 30.0; 63 59 0.0 0.0386 0.0 760 760 760 0.96 0.0 1 -30.0 30.0; 63 64 0.00172 0.02 0.216 687 687 687 0.0 0.0 1 -30.0 30.0; 64 61 0.0 0.0268 0.0 1095 1095 1095 0.985 0.0 1 -30.0 30.0; 38 65 0.00901 0.0986 1.046 297 297 297 0.0 0.0 1 -30.0 30.0; 64 65 0.00269 0.0302 0.38 675 675 675 0.0 0.0 1 -30.0 30.0; 49 66 0.018 0.0919 0.0248 186 186 186 0.0 0.0 1 -30.0 30.0; 49 66 0.018 0.0919 0.0248 186 186 186 0.0 0.0 1 -30.0 30.0; 62 66 0.0482 0.218 0.0578 132 132 132 0.0 0.0 1 -30.0 30.0; 62 67 0.0258 0.117 0.031 176 176 176 0.0 0.0 1 -30.0 30.0; 65 66 0.0 0.037 0.0 793 793 793 0.935 0.0 1 -30.0 30.0; 66 67 0.0224 0.1015 0.02682 176 176 176 0.0 0.0 1 -30.0 30.0; 65 68 0.00138 0.016 0.638 686 686 686 0.0 0.0 1 -30.0 30.0; 47 69 0.0844 0.2778 0.07092 102 102 102 0.0 0.0 1 -30.0 30.0; 49 69 0.0985 0.324 0.0828 87 87 87 0.0 0.0 1 -30.0 30.0; 68 69 0.0 0.037 0.0 793 793 793 0.935 0.0 1 -30.0 30.0; 69 70 0.03 0.127 0.122 170 170 170 0.0 0.0 1 -30.0 30.0; 24 70 0.00221 0.4115 0.10198 72 72 72 0.0 0.0 1 -30.0 30.0; 70 71 0.00882 0.0355 0.00878 166 166 166 0.0 0.0 1 -30.0 30.0; 24 72 0.0488 0.196 0.0488 146 146 146 0.0 0.0 1 -30.0 30.0; 71 72 0.0446 0.18 0.04444 159 159 159 0.0 0.0 1 -30.0 30.0; 71 73 0.00866 0.0454 0.01178 188 188 188 0.0 0.0 1 -30.0 30.0; 70 74 0.0401 0.1323 0.03368 151 151 151 0.0 0.0 1 -30.0 30.0; 70 75 0.0428 0.141 0.036 151 151 151 0.0 0.0 1 -30.0 30.0; 69 75 0.0405 0.122 0.124 145 145 145 0.0 0.0 1 -30.0 30.0; 74 75 0.0123 0.0406 0.01034 151 151 151 0.0 0.0 1 -30.0 30.0; 76 77 0.0444 0.148 0.0368 152 152 152 0.0 0.0 1 -30.0 30.0; 69 77 0.0309 0.101 0.1038 150 150 150 0.0 0.0 1 -30.0 30.0; 75 77 0.0601 0.1999 0.04978 141 141 141 0.0 0.0 1 -30.0 30.0; 77 78 0.00376 0.0124 0.01264 151 151 151 0.0 0.0 1 -30.0 30.0; 78 79 0.00546 0.0244 0.00648 174 174 174 0.0 0.0 1 -30.0 30.0; 77 80 0.017 0.0485 0.0472 141 141 141 0.0 0.0 1 -30.0 30.0; 77 80 0.0294 0.105 0.0228 157 157 157 0.0 0.0 1 -30.0 30.0; 79 80 0.0156 0.0704 0.0187 175 175 175 0.0 0.0 1 -30.0 30.0; 68 81 0.00175 0.0202 0.808 684 684 684 0.0 0.0 1 -30.0 30.0; 81 80 0.0 0.037 0.0 793 793 793 0.935 0.0 1 -30.0 30.0; 77 82 0.0298 0.0853 0.08174 141 141 141 0.0 0.0 1 -30.0 30.0; 82 83 0.0112 0.03665 0.03796 150 150 150 0.0 0.0 1 -30.0 30.0; 83 84 0.0625 0.132 0.0258 122 122 122 0.0 0.0 1 -30.0 30.0; 83 85 0.043 0.148 0.0348 154 154 154 0.0 0.0 1 -30.0 30.0; 84 85 0.0302 0.0641 0.01234 122 122 122 0.0 0.0 1 -30.0 30.0; 85 86 0.035 0.123 0.0276 156 156 156 0.0 0.0 1 -30.0 30.0; 86 87 0.02828 0.2074 0.0445 141 141 141 0.0 0.0 1 -30.0 30.0; 85 88 0.02 0.102 0.0276 186 186 186 0.0 0.0 1 -30.0 30.0; 85 89 0.0239 0.173 0.047 168 168 168 0.0 0.0 1 -30.0 30.0; 88 89 0.0139 0.0712 0.01934 186 186 186 0.0 0.0 1 -30.0 30.0; 89 90 0.0518 0.188 0.0528 151 151 151 0.0 0.0 1 -30.0 30.0; 89 90 0.0238 0.0997 0.106 169 169 169 0.0 0.0 1 -30.0 30.0; 90 91 0.0254 0.0836 0.0214 151 151 151 0.0 0.0 1 -30.0 30.0; 89 92 0.0099 0.0505 0.0548 186 186 186 0.0 0.0 1 -30.0 30.0; 89 92 0.0393 0.1581 0.0414 166 166 166 0.0 0.0 1 -30.0 30.0; 91 92 0.0387 0.1272 0.03268 151 151 151 0.0 0.0 1 -30.0 30.0; 92 93 0.0258 0.0848 0.0218 151 151 151 0.0 0.0 1 -30.0 30.0; 92 94 0.0481 0.158 0.0406 151 151 151 0.0 0.0 1 -30.0 30.0; 93 94 0.0223 0.0732 0.01876 151 151 151 0.0 0.0 1 -30.0 30.0; 94 95 0.0132 0.0434 0.0111 151 151 151 0.0 0.0 1 -30.0 30.0; 80 96 0.0356 0.182 0.0494 159 159 159 0.0 0.0 1 -30.0 30.0; 82 96 0.0162 0.053 0.0544 150 150 150 0.0 0.0 1 -30.0 30.0; 94 96 0.0269 0.0869 0.023 149 149 149 0.0 0.0 1 -30.0 30.0; 80 97 0.0183 0.0934 0.0254 186 186 186 0.0 0.0 1 -30.0 30.0; 80 98 0.0238 0.108 0.0286 176 176 176 0.0 0.0 1 -30.0 30.0; 80 99 0.0454 0.206 0.0546 140 140 140 0.0 0.0 1 -30.0 30.0; 92 100 0.0648 0.295 0.0472 98 98 98 0.0 0.0 1 -30.0 30.0; 94 100 0.0178 0.058 0.0604 150 150 150 0.0 0.0 1 -30.0 30.0; 95 96 0.0171 0.0547 0.01474 149 149 149 0.0 0.0 1 -30.0 30.0; 96 97 0.0173 0.0885 0.024 186 186 186 0.0 0.0 1 -30.0 30.0; 98 100 0.0397 0.179 0.0476 160 160 160 0.0 0.0 1 -30.0 30.0; 99 100 0.018 0.0813 0.0216 175 175 175 0.0 0.0 1 -30.0 30.0; 100 101 0.0277 0.1262 0.0328 176 176 176 0.0 0.0 1 -30.0 30.0; 92 102 0.0123 0.0559 0.01464 176 176 176 0.0 0.0 1 -30.0 30.0; 101 102 0.0246 0.112 0.0294 176 176 176 0.0 0.0 1 -30.0 30.0; 100 103 0.016 0.0525 0.0536 151 151 151 0.0 0.0 1 -30.0 30.0; 100 104 0.0451 0.204 0.0541 141 141 141 0.0 0.0 1 -30.0 30.0; 103 104 0.0466 0.1584 0.0407 153 153 153 0.0 0.0 1 -30.0 30.0; 103 105 0.0535 0.1625 0.0408 145 145 145 0.0 0.0 1 -30.0 30.0; 100 106 0.0605 0.229 0.062 124 124 124 0.0 0.0 1 -30.0 30.0; 104 105 0.00994 0.0378 0.00986 161 161 161 0.0 0.0 1 -30.0 30.0; 105 106 0.014 0.0547 0.01434 164 164 164 0.0 0.0 1 -30.0 30.0; 105 107 0.053 0.183 0.0472 154 154 154 0.0 0.0 1 -30.0 30.0; 105 108 0.0261 0.0703 0.01844 137 137 137 0.0 0.0 1 -30.0 30.0; 106 107 0.053 0.183 0.0472 154 154 154 0.0 0.0 1 -30.0 30.0; 108 109 0.0105 0.0288 0.0076 138 138 138 0.0 0.0 1 -30.0 30.0; 103 110 0.03906 0.1813 0.0461 159 159 159 0.0 0.0 1 -30.0 30.0; 109 110 0.0278 0.0762 0.0202 138 138 138 0.0 0.0 1 -30.0 30.0; 110 111 0.022 0.0755 0.02 154 154 154 0.0 0.0 1 -30.0 30.0; 110 112 0.0247 0.064 0.062 135 135 135 0.0 0.0 1 -30.0 30.0; 17 113 0.00913 0.0301 0.00768 151 151 151 0.0 0.0 1 -30.0 30.0; 32 113 0.0615 0.203 0.0518 139 139 139 0.0 0.0 1 -30.0 30.0; 32 114 0.0135 0.0612 0.01628 176 176 176 0.0 0.0 1 -30.0 30.0; 27 115 0.0164 0.0741 0.01972 175 175 175 0.0 0.0 1 -30.0 30.0; 114 115 0.0023 0.0104 0.00276 175 175 175 0.0 0.0 1 -30.0 30.0; 68 116 0.00034 0.00405 0.164 7218 7218 7218 0.0 0.0 1 -30.0 30.0; 12 117 0.0329 0.14 0.0358 170 170 170 0.0 0.0 1 -30.0 30.0; 75 118 0.0145 0.0481 0.01198 151 151 151 0.0 0.0 1 -30.0 30.0; 76 118 0.0164 0.0544 0.01356 151 151 151 0.0 0.0 1 -30.0 30.0; ]; %column_names% g_shunt shiftable shift_fr shift_to shift_fr_max shift_fr_min shift_to_max shift_to_min tappable tap_fr tap_to tap_fr_max tap_fr_min tap_to_max tap_to_min mpc.branch_variable_transformer = [ 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; ]; %column_names% prob branch_id1 branch_id2 branch_id3 gen_id1 gen_id2 gen_id3 mpc.contingencies = [ 0.980000000000000 0 0 0 0 0 0; 0.000107526881720430 1 0 0 0 0 0; 0.000107526881720430 2 0 0 0 0 0; 0.000107526881720430 3 0 0 0 0 0; 0.000107526881720430 4 0 0 0 0 0; 0.000107526881720430 5 0 0 0 0 0; 0.000107526881720430 6 0 0 0 0 0; 0.000107526881720430 7 0 0 0 0 0; 0.000107526881720430 8 0 0 0 0 0; 0.000107526881720430 9 0 0 0 0 0; 0.000107526881720430 10 0 0 0 0 0; 0.000107526881720430 11 0 0 0 0 0; 0.000107526881720430 12 0 0 0 0 0; 0.000107526881720430 13 0 0 0 0 0; 0.000107526881720430 14 0 0 0 0 0; 0.000107526881720430 15 0 0 0 0 0; 0.000107526881720430 16 0 0 0 0 0; 0.000107526881720430 17 0 0 0 0 0; 0.000107526881720430 18 0 0 0 0 0; 0.000107526881720430 19 0 0 0 0 0; 0.000107526881720430 20 0 0 0 0 0; 0.000107526881720430 21 0 0 0 0 0; 0.000107526881720430 22 0 0 0 0 0; 0.000107526881720430 23 0 0 0 0 0; 0.000107526881720430 24 0 0 0 0 0; 0.000107526881720430 25 0 0 0 0 0; 0.000107526881720430 26 0 0 0 0 0; 0.000107526881720430 27 0 0 0 0 0; 0.000107526881720430 28 0 0 0 0 0; 0.000107526881720430 29 0 0 0 0 0; 0.000107526881720430 30 0 0 0 0 0; 0.000107526881720430 31 0 0 0 0 0; 0.000107526881720430 32 0 0 0 0 0; 0.000107526881720430 33 0 0 0 0 0; 0.000107526881720430 34 0 0 0 0 0; 0.000107526881720430 35 0 0 0 0 0; 0.000107526881720430 36 0 0 0 0 0; 0.000107526881720430 37 0 0 0 0 0; 0.000107526881720430 38 0 0 0 0 0; 0.000107526881720430 39 0 0 0 0 0; 0.000107526881720430 40 0 0 0 0 0; 0.000107526881720430 41 0 0 0 0 0; 0.000107526881720430 42 0 0 0 0 0; 0.000107526881720430 43 0 0 0 0 0; 0.000107526881720430 44 0 0 0 0 0; 0.000107526881720430 45 0 0 0 0 0; 0.000107526881720430 46 0 0 0 0 0; 0.000107526881720430 47 0 0 0 0 0; 0.000107526881720430 48 0 0 0 0 0; 0.000107526881720430 49 0 0 0 0 0; 0.000107526881720430 50 0 0 0 0 0; 0.000107526881720430 51 0 0 0 0 0; 0.000107526881720430 52 0 0 0 0 0; 0.000107526881720430 53 0 0 0 0 0; 0.000107526881720430 54 0 0 0 0 0; 0.000107526881720430 55 0 0 0 0 0; 0.000107526881720430 56 0 0 0 0 0; 0.000107526881720430 57 0 0 0 0 0; 0.000107526881720430 58 0 0 0 0 0; 0.000107526881720430 59 0 0 0 0 0; 0.000107526881720430 60 0 0 0 0 0; 0.000107526881720430 61 0 0 0 0 0; 0.000107526881720430 62 0 0 0 0 0; 0.000107526881720430 63 0 0 0 0 0; 0.000107526881720430 64 0 0 0 0 0; 0.000107526881720430 65 0 0 0 0 0; 0.000107526881720430 66 0 0 0 0 0; 0.000107526881720430 67 0 0 0 0 0; 0.000107526881720430 68 0 0 0 0 0; 0.000107526881720430 69 0 0 0 0 0; 0.000107526881720430 70 0 0 0 0 0; 0.000107526881720430 71 0 0 0 0 0; 0.000107526881720430 72 0 0 0 0 0; 0.000107526881720430 73 0 0 0 0 0; 0.000107526881720430 74 0 0 0 0 0; 0.000107526881720430 75 0 0 0 0 0; 0.000107526881720430 76 0 0 0 0 0; 0.000107526881720430 77 0 0 0 0 0; 0.000107526881720430 78 0 0 0 0 0; 0.000107526881720430 79 0 0 0 0 0; 0.000107526881720430 80 0 0 0 0 0; 0.000107526881720430 81 0 0 0 0 0; 0.000107526881720430 82 0 0 0 0 0; 0.000107526881720430 83 0 0 0 0 0; 0.000107526881720430 84 0 0 0 0 0; 0.000107526881720430 85 0 0 0 0 0; 0.000107526881720430 86 0 0 0 0 0; 0.000107526881720430 87 0 0 0 0 0; 0.000107526881720430 88 0 0 0 0 0; 0.000107526881720430 89 0 0 0 0 0; 0.000107526881720430 90 0 0 0 0 0; 0.000107526881720430 91 0 0 0 0 0; 0.000107526881720430 92 0 0 0 0 0; 0.000107526881720430 93 0 0 0 0 0; 0.000107526881720430 94 0 0 0 0 0; 0.000107526881720430 95 0 0 0 0 0; 0.000107526881720430 96 0 0 0 0 0; 0.000107526881720430 97 0 0 0 0 0; 0.000107526881720430 98 0 0 0 0 0; 0.000107526881720430 99 0 0 0 0 0; 0.000107526881720430 100 0 0 0 0 0; 0.000107526881720430 101 0 0 0 0 0; 0.000107526881720430 102 0 0 0 0 0; 0.000107526881720430 103 0 0 0 0 0; 0.000107526881720430 104 0 0 0 0 0; 0.000107526881720430 105 0 0 0 0 0; 0.000107526881720430 106 0 0 0 0 0; 0.000107526881720430 107 0 0 0 0 0; 0.000107526881720430 108 0 0 0 0 0; 0.000107526881720430 109 0 0 0 0 0; 0.000107526881720430 110 0 0 0 0 0; 0.000107526881720430 111 0 0 0 0 0; 0.000107526881720430 112 0 0 0 0 0; 0.000107526881720430 114 0 0 0 0 0; 0.000107526881720430 115 0 0 0 0 0; 0.000107526881720430 116 0 0 0 0 0; 0.000107526881720430 117 0 0 0 0 0; 0.000107526881720430 118 0 0 0 0 0; 0.000107526881720430 119 0 0 0 0 0; 0.000107526881720430 120 0 0 0 0 0; 0.000107526881720430 121 0 0 0 0 0; 0.000107526881720430 122 0 0 0 0 0; 0.000107526881720430 123 0 0 0 0 0; 0.000107526881720430 124 0 0 0 0 0; 0.000107526881720430 125 0 0 0 0 0; 0.000107526881720430 126 0 0 0 0 0; 0.000107526881720430 127 0 0 0 0 0; 0.000107526881720430 128 0 0 0 0 0; 0.000107526881720430 129 0 0 0 0 0; 0.000107526881720430 130 0 0 0 0 0; 0.000107526881720430 131 0 0 0 0 0; 0.000107526881720430 132 0 0 0 0 0; 0.000107526881720430 134 0 0 0 0 0; 0.000107526881720430 135 0 0 0 0 0; 0.000107526881720430 136 0 0 0 0 0; 0.000107526881720430 137 0 0 0 0 0; 0.000107526881720430 138 0 0 0 0 0; 0.000107526881720430 139 0 0 0 0 0; 0.000107526881720430 140 0 0 0 0 0; 0.000107526881720430 141 0 0 0 0 0; 0.000107526881720430 142 0 0 0 0 0; 0.000107526881720430 143 0 0 0 0 0; 0.000107526881720430 144 0 0 0 0 0; 0.000107526881720430 145 0 0 0 0 0; 0.000107526881720430 146 0 0 0 0 0; 0.000107526881720430 147 0 0 0 0 0; 0.000107526881720430 148 0 0 0 0 0; 0.000107526881720430 149 0 0 0 0 0; 0.000107526881720430 150 0 0 0 0 0; 0.000107526881720430 151 0 0 0 0 0; 0.000107526881720430 152 0 0 0 0 0; 0.000107526881720430 153 0 0 0 0 0; 0.000107526881720430 154 0 0 0 0 0; 0.000107526881720430 155 0 0 0 0 0; 0.000107526881720430 156 0 0 0 0 0; 0.000107526881720430 157 0 0 0 0 0; 0.000107526881720430 158 0 0 0 0 0; 0.000107526881720430 159 0 0 0 0 0; 0.000107526881720430 160 0 0 0 0 0; 0.000107526881720430 161 0 0 0 0 0; 0.000107526881720430 162 0 0 0 0 0; 0.000107526881720430 163 0 0 0 0 0; 0.000107526881720430 164 0 0 0 0 0; 0.000107526881720430 165 0 0 0 0 0; 0.000107526881720430 166 0 0 0 0 0; 0.000107526881720430 167 0 0 0 0 0; 0.000107526881720430 168 0 0 0 0 0; 0.000107526881720430 169 0 0 0 0 0; 0.000107526881720430 170 0 0 0 0 0; 0.000107526881720430 171 0 0 0 0 0; 0.000107526881720430 172 0 0 0 0 0; 0.000107526881720430 173 0 0 0 0 0; 0.000107526881720430 174 0 0 0 0 0; 0.000107526881720430 175 0 0 0 0 0; 0.000107526881720430 176 0 0 0 0 0; 0.000107526881720430 178 0 0 0 0 0; 0.000107526881720430 179 0 0 0 0 0; 0.000107526881720430 180 0 0 0 0 0; 0.000107526881720430 181 0 0 0 0 0; 0.000107526881720430 182 0 0 0 0 0; 0.000107526881720430 185 0 0 0 0 0; 0.000107526881720430 186 0 0 0 0 0; ]; % 0.000107526881720430 113 0 0 0 0 0; % 0.000107526881720430 133 0 0 0 0 0; % 0.000107526881720430 177 0 0 0 0 0; % 0.000107526881720430 183 0 0 0 0 0; % 0.000107526881720430 184 0 0 0 0 0; % mpc.contingencies = [ % 0.98 0 0 0 0 0 0; % 0.005 2 0 0 0 0 0; % 0.005 0 0 0 1 0 0; % 0.0025 1 0 0 1 0 0; % 0.0025 3 0 0 1 0 0; % ];
github
frederikgeth/PowerModelsReliability.jl-master
case5_tf.m
.m
PowerModelsReliability.jl-master/test/data/case5_tf.m
3,500
utf_8
12aaf471416cd06ee299b8ae433511cb
% NESTA v0.6.0 function mpc = nesta_case5_pjm mpc.version = '2'; mpc.baseMVA = 100.0; %% area data % area refbus mpc.areas = [ 1 4; ]; %% bus data % bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin mpc.bus = [ 1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000; 2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000; 3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000; 4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000; 5 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000; ]; %% generator data % bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf mpc.gen = [ 1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 5 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; ]; %column_names% prated qrated pref qref mpc.gen_rated = [ 40.0 30.0 40.0 30.0 170.0 127.5 170.0 127.5 520.0 390.0 324.498 390.0 200.0 150.0 0.0 -10.802 600.0 450.0 470.694 -165.039 ]; %% load data %column_names% load_bus pref qref status qmax qmin pmax pmin prated qrated voll mpc.tf_load = [ 1 0.0 0.0 1 0 0 0 0.0 0.0 0.0 5000.0; 2 300.0 98.61 1 98.61 0 300.0 0.0 300.0 98.61 5000.0; 3 300.0 98.61 1 98.61 0 300.0 0.0 300.0 98.61 5000.0; 4 400.0 131.47 1 131.47 0 400.0 0.0 400.0 131.47 5000.0; 5 0.0 0.0 1 0 0 0.0 0.0 0.0 0.0 5000.0; ]; %% generator cost data % 2 startup shutdown n c(n-1) ... c0 mpc.gencost = [ 2 0.0 0.0 3 0.000000 14.000000 0.000000; 2 0.0 0.0 3 0.000000 15.000000 0.000000; 2 0.0 0.0 3 0.000000 30.000000 0.000000; 2 0.0 0.0 3 0.000000 40.000000 0.000000; 2 0.0 0.0 3 0.000000 10.000000 0.000000; ]; %% branch data % fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax mpc.branch = [ 1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0; 1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0; 1 5 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0; 2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0; 3 4 0.00297 0.0297 0.00674 426 426 426 0.0 0.0 1 -30.0 30.0; 4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0; ]; %column_names% g_shunt shiftable shift_fr shift_to shift_fr_max shift_fr_min shift_to_max shift_to_min tappable tap_fr tap_to tap_fr_max tap_fr_min tap_to_max tap_to_min mpc.branch_variable_transformer = [ 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1.1 0.9 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; ];
github
frederikgeth/PowerModelsReliability.jl-master
case5_scopf.m
.m
PowerModelsReliability.jl-master/test/data/case5_scopf.m
3,745
utf_8
d440a3c168c5c7b48b400da449938110
% NESTA v0.6.0 function mpc = nesta_case5_pjm mpc.version = '2'; mpc.baseMVA = 100.0; %% area data % area refbus mpc.areas = [ 1 4; ]; %% bus data % bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin mpc.bus = [ 1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000; 2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000; 3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000; 4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000; 5 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000; ]; %% generator data % bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf mpc.gen = [ 1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 5 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; ]; %column_names% prated qrated pref qref mpc.gen_rated = [ 40.0 30.0 40.0 30.0 170.0 127.5 170.0 127.5 520.0 390.0 324.498 390.0 200.0 150.0 0.0 -10.802 600.0 450.0 470.694 -165.039 ]; %% load data %column_names% load_bus pref qref status qmax qmin pmax pmin prated qrated voll load_idx mpc.sc_load = [ 1 0.0 0.0 1 0 0 0 0.0 0.0 0.0 5000.0 1; 2 300.0 98.61 1 98.61 0 300.0 0.0 300.0 98.61 5000.0 2; 3 300.0 98.61 1 98.61 0 300.0 0.0 300.0 98.61 5000.0 4; 4 400.0 131.47 1 131.47 0 400.0 0.0 400.0 131.47 5000.0 6; 5 0.0 0.0 1 0 0 0.0 0.0 0.0 0.0 5000.0 7; ]; %% generator cost data % 2 startup shutdown n c(n-1) ... c0 mpc.gencost = [ 2 0.0 0.0 3 0.000000 14.000000 0.000000; 2 0.0 0.0 3 0.000000 15.000000 0.000000; 2 0.0 0.0 3 0.000000 30.000000 0.000000; 2 0.0 0.0 3 0.000000 40.000000 0.000000; 2 0.0 0.0 3 0.000000 10.000000 0.000000; ]; %% branch data % fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax mpc.branch = [ 1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0; 1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0; 1 5 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0; 2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0; 3 4 0.00297 0.0297 0.00674 426 426 426 0.0 0.0 1 -30.0 30.0; 4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0; ]; %column_names% g_shunt shiftable shift_fr shift_to shift_fr_max shift_fr_min shift_to_max shift_to_min tappable tap_fr tap_to tap_fr_max tap_fr_min tap_to_max tap_to_min mpc.branch_variable_transformer = [ 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1.1 0.9 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; ]; %column_names% prob branch_id1 branch_id2 branch_id3 gen_id1 gen_id2 gen_id3 mpc.contingencies = [ 0.98 0 0 0 0 0 0; 0.005 2 0 0 0 0 0; 0.005 0 0 0 1 0 0; 0.0025 1 0 0 1 0 0; 0.0025 3 0 0 1 0 0; ];
github
frederikgeth/PowerModelsReliability.jl-master
case5_scopf_load.m
.m
PowerModelsReliability.jl-master/test/data/case5_scopf_load.m
3,816
utf_8
b0fe0f418987daec60be5f36b88bb4ab
% NESTA v0.6.0 function mpc = nesta_case5_pjm mpc.version = '2'; mpc.baseMVA = 100.0; %% area data % area refbus mpc.areas = [ 1 4; ]; %% bus data % bus_i type Pd Qd Gs Bs area Vm Va baseKV zone Vmax Vmin mpc.bus = [ 1 2 0.0 0.0 0.0 0.0 1 1.07762 2.80377 230.0 1 1.10000 0.90000; 2 1 300.0 98.61 0.0 0.0 1 1.08407 -0.73465 230.0 1 1.10000 0.90000; 3 2 300.0 98.61 0.0 0.0 1 1.10000 -0.55972 230.0 1 1.10000 0.90000; 4 3 400.0 131.47 0.0 0.0 1 1.06414 0.00000 230.0 1 1.10000 0.90000; 5 2 0.0 0.0 0.0 0.0 1 1.06907 3.59033 230.0 1 1.10000 0.90000; ]; %% generator data % bus Pg Qg Qmax Qmin Vg mBase status Pmax Pmin Pc1 Pc2 Qc1min Qc1max Qc2min Qc2max ramp_agc ramp_10 ramp_30 ramp_q apf mpc.gen = [ 1 40.0 30.0 30.0 -30.0 1.07762 100.0 1 40.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 1 170.0 127.5 127.5 -127.5 1.07762 100.0 1 170.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 3 324.498 390.0 390.0 -390.0 1.1 100.0 1 520.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 4 0.0 -10.802 150.0 -150.0 1.06414 100.0 1 200.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; 5 470.694 -165.039 450.0 -450.0 1.06907 100.0 1 600.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0; ]; %column_names% prated qrated pref qref mpc.gen_rated = [ 40.0 30.0 40.0 30.0 170.0 127.5 170.0 127.5 520.0 390.0 324.498 390.0 200.0 150.0 0.0 -10.802 600.0 450.0 470.694 -165.039 ]; %% load data %column_names% load_bus pref qref status qmax qmin pmax pmin prated qrated voll load_idx mpc.sc_load = [ 1 0.0 0.0 1 0 0 0 0.0 0.0 0.0 5000.0 1; 2 150.0 49.0 1 49.0 0 150.0 0.0 150.0 49.0 5000.0 2; 2 150.0 49.0 1 49.0 0 150.0 0.0 150.0 49.0 10000.0 3; 3 300.0 98.61 1 98.61 0 300.0 0.0 300.0 98.61 5000.0 4; 4 400.0 131.47 1 131.47 0 400.0 0.0 400.0 131.47 5000.0 6; 5 0.0 0.0 1 0 0 0.0 0.0 0.0 0.0 5000.0 7; ]; %% generator cost data % 2 startup shutdown n c(n-1) ... c0 mpc.gencost = [ 2 0.0 0.0 3 0.000000 14.000000 0.000000; 2 0.0 0.0 3 0.000000 15.000000 0.000000; 2 0.0 0.0 3 0.000000 30.000000 0.000000; 2 0.0 0.0 3 0.000000 40.000000 0.000000; 2 0.0 0.0 3 0.000000 10.000000 0.000000; ]; %% branch data % fbus tbus r x b rateA rateB rateC ratio angle status angmin angmax mpc.branch = [ 1 2 0.00281 0.0281 0.00712 400.0 400.0 400.0 0.0 0.0 1 -30.0 30.0; 1 4 0.00304 0.0304 0.00658 426 426 426 0.0 0.0 1 -30.0 30.0; 1 5 0.00064 0.0064 0.03126 426 426 426 0.0 0.0 1 -30.0 30.0; 2 3 0.00108 0.0108 0.01852 426 426 426 0.0 0.0 1 -30.0 30.0; 3 4 0.00297 0.0297 0.00674 426 426 426 0.0 0.0 1 -30.0 30.0; 4 5 0.00297 0.0297 0.00674 240.0 240.0 240.0 0.0 0.0 1 -30.0 30.0; ]; %column_names% g_shunt shiftable shift_fr shift_to shift_fr_max shift_fr_min shift_to_max shift_to_min tappable tap_fr tap_to tap_fr_max tap_fr_min tap_to_max tap_to_min mpc.branch_variable_transformer = [ 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; 0 0 0 0 30 -30 0 0 0 1 1 1 1 1 1; 0 0 0 0 0 0 0 0 0 1 1 1.1 0.9 1 1; 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1; ]; %column_names% prob branch_id1 branch_id2 branch_id3 gen_id1 gen_id2 gen_id3 mpc.contingencies = [ 0.98 0 0 0 0 0 0; 0.005 2 0 0 0 0 0; 0.005 0 0 0 1 0 0; 0.0025 1 0 0 1 0 0; 0.0025 3 0 0 1 0 0; ];
github
zhichaowang/kaldi-master
Generate_mcTrainData_cut.m
.m
kaldi-master/egs/reverb/s5/local/Generate_mcTrainData_cut.m
7,311
utf_8
f59dd892f0f8da04a515a2c58ff50a69
function Generate_mcTrainData_cut(WSJ_dir_name, save_dir) % % Input variables: % WSJ_dir_name: string name of user's clean wsjcam0 corpus directory % (*Directory structure for wsjcam0 corpushas to be kept as it is after obtaining it from LDC. % Otherwise this script does not work.) % % This function generates multi-condition traiing data % based on the following items: % 1. wsjcam0 corpus (distributed from the LDC) % 2. room impulse responses (ones under ./RIR/) % 3. noise (ones under ./NOISE/). % Generated data has the same directory structure as original wsjcam0 corpus. % if nargin<2 error('Usage: Generate_mcTrainData(WSJCAM0_data_path, save_dir) *Note that the input variable WSJCAM0_data_path should indicate the directory name of your clean WSJCAM0 corpus. '); end if exist([WSJ_dir_name,'/data/'])==0 error(['Could not find wsjcam0 corpus : Please confirm if ',WSJ_dir_name,' is a correct path to your clean WSJCAM0 corpus']); end if ~exist('save_dir', 'var') error('You have to set the save_dir variable in the code before running this script!') end display(['Name of directory for original wsjcam0: ',WSJ_dir_name]) display(['Name of directory to save generated multi-condition training data: ',save_dir]) unix(['chmod u+x sphere_to_wave.csh']); unix(['chmod u+x bin/*']); % Parameters related to acoustic conditions SNRdB=20; % List of WSJ speech data flist1='etc/audio_si_tr.lst'; % % List of RIRs % num_RIRvar=24; RIR_sim1='./RIR/RIR_SmallRoom1_near_AnglA.wav'; RIR_sim2='./RIR/RIR_SmallRoom1_near_AnglB.wav'; RIR_sim3='./RIR/RIR_SmallRoom1_far_AnglA.wav'; RIR_sim4='./RIR/RIR_SmallRoom1_far_AnglB.wav'; RIR_sim5='./RIR/RIR_MediumRoom1_near_AnglA.wav'; RIR_sim6='./RIR/RIR_MediumRoom1_near_AnglB.wav'; RIR_sim7='./RIR/RIR_MediumRoom1_far_AnglA.wav'; RIR_sim8='./RIR/RIR_MediumRoom1_far_AnglB.wav'; RIR_sim9='./RIR/RIR_LargeRoom1_near_AnglA.wav'; RIR_sim10='./RIR/RIR_LargeRoom1_near_AnglB.wav'; RIR_sim11='./RIR/RIR_LargeRoom1_far_AnglA.wav'; RIR_sim12='./RIR/RIR_LargeRoom1_far_AnglB.wav'; RIR_sim13='./RIR/RIR_SmallRoom2_near_AnglA.wav'; RIR_sim14='./RIR/RIR_SmallRoom2_near_AnglB.wav'; RIR_sim15='./RIR/RIR_SmallRoom2_far_AnglA.wav'; RIR_sim16='./RIR/RIR_SmallRoom2_far_AnglB.wav'; RIR_sim17='./RIR/RIR_MediumRoom2_near_AnglA.wav'; RIR_sim18='./RIR/RIR_MediumRoom2_near_AnglB.wav'; RIR_sim19='./RIR/RIR_MediumRoom2_far_AnglA.wav'; RIR_sim20='./RIR/RIR_MediumRoom2_far_AnglB.wav'; RIR_sim21='./RIR/RIR_LargeRoom2_near_AnglA.wav'; RIR_sim22='./RIR/RIR_LargeRoom2_near_AnglB.wav'; RIR_sim23='./RIR/RIR_LargeRoom2_far_AnglA.wav'; RIR_sim24='./RIR/RIR_LargeRoom2_far_AnglB.wav'; % % List of noise % num_NOISEvar=6; noise_sim1='./NOISE/Noise_SmallRoom1'; noise_sim2='./NOISE/Noise_MediumRoom1'; noise_sim3='./NOISE/Noise_LargeRoom1'; noise_sim4='./NOISE/Noise_SmallRoom2'; noise_sim5='./NOISE/Noise_MediumRoom2'; noise_sim6='./NOISE/Noise_LargeRoom2'; % % Start generating noisy reverberant data with creating new directories % fcount=1; rcount=1; ncount=1; if save_dir(end)=='/'; save_dir_tr=[save_dir,'data/mc_train/']; else save_dir_tr=[save_dir,'/data/mc_train/']; end mkdir([save_dir_tr]); %mkdir([save_dir,'/taskfiles/']) mic_idx=['A';'B';'C';'D';'E';'F';'G';'H']; prev_fname='dummy'; for nlist=1:1 % Open file list eval(['fid=fopen(flist',num2str(nlist),',''r'');']); while 1 % Set data file name fname=fgetl(fid); if ~ischar(fname); break; end idx1=find(fname=='/'); % Make directory if there isn't any if ~strcmp(prev_fname,fname(1:idx1(end))) mkdir([save_dir_tr fname(1:idx1(end))]) end prev_fname=fname(1:idx1(end)); % load (sphere format) speech signal x=read_sphere([WSJ_dir_name,'/data/', fname]); x=x/(2^15); % conversion from short-int to float % load RIR and noise for "THIS" utterance eval(['RIR=wavread(RIR_sim',num2str(rcount),');']); eval(['NOISE=wavread([noise_sim',num2str(ceil(rcount/4)),',''_',num2str(ncount),'.wav'']);']); % Generate 8ch noisy reverberant data y=gen_obs(x,RIR,NOISE,SNRdB); % cut to length of original signal y = y(1:size(x,2),:); % rotine to cyclicly switch RIRs and noise, utterance by utterance rcount=rcount+1; if rcount>num_RIRvar;rcount=1;ncount=ncount+1;end if ncount>10;ncount=1;end % save the data y=y/4; % common normalization to all the data to prevent clipping % denominator was decided experimentally for ch=1:8 eval(['wavwrite(y(:,',num2str(ch),'),16000,''',save_dir_tr fname,'_ch',num2str(ch),'.wav'');']); end display(['sentence ',num2str(fcount),' (out of 7861) finished! (Multi-condition training data)']) fcount=fcount+1; end end %%%% function [y]=gen_obs(x,RIR,NOISE,SNRdB) % function to generate noisy reverberant data x=x'; % calculate direct+early reflection signal for calculating SNR [val,delay]=max(RIR(:,1)); before_impulse=floor(16000*0.001); after_impulse=floor(16000*0.05); RIR_direct=RIR(delay-before_impulse:delay+after_impulse,1); direct_signal=fconv(x,RIR_direct); % obtain reverberant speech for ch=1:8 rev_y(:,ch)=fconv(x,RIR(:,ch)); end % normalize noise data according to the prefixed SNR value NOISE=NOISE(1:size(rev_y,1),:); NOISE_ref=NOISE(:,1); iPn = diag(1./mean(NOISE_ref.^2,1)); Px = diag(mean(direct_signal.^2,1)); Msnr = sqrt(10^(-SNRdB/10)*iPn*Px); scaled_NOISE = NOISE*Msnr; y = rev_y + scaled_NOISE; y = y(delay:end,:); %%%% function [y]=fconv(x, h) %FCONV Fast Convolution % [y] = FCONV(x, h) convolves x and h, and normalizes the output % to +-1. % % x = input vector % h = input vector % % See also CONV % % NOTES: % % 1) I have a short article explaining what a convolution is. It % is available at http://stevem.us/fconv.html. % % %Version 1.0 %Coded by: Stephen G. McGovern, 2003-2004. % %Copyright (c) 2003, Stephen McGovern %All rights reserved. % %THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" %AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE %IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE %ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE %LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR %CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF %SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS %INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN %CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) %ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE %POSSIBILITY OF SUCH DAMAGE. Ly=length(x)+length(h)-1; % Ly2=pow2(nextpow2(Ly)); % Find smallest power of 2 that is > Ly X=fft(x, Ly2); % Fast Fourier transform H=fft(h, Ly2); % Fast Fourier transform Y=X.*H; % y=real(ifft(Y, Ly2)); % Inverse fast Fourier transform y=y(1:1:Ly); % Take just the first N elements
github
yihui-he/reconstructing-pascal-voc-master
montage_new.m
.m
reconstructing-pascal-voc-master/external_src/montage_new.m
12,139
utf_8
0bbddfdad558a03de80a4e5889f64ca9
function handles = montage_new(I, titles, varargin) %MONTAGE Display multiple images as a montage of subplots % Changed by Joao Carreira to be able to include titles (cell array of % strings) % % Examples: % montage % montage(I) % montage(I, map) % montage(..., param1, value1, param2, value2, ...) % % This function displays multiple images, in a stack or cell array or % defined by filenames in a cell array or simply in the current directory, % in a grid of subplots in the current figure. % % The size of grid is calculated or user defined. Images not fitting in the % grid can be scrolled through using the scroll keys. This allows fast % scrolling through a movie or image stack, e.g. % montage(imstack, 'Size', 1) % creates a single frame montage with images scrolled through using arrow % keys. % % This function is designed to replace the MONTAGE function provided with % the Image Processing Toolbox (IPT). It is syntax compatible, but operates % differently, and while results are generally comparable given identical % syntaxes, this is not guaranteed. % % Differences from the IPT version are: % - The IPT is not required! % - Images are placed in subplots, so can be zoomed separately. % - Small images are properly enlarged on screen. % - Gaps can be placed between images. % - Images can be viewed on a grid smaller than the number of images. % - Surplus images can be viewed by scrolling through pages. % - A directory of images can be viewed easily. % - It cannot return an image handle (as there are multiple images) % % Keys: % Up - Back a row. % Down - Forward a row. % Left - Back a page (or column if there is only one row). % Right - Forward a page (or column if there is only one row). % Shift - 2 x speed. % Ctrl - 4 x speed. % Shift + Ctrl - 8 x speed. % % IN: % I - MxNxCxP array of images, or 1xP cell array. C is 1 for indexed % images or 3 for RGB images. P is the number of images. If I is a % cell array then each cell must contain an image or image filename. % If I is empty then all the images in the current directory are % used. Default: []. % map - Kx3 colormap to be used with indexed images. Default: gray(256). % Optional parameters - name, value parameter pairs for the following: % 'Size' - [H W] size of grid to display image on. If only H is given % then W = H. If either H or W is NaN then the number of rows % or columns is chosen such that all images fit. If both H % and W are NaN or the array is empty then the size of grid % is chosen to fit all images in as large as possible. % Default: []. % 'Indices' - 1xL list of indices of images to display. Default: 1:P. % 'Border' - [B R] borders to give each image top and bottom (B) and % left and right (R), to space out images. Borders are % normalized to the subplot size, i.e. B = 0.01 gives a border % 1% of the height of each subplot. If only B is given, R = % B. Default: 0.01. % 'DisplayRange' - [LOW HIGH] display range for indexed images. % Default: [min(I(:)) max(I(:))]. % 'Map' - Kx3 colormap or (additionally from above) name of MATLAB % colormap, for use with indexed images. Default: gray(256). % $Id: montage.m,v 1.7 2009/02/25 16:39:01 ojw Exp $ % Parse inputs [map layout gap indices lims] = parse_inputs(varargin); if nargin == 0 || isempty(I) % Read in all the images in the directory I = get_im_names; if isempty(I) % No images found return end end if isnumeric(I) [y x c n] = size(I); if isempty(lims) lims = [min(reshape(I, numel(I), 1)) max(reshape(I, numel(I), 1))]; elseif isequal(0, lims) lims = default_limits(I); end if isfloat(I) && c == 3 I = uint8(I * 256 - 0.5); lims = round(lims * 256 - 0.5); end I = squeeze(num2cell(I, [1 2 3])); elseif iscell(I) A = I{1}; if ischar(A) A = imread_rgb(A); I{1} = A; end n = numel(I); % Assume all images are the same size and type as the first [y x c] = size(A); if isempty(lims) || isequal(0, lims) lims = default_limits(A); end else error('I not of recognized type.'); end % Select indexed images if ~isequal(indices, -1) I = I(indices); n = numel(I); end % Compute a good layout layout = choose_layout(n, y, x, layout); % Create a data structure to store the data in num = prod(layout); state.n = num * ceil(n / num); state.h = zeros(layout); I = [I(:); cell(state.n-n, 1)]; % Get and clear the figure fig = gcf; clf(fig); % Set the figure size well MonSz = get(0, 'ScreenSize'); MaxSz = MonSz(3:4) - [20 120]; %MaxSz = MonSz(3:4) + 10*[20 120]; ImSz = layout([2 1]) .* [x y] ./ (1 - 2 * gap([end 1])); RescaleFactor = min(MaxSz ./ ImSz); if RescaleFactor > 1 % Integer scale for enlarging, but don't make too big MaxSz = min(MaxSz, [1000 680]); RescaleFactor = max(floor(min(MaxSz ./ ImSz)), 1); end figPosNew = ceil(ImSz * RescaleFactor); % Don't move the figure if the size isn't changing figPosCur = get(fig, 'Position'); if ~isequal(figPosCur(3:4), figPosNew) % Keep the centre of the figure stationary figPosNew = [max(1, floor(figPosCur(1:2)+(figPosCur(3:4)-figPosNew)/2)) figPosNew]; % Ensure the figure bar is in bounds figPosNew(1:2) = min(figPosNew(1:2), MonSz(1:2)+MonSz(3:4)-[6 101]-figPosNew(3:4)); set(fig, 'Position', figPosNew); end % Set the colourmap colormap(map); % Set the first lot of images index = mod(0:num-1, state.n) + 1; hw = 1 ./ layout; gap = gap ./ layout; dims = hw - 2 * gap; dims = dims([2 1]); counter = 1; for a = 1:layout(1) for b = 1:layout(2) c(counter) = index(b + (layout(1) - a) * layout(2)); A = I{c(counter)}; if ischar(A) A = imread_rgb(A); I{c} = A; end handles(counter)= subplot('Position', [(b-1)*hw(2)+gap(2) (a-1)*hw(1)+gap(1) dims]); counter = counter + 1; if isempty(A) state.h(a,b) = imagesc(zeros(1, 1, 3), lims); axis image off; set(state.h(a,b), 'CData', []); handles(counter-1) = []; c(counter-1) = []; counter = counter - 1; else state.h(a,b) = imagesc(A, lims); axis image off; if(nargin>=2 && ~isempty(titles)) title(titles{c(end)}, 'FontSize', 15); set(get(handles(b), 'Title'), 'VerticalAlignment', 'baseline'); set(get(handles(b), 'XLabel'), 'VerticalAlignment', 'baseline'); end end end end [s_c, ids] = sort(c); handles = handles(ids); drawnow; figure(fig); % Bring the montage into view % Check if we need to be able to scroll through images if n > num % Intialize rest of data structure state.index = 1; state.layout = layout; state.I = I; % Set the callback for image navigation, and save the image data in the figure set(fig, 'KeyPressFcn', @keypress_callback, 'Interruptible', 'off', 'UserData', state); end return %% Keypress callback % The function which does all the display stuff function keypress_callback(fig, event_data) % Check what key was pressed and update the image index as necessary switch event_data.Character case 28 % Left up = -1; % Back a page case 29 % Right up = 1; % Forward a page case 30 % Up up = -0.1; % Back a row case 31 % Down up = 0.1; % Forward a row otherwise % Another key was pressed - ignore it return end % Use control and shift for faster scrolling if ~isempty(event_data.Modifier) up = up * (2 ^ (strcmpi(event_data.Modifier, {'shift', 'control'}) * [1; 2])); end % Get the state data, if not given state = get(fig, 'UserData'); % Get the current index index = state.index; % Get number of images n = prod(state.layout); % Generate 12 valid indices if abs(up) < 1 % Increment by row index = index + state.layout(2) * (up * 10) - 1; else if state.layout(1) == 1 % Increment by column index = index + up - 1; else % Increment by page index = index + n * up - 1; end end index = mod(index:index+n, state.n) + 1; % Plot the images figure(fig); for a = 1:state.layout(1) for b = 1:state.layout(2) c = index(b + (state.layout(1) - a) * state.layout(2)); A = state.I{c}; if ischar(A) A = imread_rgb(A); state.I{c} = A; end set(state.h(a,b), 'CData', A); end end drawnow; % Save the current index state.index = index(1); set(fig, 'UserData', state); return %% Choose a good layout for the images function layout = choose_layout(n, y, x, layout) layout = reshape(layout, 1, min(numel(layout), 2)); v = numel(layout); N = isnan(layout); if v == 0 || all(N) sz = get(0, 'ScreenSize'); sz = sz(3:4) ./ [x y]; layout = ceil(sz([2 1]) ./ sqrt(prod(sz) / n)); switch ([prod(layout - [1 0]) prod(layout - [0 1])] >= n) * [2; 1] case 0 case 1 layout = layout - [0 1]; case 2 layout = layout - [1 0]; case 3 if min(sz .* (layout - [0 1])) > min(sz .* (layout - [1 0])) layout = layout - [0 1]; else layout = layout - [1 0]; end end elseif v == 1 layout = layout([1 1]); elseif any(N) layout(N) = ceil(n / layout(~N)); end return %% Read image to uint8 rgb array function A = imread_rgb(name) try [A map] = imread(name); catch % Format not recognized by imread, so create a red cross (along diagonals) A = eye(101) | diag(ones(100, 1), 1) | diag(ones(100, 1), -1); A = uint8(255 * (1 - (A | flipud(A)))); A = cat(3, zeros(size(A), 'uint8')+uint8(255), A, A); return end if ~isempty(map) map = uint8(map * 256 - 0.5); A = reshape(map(A,:), [size(A) size(map, 2)]); elseif size(A, 3) == 4 ll = lower(name(end)); if ll == 'f' % TIFF in CMYK colourspace - convert to RGB error('CMYK image files not yet supported - please fix.'); elseif ll == 's' % RAS in RGBA colourspace - convert to RGB error('RGBA image files not yet supported - please fix.'); end end return %% Get the names of all images in a directory function L = get_im_names D = dir; n = 0; L = cell(size(D)); % Go through the directory list for a = 1:numel(D) % Check if file is a supported image type if numel(D(a).name) > 4 && ~D(a).isdir && (any(strcmpi(D(a).name(end-3:end), {'.png', '.tif', '.jpg', '.bmp', '.ppm', '.pgm', '.pbm', '.gif', '.ras'})) || any(strcmpi(D(a).name(end-4:end), {'.tiff', '.jpeg'}))) n = n + 1; L{n} = D(a).name; end end L = L(1:n); return %% Parse inputs function [map layout gap indices lims] = parse_inputs(inputs) % Set defaults map = gray(256); layout = []; gap = 0.01; indices = -1; lims = 0; % Check for map if numel(inputs) && isnumeric(inputs{1}) && size(inputs{1}, 2) == 3 map = inputs{1}; inputs = inputs(2:end); end % Go through option pairs for a = 1:2:numel(inputs) switch lower(inputs{a}) case 'map' map = inputs{a+1}; if ischar(map) map = eval([map '(256)']); end case {'size', 'grid'} layout = inputs{a+1}; case {'gap', 'border'} gap = inputs{a+1}; case 'indices' indices = inputs{a+1}; case {'lims', 'displayrange'} lims = inputs{a+1}; otherwise error('Input option %s not recognized', inputs{a}); end end return %% Return default limits for the image type function lims = default_limits(A) if size(A, 3) == 1 lims = [min(reshape(A, numel(A), 1)) max(reshape(A, numel(A), 1))]; else lims = [0 1]; if ~isfloat(A) lims = lims * double(intmax(class(A))); end end return
github
yihui-he/reconstructing-pascal-voc-master
parseXML.m
.m
reconstructing-pascal-voc-master/external_src/parseXML.m
2,107
utf_8
ecc51819782827aa19e181f13cc7a1cc
function theStruct = parseXML(filename) % PARSEXML Convert XML file to a MATLAB structure. try tree = xmlread(filename); catch error('Failed to read XML file %s.',filename); end % Recurse over child nodes. This could run into problems % with very deeply nested trees. try theStruct = parseChildNodes(tree); catch error('Unable to parse XML file %s.',filename); end % ----- Subfunction PARSECHILDNODES ----- function children = parseChildNodes(theNode) % Recurse over node children. children = []; if theNode.hasChildNodes childNodes = theNode.getChildNodes; numChildNodes = childNodes.getLength; allocCell = cell(1, numChildNodes); children = struct( ... 'Name', allocCell, 'Attributes', allocCell, ... 'Data', allocCell, 'Children', allocCell); for count = 1:numChildNodes theChild = childNodes.item(count-1); children(count) = makeStructFromNode(theChild); end %to_remove = arrayfun(@(a) strcmp(a.Name, '#text'), children); %children(to_remove) = []; end % ----- Subfunction MAKESTRUCTFROMNODE ----- function nodeStruct = makeStructFromNode(theNode) % Create structure of node info. nodeStruct = struct( ... 'Name', char(theNode.getNodeName), ... 'Attributes', parseAttributes(theNode), ... 'Data', '', ... 'Children', parseChildNodes(theNode)); if any(strcmp(methods(theNode), 'getData')) nodeStruct.Data = char(theNode.getData); else nodeStruct.Data = ''; end % ----- Subfunction PARSEATTRIBUTES ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = []; if theNode.hasAttributes theAttributes = theNode.getAttributes; numAttributes = theAttributes.getLength; allocCell = cell(1, numAttributes); attributes = struct('Name', allocCell, 'Value', ... allocCell); for count = 1:numAttributes attrib = theAttributes.item(count-1); attributes(count).Name = char(attrib.getName); attributes(count).Value = char(attrib.getValue); end end
github
yihui-he/reconstructing-pascal-voc-master
SvmSegm_show_best_segments.m
.m
reconstructing-pascal-voc-master/external_src/SvmSegm_show_best_segments.m
825
utf_8
e486320500066ff0bb4543e0fef15585
%function SvmSegm_show_best_segments(I, Q, masks) % I is the image % Q is the qualities of each segment (find the file in SegmentEval folder) % masks are the computed segments function [best, max_score, best_seg_id] = SvmSegm_show_best_segments(I, Q, masks, n) DefaultVal('*n', '1'); if(iscell(Q)) Q = Q{1}; end for i=1:numel(Q) if(n~=1) [max_score{i}, best_seg_id{i}] = sort(Q(i).q, 'descend'); best_seg_id{i} = best_seg_id{i}(1:n); tit = []; else [max_score(i), best_seg_id(i)] = max(Q(i).q); tit{i} = sprintf('%f', Q(i).q(best_seg_id(i))); end end if(iscell(best_seg_id)) best_seg_id = cell2mat(best_seg_id); max_score = cell2mat(max_score); end best = subplot_auto_transparent(masks(:,:,best_seg_id), I, tit); %figure; %sc(seg, 'rand') end
github
yihui-he/reconstructing-pascal-voc-master
myCalcCandScoreFigureGroundAll.m
.m
reconstructing-pascal-voc-master/external_src/myCalcCandScoreFigureGroundAll.m
4,625
utf_8
7c7df819fd640b0633d87d97561e43e1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate the F-score of the evaluated method % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % best_s is the filename of the best figure-ground segmentation (needs to % be binary!!!) Only considers the segment with label 0 %%% P and R are ignored, the score is in F function [P R F]=myCalcCandScoreFigureGroundAll(Segmaps,HumanSeg, type, care) Fmax=0; F = zeros(size(Segmaps,3),1); P = F; R = F; if(strcmp(type, 'overlap_and_bbox_edges') || strcmp(type, 'overlap_action')) % do a priori computation bb_human = compute_bbox(HumanSeg)'; bb_segms = zeros(size(Segmaps,3),4); for i=1:size(Segmaps,3) bbox = compute_bbox(Segmaps(:,:,i))'; if(~isempty(bbox)) bb_segms(i,:) = bbox; else bb_segms(i,:) = [-1 -1 1 1]; end end end gt_img_fraction = sum(sum(HumanSeg)) /numel(HumanSeg); for i=1:size(Segmaps,3) FragMap = Segmaps(:,:,i); if(strcmp(type, 'fmeasure')) [p r f]=CalcPRPixel(HumanSeg,FragMap, care);%Calculate the F-score elseif(strcmp(type, 'overlap')) [p r f]=CalcOverlap(HumanSeg,FragMap, care);%Calculate the overlap, puts it in f elseif(strcmp(type, 'intersection')) [p r f]=CalcIntersection(HumanSeg,FragMap, care);%Calculate the overlap, puts it in f elseif(strcmp(type, 'inter_over_area')) [p r f]=CalcIntersectionOverArea(HumanSeg,FragMap, care);%Calculate the overlap, puts it in f elseif(strcmp(type, 'overlap_and_bbox_edges') || strcmp(type, 'overlap_action')) [p r f] = CalcOverlapBBoxEdges(HumanSeg, FragMap, bb_human, bb_segms(i,:), care); elseif(strcmp(type, 'overlap_times_area_fraction')) [p r f]=CalcOverlap(HumanSeg,FragMap, care);%Calculate the overlap, puts it in f % now multiple by area fraction f = f*gt_img_fraction; end F(i)=f; P(i)=p; R(i)=r; end;%Go over all segmentations in the Dir end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % (ADAPTED FROM WEIZMANN DATABASE CODE) Calculate the F-score % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [p r f]=CalcPRPixel(GT,mask, care) if(exist('care', 'var')) error('not ready yet, code this!'); end % CARREIRA if if(size(GT,3) == 3) GT = GT(:,:,1); end sum_GT_and_mask = sum(GT(:)&mask(:)); if (sum_GT_and_mask==0) p=0;r=0;f=0; return; end; r=sum_GT_and_mask./sum(GT(:)); c=sum(mask(:))-sum_GT_and_mask; p=sum_GT_and_mask./(sum_GT_and_mask+c); f=(r*p)/(0.5*(r+p)); end %%%%%%%%%%%%%%%%%%%%%%%%%% Overlap %%%%%%%%%%%%%%%%%%%%%%% function [p, r, f] = CalcIntersection(GT, mask, care) p = -1; r = -1; f = sum(sum(GT & mask & care)); end function [p, r, f] = CalcIntersectionOverArea(GT, mask, care) p = -1; r = -1; f = sum(sum(GT & mask & care)) / sum(mask(:)); end function [p, r, f] = CalcOverlap(GT, mask, care) p = -1; r = -1; f = sum(sum(GT & mask & care)) / sum(sum((GT | mask) & care)); end function [p, r, f] = CalcOverlapBBoxEdges(GT, mask, bb_gt, bb_mask, care) p = -1; r = -1; if(~isempty(bb_gt)) width_gt = bb_gt(3); height_gt = bb_gt(4); inters = rectint(bb_gt, bb_mask); else width_gt = 0; height_gt = 0; inters = 0; end width_mask = bb_mask(3); height_mask = bb_mask(4); area_bb_gt = width_gt*height_gt; area_mask = width_mask*height_mask; reun = (area_bb_gt+area_mask - inters); f = inters/reun; % min_x_gt = bb_gt(1); % max_x_gt = bb_gt(1)+bb_gt(3); % min_y_gt = bb_gt(2); % max_y_gt = bb_gt(2) + bb_gt(4); % % % min_x_mask = bb_mask(1); % max_x_mask = bb_mask(1) + bb_mask(3); % min_y_mask = bb_mask(2); % max_y_mask = bb_mask(2) + bb_mask(4); % % diffs(1) = abs(min_x_mask - min_x_gt) / width_mask; % diffs(2) = abs(max_x_mask - max_x_gt ) / width_mask; % diffs(3) = abs(min_y_mask - min_y_gt ) / height_mask; % diffs(4) = abs(max_y_mask - max_y_gt ) / height_mask; % % f = mean(diffs); %%% visualization %%% %showboxes(GT*255, [bb_gt(1) bb_gt(2) bb_gt(1) + bb_gt(3) bb_gt(2) + bb_gt(4)]) %showboxes(mask(:,:,1)*255, [bb_mask(1,1) bb_mask(1, 2) bb_mask(1,1) + bb_mask(1,3) bb_mask(1,2) + bb_mask(1,4)]) end
github
yihui-he/reconstructing-pascal-voc-master
DefaultVal.m
.m
reconstructing-pascal-voc-master/external_src/DefaultVal.m
1,258
utf_8
518947d797d61092d4e16bd1b3ba1e27
% Function written by Dr. Adrian Ion % % This code is part of the extended implementation of the paper: % % J. Carreira, C. Sminchisescu, Constrained Parametric Min-Cuts for Automatic Object Segmentation, IEEE CVPR 2010 % function DefaultVal(varargin) % assign default values to variables if they do not exist or are empty % % use string pairs 'var', 'value' % preceede the variable name with a '*' to set also it empty % % % e.g. DefaultVal('p1', '1', '*p2', '2'); % % will create p1 = 1 if it does not exist in the current scope % will create or set p2 = 2 if it does not exist, or it is empty assert(mod(nargin,2) == 0); for i=1:2:nargin if ~ischar(varargin{i}) || length(varargin{i})<1 || ~ischar(varargin{i+1}) length(varargin{i+1})<1 error('Bad parameters passed to function. See function help.'); end if (varargin{i}(1)=='*') cmd = sprintf('if ~exist(''%s'',''var'') || isempty(%s) %s = %s; end', varargin{i}(2:end), varargin{i}(2:end), varargin{i}(2:end), varargin{i+1}); else cmd = sprintf('if ~exist(''%s'',''var'') %s = %s; end', varargin{i}, varargin{i}, varargin{i+1}); end evalin('caller', cmd, 'error(''Requires and even number of (string names of possibly missing) variables & values'')') ; end end
github
yihui-he/reconstructing-pascal-voc-master
VOCevalseg.m
.m
reconstructing-pascal-voc-master/external_src/VOCcode/VOCevalseg.m
3,238
utf_8
454757a787993ac892eb5dc277abc04d
%VOCEVALSEG Evaluates a set of segmentation results. % VOCEVALSEG(VOCopts,ID); prints out the per class and overall % segmentation accuracies. Accuracies are given using the intersection/union % metric: % true positives / (true positives + false positives + false negatives) % % [ACCURACIES,AVACC,CONF] = VOCEVALSEG(VOCopts,ID) returns the per class % percentage ACCURACIES, the average accuracy AVACC and the confusion % matrix CONF. % % [ACCURACIES,AVACC,CONF,RAWCOUNTS] = VOCEVALSEG(VOCopts,ID) also returns % the unnormalised confusion matrix, which contains raw pixel counts. function [accuracies,avacc,conf,rawcounts] = VOCevalseg(VOCopts,id) % image test set [gtids,t]=textread(sprintf(VOCopts.seg.imgsetpath,VOCopts.testset),'%s %d'); % number of labels = number of classes plus one for the background num = VOCopts.nclasses+1; confcounts = zeros(num); count=0; tic; for i=1:length(gtids) % display progress if toc>1 fprintf('test confusion: %d/%d\n',i,length(gtids)); drawnow; tic; end imname = gtids{i}; % ground truth label file gtfile = sprintf(VOCopts.seg.clsimgpath,imname); [gtim,map] = imread(gtfile); gtim = double(gtim); % results file resfile = sprintf(VOCopts.seg.clsrespath,id,VOCopts.testset,imname); [resim,map] = imread(resfile); resim = double(resim); % Check validity of results image maxlabel = max(resim(:)); if (maxlabel>VOCopts.nclasses), error('Results image ''%s'' has out of range value %d (the value should be <= %d)',imname,maxlabel,VOCopts.nclasses); end szgtim = size(gtim); szresim = size(resim); if any(szgtim~=szresim) error('Results image ''%s'' is the wrong size, was %d x %d, should be %d x %d.',imname,szresim(1),szresim(2),szgtim(1),szgtim(2)); end %pixel locations to include in computation locs = gtim<255; % joint histogram sumim = 1+gtim+resim*num; hs = histc(sumim(locs),1:num*num); count = count + numel(find(locs)); confcounts(:) = confcounts(:) + hs(:); end % confusion matrix - first index is true label, second is inferred label %conf = zeros(num); conf = 100*confcounts./repmat(1E-20+sum(confcounts,2),[1 size(confcounts,2)]); rawcounts = confcounts; % Percentage correct labels measure is no longer being used. Uncomment if % you wish to see it anyway %overall_acc = 100*sum(diag(confcounts)) / sum(confcounts(:)); %fprintf('Percentage of pixels correctly labelled overall: %6.3f%%\n',overall_acc); accuracies = zeros(VOCopts.nclasses,1); fprintf('Accuracy for each class (intersection/union measure)\n'); for j=1:num gtj=sum(confcounts(j,:)); resj=sum(confcounts(:,j)); gtjresj=confcounts(j,j); % The accuracy is: true positive / (true positive + false positive + false negative) % which is equivalent to the following percentage: accuracies(j)=100*gtjresj/(gtj+resj-gtjresj); clname = 'background'; if (j>1), clname = VOCopts.classes{j-1};end; fprintf(' %14s: %6.3f%%\n',clname,accuracies(j)); end accuracies = accuracies(1:end); avacc = mean(accuracies); fprintf('-------------------------\n'); fprintf('Average accuracy: %6.3f%%\n',avacc);
github
yihui-he/reconstructing-pascal-voc-master
VOClabelcolormap.m
.m
reconstructing-pascal-voc-master/external_src/VOCcode/VOClabelcolormap.m
669
utf_8
565f5eb4134900aa85056d6becc880f5
% VOCLABELCOLORMAP Creates a label color map such that adjacent indices have different % colors. Useful for reading and writing index images which contain large indices, % by encoding them as RGB images. % % CMAP = VOCLABELCOLORMAP(N) creates a label color map with N entries. function cmap = labelcolormap(N) if nargin==0 N=256 end cmap = zeros(N,3); for i=1:N id = i-1; r=0;g=0;b=0; for j=0:7 r = bitor(r, bitshift(bitget(id,1),7 - j)); g = bitor(g, bitshift(bitget(id,2),7 - j)); b = bitor(b, bitshift(bitget(id,3),7 - j)); id = bitshift(id,-3); end cmap(i,1)=r; cmap(i,2)=g; cmap(i,3)=b; end cmap = cmap / 255;
github
yihui-he/reconstructing-pascal-voc-master
VOCwritexml.m
.m
reconstructing-pascal-voc-master/external_src/VOCcode/VOCwritexml.m
1,126
utf_8
d7749b6f4def796021e352fcf987fae6
function VOCwritexml(rec, path) fid=fopen(path,'w'); writexml(fid,rec,0); fclose(fid); function xml = writexml(fid,rec,depth) fn=fieldnames(rec); for i=1:length(fn) f=rec.(fn{i}); if ~isempty(f) if isstruct(f) for j=1:length(f) fprintf(fid,'%s',repmat(char(9),1,depth)); fprintf(fid,'<%s>\n',fn{i}); writexml(fid,rec.(fn{i})(j),depth+1); fprintf(fid,'%s',repmat(char(9),1,depth)); fprintf(fid,'</%s>\n',fn{i}); end else if ~iscell(f) f={f}; end for j=1:length(f) fprintf(fid,'%s',repmat(char(9),1,depth)); fprintf(fid,'<%s>',fn{i}); if ischar(f{j}) fprintf(fid,'%s',f{j}); elseif isnumeric(f{j})&&numel(f{j})==1 fprintf(fid,'%s',num2str(f{j})); else error('unsupported type'); end fprintf(fid,'</%s>\n',fn{i}); end end end end
github
yihui-he/reconstructing-pascal-voc-master
VOCreadrecxml.m
.m
reconstructing-pascal-voc-master/external_src/VOCcode/VOCreadrecxml.m
2,158
utf_8
e48003524ee25fff35c9a76c8e9044fa
function rec = VOCreadrecxml(path) x=VOCreadxml(path); x=x.annotation; rec.folder=x.folder; rec.filename=x.filename; rec.source.database=x.source.database; rec.source.annotation=x.source.annotation; rec.source.image=x.source.image; rec.size.width=str2double(x.size.width); rec.size.height=str2double(x.size.height); rec.size.depth=str2double(x.size.depth); rec.segmented=strcmp(x.segmented,'1'); rec.imgname=[x.folder '/JPEGImages/' x.filename]; rec.imgsize=str2double({x.size.width x.size.height x.size.depth}); rec.database=rec.source.database; for i=1:length(x.object) rec.objects(i)=xmlobjtopas(x.object(i)); end function p = xmlobjtopas(o) p.class=o.name; if isfield(o,'pose') if strcmp(o.pose,'Unspecified') p.view=''; else p.view=o.pose; end else p.view=''; end if isfield(o,'truncated') p.truncated=strcmp(o.truncated,'1'); else p.truncated=false; end if isfield(o,'occluded') p.occluded=strcmp(o.occluded,'1'); else p.occluded=false; end if isfield(o,'difficult') p.difficult=strcmp(o.difficult,'1'); else p.difficult=false; end p.label=['PAS' p.class p.view]; if p.truncated p.label=[p.label 'Trunc']; end if p.occluded p.label=[p.label 'Occ']; end if p.difficult p.label=[p.label 'Diff']; end p.orglabel=p.label; p.bbox=str2double({o.bndbox.xmin o.bndbox.ymin o.bndbox.xmax o.bndbox.ymax}); p.bndbox.xmin=str2double(o.bndbox.xmin); p.bndbox.ymin=str2double(o.bndbox.ymin); p.bndbox.xmax=str2double(o.bndbox.xmax); p.bndbox.ymax=str2double(o.bndbox.ymax); if isfield(o,'polygon') warning('polygon unimplemented'); p.polygon=[]; else p.polygon=[]; end if isfield(o,'mask') warning('mask unimplemented'); p.mask=[]; else p.mask=[]; end if isfield(o,'part')&&~isempty(o.part) p.hasparts=true; for i=1:length(o.part) p.part(i)=xmlobjtopas(o.part(i)); end else p.hasparts=false; p.part=[]; end if isfield(o,'actions') p.hasactions=true; fn=fieldnames(o.actions); for i=1:numel(fn) p.actions.(fn{i})=strcmp(o.actions.(fn{i}),'1'); end else p.hasactions=false; p.actions=[]; end
github
yihui-he/reconstructing-pascal-voc-master
VOCxml2struct.m
.m
reconstructing-pascal-voc-master/external_src/VOCcode/VOCxml2struct.m
1,830
utf_8
86b8ceeb5ce8c143aa78e2e805fef5d6
function res = VOCxml2struct(xml) xml(xml==9|xml==10|xml==13)=[]; [res,xml]=parse(xml,1,[]); function [res,ind]=parse(xml,ind,parent) res=[]; if ~isempty(parent)&&xml(ind)~='<' i=findchar(xml,ind,'<'); res=trim(xml(ind:i-1)); ind=i; [tag,ind]=gettag(xml,i); if ~strcmp(tag,['/' parent]) error('<%s> closed with <%s>',parent,tag); end else while ind<=length(xml) [tag,ind]=gettag(xml,ind); if strcmp(tag,['/' parent]) return else [sub,ind]=parse(xml,ind,tag); if isstruct(sub) if isfield(res,tag) n=length(res.(tag)); fn=fieldnames(sub); for f=1:length(fn) res.(tag)(n+1).(fn{f})=sub.(fn{f}); end else res.(tag)=sub; end else if isfield(res,tag) if ~iscell(res.(tag)) res.(tag)={res.(tag)}; end res.(tag){end+1}=sub; else res.(tag)=sub; end end end end end function i = findchar(str,ind,chr) i=[]; while ind<=length(str) if str(ind)==chr i=ind; break else ind=ind+1; end end function [tag,ind]=gettag(xml,ind) if ind>length(xml) tag=[]; elseif xml(ind)=='<' i=findchar(xml,ind,'>'); if isempty(i) error('incomplete tag'); end tag=xml(ind+1:i-1); ind=i+1; else error('expected tag'); end function s = trim(s) for i=1:numel(s) if ~isspace(s(i)) s=s(i:end); break end end for i=numel(s):-1:1 if ~isspace(s(i)) s=s(1:i); break end end
github
yihui-he/reconstructing-pascal-voc-master
PASreadrectxt.m
.m
reconstructing-pascal-voc-master/external_src/VOCcode/PASreadrectxt.m
3,179
utf_8
3b0bdbeb488c8292a1744dace066bb73
function record=PASreadrectxt(filename) [fd,syserrmsg]=fopen(filename,'rt'); if (fd==-1), PASmsg=sprintf('Could not open %s for reading',filename); PASerrmsg(PASmsg,syserrmsg); end; matchstrs=initstrings; record=PASemptyrecord; notEOF=1; while (notEOF), line=fgetl(fd); notEOF=ischar(line); if (notEOF), matchnum=match(line,matchstrs); switch matchnum, case 1, [imgname]=strread(line,matchstrs(matchnum).str); record.imgname=char(imgname); case 2, [x,y,c]=strread(line,matchstrs(matchnum).str); record.imgsize=[x y c]; case 3, [database]=strread(line,matchstrs(matchnum).str); record.database=char(database); case 4, [obj,lbl,xmin,ymin,xmax,ymax]=strread(line,matchstrs(matchnum).str); record.objects(obj).label=char(lbl); record.objects(obj).bbox=[min(xmin,xmax),min(ymin,ymax),max(xmin,xmax),max(ymin,ymax)]; case 5, tmp=findstr(line,' : '); [obj,lbl]=strread(line(1:tmp),matchstrs(matchnum).str); record.objects(obj).label=char(lbl); record.objects(obj).polygon=sscanf(line(tmp+3:end),'(%d, %d) ')'; case 6, [obj,lbl,mask]=strread(line,matchstrs(matchnum).str); record.objects(obj).label=char(lbl); record.objects(obj).mask=char(mask); case 7, [obj,lbl,orglbl]=strread(line,matchstrs(matchnum).str); lbl=char(lbl); record.objects(obj).label=lbl; record.objects(obj).orglabel=char(orglbl); if strcmp(lbl(max(end-8,1):end),'Difficult') record.objects(obj).difficult=true; lbl(end-8:end)=[]; else record.objects(obj).difficult=false; end if strcmp(lbl(max(end-4,1):end),'Trunc') record.objects(obj).truncated=true; lbl(end-4:end)=[]; else record.objects(obj).truncated=false; end t=find(lbl>='A'&lbl<='Z'); t=t(t>=4); if ~isempty(t) record.objects(obj).view=lbl(t(1):end); lbl(t(1):end)=[]; else record.objects(obj).view=''; end record.objects(obj).class=lbl(4:end); otherwise, %fprintf('Skipping: %s\n',line); end; end; end; fclose(fd); return function matchnum=match(line,matchstrs) for i=1:length(matchstrs), matched(i)=strncmp(line,matchstrs(i).str,matchstrs(i).matchlen); end; matchnum=find(matched); if isempty(matchnum), matchnum=0; end; if (length(matchnum)~=1), PASerrmsg('Multiple matches while parsing',''); end; return function s=initstrings s(1).matchlen=14; s(1).str='Image filename : %q'; s(2).matchlen=10; s(2).str='Image size (X x Y x C) : %d x %d x %d'; s(3).matchlen=8; s(3).str='Database : %q'; s(4).matchlen=8; s(4).str='Bounding box for object %d %q (Xmin, Ymin) - (Xmax, Ymax) : (%d, %d) - (%d, %d)'; s(5).matchlen=7; s(5).str='Polygon for object %d %q (X, Y)'; s(6).matchlen=5; s(6).str='Pixel mask for object %d %q : %q'; s(7).matchlen=8; s(7).str='Original label for object %d %q : %q'; return
github
yihui-he/reconstructing-pascal-voc-master
icp.m
.m
reconstructing-pascal-voc-master/external_src/icp/icp.m
18,342
utf_8
283054154b9888ad4a7e24be82f8851c
function [TR, TT, ER, t] = icp(q,p,varargin) % Perform the Iterative Closest Point algorithm on three dimensional point % clouds. % % [TR, TT] = icp(q,p) returns the rotation matrix TR and translation % vector TT that minimizes the distances from (TR * p + TT) to q. % p is a 3xm matrix and q is a 3xn matrix. % % [TR, TT] = icp(q,p,k) forces the algorithm to make k iterations % exactly. The default is 10 iterations. % % [TR, TT, ER] = icp(q,p,k) also returns the RMS of errors for k % iterations in a (k+1)x1 vector. ER(0) is the initial error. % % [TR, TT, ER, t] = icp(q,p,k) also returns the calculation times per % iteration in a (k+1)x1 vector. t(0) is the time consumed for preprocessing. % % Additional settings may be provided in a parameter list: % % Boundary % {[]} | 1x? vector % If EdgeRejection is set, a vector can be provided that indexes into % q and specifies which points of q are on the boundary. % % EdgeRejection % {false} | true % If EdgeRejection is true, point matches to edge vertices of q are % ignored. Requires that boundary points of q are specified using % Boundary or that a triangulation matrix for q is provided. % % Extrapolation % {false} | true % If Extrapolation is true, the iteration direction will be evaluated % and extrapolated if possible using the method outlined by % Besl and McKay 1992. % % Matching % {bruteForce} | Delaunay | kDtree % Specifies how point matching should be done. % bruteForce is usually the slowest and kDtree is the fastest. % Note that the kDtree option is depends on the Statistics Toolbox % v. 7.3 or higher. % % Minimize % {point} | plane | lmaPoint % Defines whether point to point or point to plane minimization % should be performed. point is based on the SVD approach and is % usually the fastest. plane will often yield higher accuracy. It % uses linearized angles and requires surface normals for all points % in q. Calculation of surface normals requires substantial pre % proccessing. % The option lmaPoint does point to point minimization using the non % linear least squares Levenberg Marquardt algorithm. Results are % generally the same as in points, but computation time may differ. % % Normals % {[]} | n x 3 matrix % A matrix of normals for the n points in q might be provided. % Normals of q are used for point to plane minimization. % Else normals will be found through a PCA of the 4 nearest % neighbors. % % ReturnAll % {false} | true % Determines whether R and T should be returned for all iterations % or only for the last one. If this option is set to true, R will be % a 3x3x(k+1) matrix and T will be a 3x1x(k+1) matrix. % % Triangulation % {[]} | ? x 3 matrix % A triangulation matrix for the points in q can be provided, % enabling EdgeRejection. The elements should index into q, defining % point triples that act together as triangles. % % Verbose % {false} | true % Enables extrapolation output in the Command Window. % % Weight % {@(match)ones(1,m)} | Function handle % For point or plane minimization, a function handle to a weighting % function can be provided. The weighting function will be called % with one argument, a 1xm vector that specifies point pairs by % indexing into q. The weighting function should return a 1xm vector % of weights for every point pair. % % WorstRejection % {0} | scalar in ]0; 1[ % Reject a given percentage of the worst point pairs, based on their % Euclidean distance. % % Martin Kjer and Jakob Wilm, Technical University of Denmark, 2012 % Use the inputParser class to validate input arguments. inp = inputParser; inp.addRequired('q', @(x)isreal(x) && size(x,1) == 3); inp.addRequired('p', @(x)isreal(x) && size(x,1) == 3); inp.addOptional('iter', 10, @(x)x > 0 && x < 10^5); inp.addParamValue('Boundary', [], @(x)size(x,1) == 1); inp.addParamValue('EdgeRejection', false, @(x)islogical(x)); inp.addParamValue('Extrapolation', false, @(x)islogical(x)); validMatching = {'bruteForce','Delaunay','kDtree'}; inp.addParamValue('Matching', 'bruteForce', @(x)any(strcmpi(x,validMatching))); validMinimize = {'point','plane','lmapoint'}; inp.addParamValue('Minimize', 'point', @(x)any(strcmpi(x,validMinimize))); inp.addParamValue('Normals', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('NormalsData', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('ReturnAll', false, @(x)islogical(x)); inp.addParamValue('Triangulation', [], @(x)isreal(x) && size(x,2) == 3); inp.addParamValue('Verbose', false, @(x)islogical(x)); inp.addParamValue('Weight', @(x)ones(1,length(x)), @(x)isa(x,'function_handle')); inp.addParamValue('WorstRejection', 0, @(x)isscalar(x) && x > 0 && x < 1); inp.parse(q,p,varargin{:}); arg = inp.Results; clear('inp'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Actual implementation % Allocate vector for RMS of errors in every iteration. t = zeros(arg.iter+1,1); % Start timer tic; Np = size(p,2); % Transformed data point cloud pt = p; % Allocate vector for RMS of errors in every iteration. ER = zeros(arg.iter+1,1); % Initialize temporary transform vector and matrix. T = zeros(3,1); R = eye(3,3); % Initialize total transform vector(s) and rotation matric(es). TT = zeros(3,1, arg.iter+1); TR = repmat(eye(3,3), [1,1, arg.iter+1]); % If Minimize == 'plane', normals are needed if (strcmp(arg.Minimize, 'plane') && isempty(arg.Normals)) arg.Normals = lsqnormest(q,4); end % If Matching == 'Delaunay', a triangulation is needed if strcmp(arg.Matching, 'Delaunay') DT = DelaunayTri(transpose(q)); end % If Matching == 'kDtree', a kD tree should be built (req. Stat. TB >= 7.3) if strcmp(arg.Matching, 'kDtree') kdOBJ = KDTreeSearcher(transpose(q)); end % If edge vertices should be rejected, find edge vertices if arg.EdgeRejection if isempty(arg.Boundary) bdr = find_bound(q, arg.Triangulation); else bdr = arg.Boundary; end end if arg.Extrapolation % Initialize total transform vector (quaternion ; translation vec.) qq = [ones(1,arg.iter+1);zeros(6,arg.iter+1)]; % Allocate vector for direction change and change angle. dq = zeros(7,arg.iter+1); theta = zeros(1,arg.iter+1); end t(1) = toc; % Go into main iteration loop for k=1:arg.iter % Do matching switch arg.Matching case 'bruteForce' [match mindist] = match_bruteForce(q,pt); case 'Delaunay' [match mindist] = match_Delaunay(q,pt,DT); case 'kDtree' [match mindist] = match_kDtree(q,pt,kdOBJ); end % If matches to edge vertices should be rejected if arg.EdgeRejection p_idx = not(ismember(match, bdr)); q_idx = match(p_idx); mindist = mindist(p_idx); else p_idx = true(1, Np); q_idx = match; end % If worst matches should be rejected if arg.WorstRejection edge = round((1-arg.WorstRejection)*sum(p_idx)); pairs = find(p_idx); [~, idx] = sort(mindist); p_idx(pairs(idx(edge:end))) = false; q_idx = match(p_idx); mindist = mindist(p_idx); end if k == 1 ER(k) = sqrt(sum(mindist.^2)/length(mindist)); end switch arg.Minimize case 'point' % Determine weight vector weights = arg.Weight(match); [R,T] = eq_point(q(:,q_idx),pt(:,p_idx), weights(p_idx)); case 'plane' weights = arg.Weight(match); [R,T] = eq_plane(q(:,q_idx),pt(:,p_idx),arg.Normals(:,q_idx),weights(p_idx)); case 'lmaPoint' [R,T] = eq_lmaPoint(q(:,q_idx),pt(:,p_idx)); end % Add to the total transformation TR(:,:,k+1) = R*TR(:,:,k); TT(:,:,k+1) = R*TT(:,:,k)+T; % Apply last transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Root mean of objective function ER(k+1) = rms_error(q(:,q_idx), pt(:,p_idx)); % If Extrapolation, we might be able to move quicker if arg.Extrapolation qq(:,k+1) = [rmat2quat(TR(:,:,k+1));TT(:,:,k+1)]; dq(:,k+1) = qq(:,k+1) - qq(:,k); theta(k+1) = (180/pi)*acos(dot(dq(:,k),dq(:,k+1))/(norm(dq(:,k))*norm(dq(:,k+1)))); if arg.Verbose disp(['Direction change ' num2str(theta(k+1)) ' degree in iteration ' num2str(k)]); end if k>2 && theta(k+1) < 10 && theta(k) < 10 d = [ER(k+1), ER(k), ER(k-1)]; v = [0, -norm(dq(:,k+1)), -norm(dq(:,k))-norm(dq(:,k+1))]; vmax = 25 * norm(dq(:,k+1)); dv = extrapolate(v,d,vmax); if dv ~= 0 q_mark = qq(:,k+1) + dv * dq(:,k+1)/norm(dq(:,k+1)); q_mark(1:4) = q_mark(1:4)/norm(q_mark(1:4)); qq(:,k+1) = q_mark; TR(:,:,k+1) = quat2rmat(qq(1:4,k+1)); TT(:,:,k+1) = qq(5:7,k+1); % Reapply total transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Recalculate root mean of objective function % Note this is costly and only for fun! switch arg.Matching case 'bruteForce' [~, mindist] = match_bruteForce(q,pt); case 'Delaunay' [~, mindist] = match_Delaunay(q,pt,DT); case 'kDtree' [~, mindist] = match_kDtree(q,pt,kdOBJ); end ER(k+1) = sqrt(sum(mindist.^2)/length(mindist)); end end end t(k+1) = toc; end if not(arg.ReturnAll) TR = TR(:,:,end); TT = TT(:,:,end); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_bruteForce(q, p) m = size(p,2); n = size(q,2); match = zeros(1,m); mindist = zeros(1,m); for ki=1:m d=zeros(1,n); for ti=1:3 d=d+(q(ti,:)-p(ti,ki)).^2; end [mindist(ki),match(ki)]=min(d); end mindist = sqrt(mindist); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_Delaunay(q, p, DT) match = transpose(nearestNeighbor(DT, transpose(p))); mindist = sqrt(sum((p-q(:,match)).^2,1)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_kDtree(~, p, kdOBJ) [match mindist] = knnsearch(kdOBJ,transpose(p)); match = transpose(match); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_point(q,p,weights) m = size(p,2); n = size(q,2); % normalize weights weights = weights ./ sum(weights); % find data centroid and deviations from centroid q_bar = q * transpose(weights); q_mark = q - repmat(q_bar, 1, n); % Apply weights q_mark = q_mark .* repmat(weights, 3, 1); % find data centroid and deviations from centroid p_bar = p * transpose(weights); p_mark = p - repmat(p_bar, 1, m); % Apply weights %p_mark = p_mark .* repmat(weights, 3, 1); N = p_mark*transpose(q_mark); % taking points of q in matched order [U,~,V] = svd(N); % singular value decomposition R = V*diag([1 1 det(U*V')])*transpose(U); T = q_bar - R*p_bar; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_plane(q,p,n,weights) n = n .* repmat(weights,3,1); c = cross(p,n); cn = vertcat(c,n); C = cn*transpose(cn); b = - [sum(sum((p-q).*repmat(cn(1,:),3,1).*n)); sum(sum((p-q).*repmat(cn(2,:),3,1).*n)); sum(sum((p-q).*repmat(cn(3,:),3,1).*n)); sum(sum((p-q).*repmat(cn(4,:),3,1).*n)); sum(sum((p-q).*repmat(cn(5,:),3,1).*n)); sum(sum((p-q).*repmat(cn(6,:),3,1).*n))]; 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 cz*sx*sy-cx*sz cx*cz*sy+sx*sz; cy*sz cx*cz+sx*sy*sz cx*sy*sz-cz*sx; -sy cy*sx cx*cy]; T = X(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_lmaPoint(q,p) Rx = @(a)[1 0 0; 0 cos(a) -sin(a); 0 sin(a) cos(a)]; Ry = @(b)[cos(b) 0 sin(b); 0 1 0; -sin(b) 0 cos(b)]; Rz = @(g)[cos(g) -sin(g) 0; sin(g) cos(g) 0; 0 0 1]; Rot = @(x)Rx(x(1))*Ry(x(2))*Rz(x(3)); myfun = @(x,xdata)Rot(x(1:3))*xdata+repmat(x(4:6),1,length(xdata)); options = optimset('Algorithm', 'levenberg-marquardt'); x = lsqcurvefit(myfun, zeros(6,1), p, q, [], [], options); R = Rot(x(1:3)); T = x(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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 v2 = -p2(2)/(2*p2(1)); % polynomial top point if issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1]) disp('Parabolic update!'); dv = v2; elseif issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])... || (v2 < 0 && issorted([0 v1 vmax])) disp('Line based update!'); dv = v1; elseif v1 > vmax && v2 > vmax disp('Maximum update!'); dv = vmax; else disp('No extrapolation!'); dv = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Determine the RMS error between two point equally sized point clouds with % point correspondance. % ER = rms_error(p1,p2) where p1 and p2 are 3xn matrices. function ER = rms_error(p1,p2) dsq = sum(power(p1 - p2, 2),1); ER = sqrt(mean(dsq)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (orthogonal) rotation matrices R to (unit) quaternion % representations % % Input: A 3x3xn matrix of rotation matrices % Output: A 4xn matrix of n corresponding quaternions % % http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion function quaternion = rmat2quat(R) Qxx = R(1,1,:); Qxy = R(1,2,:); Qxz = R(1,3,:); Qyx = R(2,1,:); Qyy = R(2,2,:); Qyz = R(2,3,:); Qzx = R(3,1,:); Qzy = R(3,2,:); Qzz = R(3,3,:); w = 0.5 * sqrt(1+Qxx+Qyy+Qzz); x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz); y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz); z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz); quaternion = reshape([w;x;y;z],4,[]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (unit) quaternion representations to (orthogonal) rotation matrices R % % Input: A 4xn matrix of n quaternions % Output: A 3x3xn matrix of corresponding rotation matrices % % http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix function R = quat2rmat(quaternion) q0(1,1,:) = quaternion(1,:); qx(1,1,:) = quaternion(2,:); qy(1,1,:) = quaternion(3,:); qz(1,1,:) = quaternion(4,:); R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy; 2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx; 2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Least squares normal estimation from point clouds using PCA % % H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle. % Surface reconstruction from unorganized points. % In Proceedings of ACM Siggraph, pages 71:78, 1992. % % p should be a matrix containing the horizontally concatenated column % vectors with points. k is a scalar indicating how many neighbors the % normal estimation is based upon. % % Note that for large point sets, the function performs significantly % faster if Statistics Toolbox >= v. 7.3 is installed. % % Jakob Wilm 2010 function n = lsqnormest(p, k) m = size(p,2); n = zeros(3,m); v = ver('stats'); if str2double(v.Version) >= 7.5 neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1)); else neighbors = k_nearest_neighbors(p, p, k+1); end for i = 1:m x = p(:,neighbors(2:end, i)); p_bar = 1/k * sum(x,2); P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P %P = 2*cov(x); [V,D] = eig(P); [~, idx] = min(diag(D)); % choses the smallest eigenvalue n(:,i) = V(:,idx); % returns the corresponding eigenvector end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Program to find the k - nearest neighbors (kNN) within a set of points. % Distance metric used: Euclidean distance % % Note that this function makes repetitive use of min(), which seems to be % more efficient than sort() for k < 30. function [neighborIds neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k) numDataPoints = size(dataMatrix,2); numQueryPoints = size(queryMatrix,2); neighborIds = zeros(k,numQueryPoints); neighborDistances = zeros(k,numQueryPoints); D = size(dataMatrix, 1); %dimensionality of points for i=1:numQueryPoints d=zeros(1,numDataPoints); for t=1:D % this is to avoid slow repmat() d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2; end for j=1:k [s,t] = min(d); neighborIds(j,i)=t; neighborDistances(j,i)=sqrt(s); d(t) = NaN; % remove found number from d end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Boundary point determination. Given a set of 3D points and a % corresponding triangle representation, returns those point indices that % define the border/edge of the surface. function bound = find_bound(pts, poly) %Correcting polygon indices and converting datatype poly = double(poly); pts = double(pts); %Calculating freeboundary points: TR = TriRep(poly, pts(1,:)', pts(2,:)', pts(3,:)'); FF = freeBoundary(TR); %Output bound = FF(:,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
yihui-he/reconstructing-pascal-voc-master
factorization.m
.m
reconstructing-pascal-voc-master/external_src/marques_costeira/factorization.m
3,358
utf_8
70c3edcecdca748814f20a5eba52ed7a
% [Motion, Shape, T] = factorization(Wo, iterMax1, iterMax2) % % This function computes the 3D object shape from missing and degenerate data. % % % Input arguments: % % Wo - The data matrix is defined as: % Wo = [ u_1^1 ... u_P^1 % v_1^1 ... v_P^1 % . . . % . . . % . . . % u_1^F ... u_P^F % v_1^F ... v_P^F ] % The missing data entries must be identified with NaN. % % iterMax1 [Typical values: 3000-15000] - Maximum number of iterations for % the missing data algorithm % iterMax2 [100-500] - Maximum number of iterations for Rigid Factorization % stopError1 [10^(-4) - 10^(-7)] - The missing data algorithm stops if the % error between two consecutive iterations % is lower than this threshold % stopError2 [10^(-1) - 10^(-3)] - Rigid Factorization algorithm stops if % the error between two consecutive iterations % is lower than this threshold % % Note that Rigid Factorization is one step of the global missing data algorithm. % % % Output arguments: % % Motion - The motion matrix stacks the camera matrices in all frames. The % camera matrix in frame f is a Stiefel matrix and is composed by lines % 2*f-1 and 2*f. % Shape - 3D object shape % T - Translation vector % % % For details, see: % % Marques, M., and Costeira, J.. "Estimating 3D shape from degenerate sequences with missing data", % Computer Vision and Image Understanding, 113(2):261-272, February 2009. function [Motion, Shape, T] = factorization(Wo, iterMax1, iterMax2, stopError1, stopError2) WW = Wo; M = not(isnan(Wo)); unknowns = sum(sum(not(M))); Wo(find(M == 0)) = 0; Wo = (sum(Wo,2)./sum(M,2)*ones(1,size(Wo,2))).*not(M) + Wo.*M; W = Wo; nImgs = floor(size(W,1)/2); iter1 = 0; diagError = []; ind = find(sum(M,1) == 2*nImgs); if length(ind) > 0 T = Wo(:,ind(1)); else T = mean(W,2); end [o1,e,o2]=svd(W); E=e(1:3,1:3); O1=o1(:,1:3); O2=o2(:,1:3); R=O1*sqrtm(E); S=sqrtm(E)*O2'; try, while iter1 < iterMax1 iter1 W = W - T*ones(1,size(W,2)); Woit = Wo - T*ones(1,size(W,2)); Rprev = R; Wprev = W; iterAux = 0; t = tic(); while iterAux < iterMax2 Motion = []; for i = 1:nImgs A_f = projStiefel(R(2*i-1:2*i,:)'); Motion = [Motion; A_f']; end Shape = pinv(Motion)*W; R = W*pinv(Shape); Rprev = R; iterAux = iterAux + 1; end toc(t) W = Motion*Shape + T*ones(1,size(W,2)); W = Motion*Shape.*not(M) + Woit.*M + T*ones(1,size(W,2)); iter1 = iter1 + 1; if length(ind) > 0 T = Wo(:,ind(1)); else T = mean(W,2); Motionret=Motion; Tret=T; Shaperet=Shape; end end catch, Motion=Motioneret; T=Tret; Shape=Shaperet; end % Motion = R; function W = projStiefel(Wo) [U,D,V] = svd(Wo,'econ'); c = mean(diag(D)); W = c*U*V';
github
yihui-he/reconstructing-pascal-voc-master
factorization_plane.m
.m
reconstructing-pascal-voc-master/external_src/marques_costeira/factorization_plane.m
5,238
utf_8
56df592f3605e585151493ee02875a01
% [Motion, Shape, T] = factorization(Wo, iterMax1, iterMax2) % % This function computes the 3D object shape from missing and degenerate data. % % % Input arguments: % % Wo - The data matrix is defined as: % Wo = [ u_1^1 ... u_P^1 % v_1^1 ... v_P^1 % . . . % . . . % . . . % u_1^F ... u_P^F % v_1^F ... v_P^F ] % The missing data entries must be identified with NaN. % % iterMax1 [Typical values: 3000-15000] - Maximum number of iterations for % the missing data algorithm % iterMax2 [100-500] - Maximum number of iterations for Rigid Factorization % stopError1 [10^(-4) - 10^(-7)] - The missing data algorithm stops if the % error between two consecutive iterations % is lower than this threshold % stopError2 [10^(-1) - 10^(-3)] - Rigid Factorization algorithm stops if % the error between two consecutive iterations % is lower than this threshold % % Note that Rigid Factorization is one step of the global missing data algorithm. % % % Output arguments: % % Motion - The motion matrix stacks the camera matrices in all frames. The % camera matrix in frame f is a Stiefel matrix and is composed by lines % 2*f-1 and 2*f. % Shape - 3D object shape % T - Translation vector % % % For details, see: % % Marques, M., and Costeira, J.. "Estimating 3D shape from degenerate sequences with missing data", % Computer Vision and Image Understanding, 113(2):261-272, February 2009. % NOTE: adapted for planar case, for the Reconstructing PASCAL VOC paper. function [Motion, Shape, T, errors] = factorization_plane(Wo, iterMax1, iterMax2) be_silent = true; having_no_kp = find(all(isnan(Wo)')); having_kps = setdiff(1:size(Wo,1), having_no_kp); Wo(having_no_kp,:) = []; WW = Wo; M = not(isnan(Wo)); unknowns = sum(sum(not(M))); Wo(find(M == 0)) = 0; Wo = (sum(Wo,2)./sum(M,2)*ones(1,size(Wo,2))).*not(M) + Wo.*M; W = Wo; nImgs = floor(size(W,1)/2); iter1 = 0; diagError = []; ind = find(sum(M,1) == 2*nImgs); if length(ind) > 0 T = Wo(:,ind(1)); else T = mean(W,2); end [o1,e,o2]=svd(W); E=e(1:3,1:3); O1=o1(:,1:3); O2=o2(:,1:3); R=O1*sqrtm(E); S=sqrtm(E)*O2'; try, while iter1 < iterMax1 if ~be_silent t = tic(); iter1 end W_prev_J = W; W = W - T*ones(1,size(W,2)); Woit = Wo - T*ones(1,size(W,2)); Rprev = R; Wprev = W; iterAux = 0; Motion = zeros(size(Wo,1)+3, 3); Motion(end-2:end,:) = 5000*eye(3); while iterAux < iterMax2 %Motion = cell(nImgs,1); %parfor i = 1:nImgs for i=1:nImgs range = 2*i-1:2*i; %%%% orig %A_f = projStiefel(R(2*i-1:2*i,:)'); %%%% faster version [U,D,V] = svd(R(range,:)','econ'); c = min(0.5*(D(1,1) + D(2,2)),100); A_f = c*U*V'; %Motion{i} = A_f'; Motion(range,:) = A_f'; end %Motion = cell2mat(Motion); W_ext = [W; zeros(3,size(W,2))]; Shape = pinv(Motion)*W_ext; R = W_ext*pinv(Shape); Rprev = R; iterAux = iterAux + 1; end Motion = Motion(1:end-3,:); W = Motion*Shape + T*ones(1,size(W,2)); error1 = norm(W(M) - WW(M)); change = norm(W(:) - W_prev_J(:)); if ~be_silent fprintf('Projection error: %f, solution change: %f', error1, change); end W = Motion*Shape.*not(M) + Woit.*M + T*ones(1,size(Wo,2)); iter1 = iter1 + 1; if ~isempty(ind) T = Wo(:,ind(1)); else T = mean(W,2); Motionret=Motion; Tret=T; Shaperet=Shape; end if ~be_silent toc(t) end end catch, Motion=Motioneret; T=Tret; Shape=Shaperet; end duh = Motion*Shape + T*ones(1,size(W,2)); counter = 1; errors = zeros(((size(M,1)/2)),1); for i=1:((size(M,1)/2)) range = (2*(i-1) + 1):(2*i); this_duh = duh(range,:); this_duh = this_duh(M(range,:)); this_WW = WW(range,:); this_WW = this_WW(M(range,:)); % errors(counter) = norm(this_duh - this_WW); [sc1, scaling1] = scale_data(this_WW(1:2:end)', 'zscore'); [sc2, scaling2] = scale_data(this_WW(2:2:end)', 'zscore'); this_sc1 = scale_data(this_duh(1:2:end)', 'zscore', scaling1); this_sc2 = scale_data(this_duh(2:2:end)', 'zscore', scaling2); errors(counter) = norm([sc1; sc2] - [this_sc1; this_sc2]); counter = counter + 1; end newMotion = zeros(numel(having_kps) + numel(having_no_kp), 3); newMotion(having_kps,:) = Motion; newT = zeros(numel(having_kps ) + numel(having_no_kp),1); newT(having_kps) = T; Motion = newMotion; T = newT; function W = projStiefel(Wo) [U,D,V] = svd(Wo,'econ'); c = mean(diag(D)); c = min(c,100); W = c*U*V';
github
yihui-he/reconstructing-pascal-voc-master
factorization_custom.m
.m
reconstructing-pascal-voc-master/external_src/marques_costeira/factorization_custom.m
5,143
utf_8
e0d3459a70acb2997412cb6f0b92272f
% [Motion, Shape, T] = factorization(Wo, iterMax1, iterMax2) % % This function computes the 3D object shape from missing and degenerate data. % % % Input arguments: % % Wo - The data matrix is defined as: % Wo = [ u_1^1 ... u_P^1 % v_1^1 ... v_P^1 % . . . % . . . % . . . % u_1^F ... u_P^F % v_1^F ... v_P^F ] % The missing data entries must be identified with NaN. % % iterMax1 [Typical values: 3000-15000] - Maximum number of iterations for % the missing data algorithm % iterMax2 [100-500] - Maximum number of iterations for Rigid Factorization % stopError1 [10^(-4) - 10^(-7)] - The missing data algorithm stops if the % error between two consecutive iterations % is lower than this threshold % stopError2 [10^(-1) - 10^(-3)] - Rigid Factorization algorithm stops if % the error between two consecutive iterations % is lower than this threshold % % Note that Rigid Factorization is one step of the global missing data algorithm. % % % Output arguments: % % Motion - The motion matrix stacks the camera matrices in all frames. The % camera matrix in frame f is a Stiefel matrix and is composed by lines % 2*f-1 and 2*f. % Shape - 3D object shape % T - Translation vector % % % For details, see: % % Marques, M., and Costeira, J.. "Estimating 3D shape from degenerate sequences with missing data", % Computer Vision and Image Understanding, 113(2):261-272, February 2009. % NOTE: It has been optimized somewhat for the Reconstructing PASCAL VOC paper. function [Motion, Shape, T, errors] = factorization_custom(Wo, iterMax1, iterMax2) be_silent = true; having_no_kp = find(all(isnan(Wo)')); having_kps = setdiff(1:size(Wo,1), having_no_kp); Wo(having_no_kp,:) = []; WW = Wo; M = not(isnan(Wo)); unknowns = sum(sum(not(M))); Wo(find(M == 0)) = 0; Wo = (sum(Wo,2)./sum(M,2)*ones(1,size(Wo,2))).*not(M) + Wo.*M; W = Wo; nImgs = floor(size(W,1)/2); iter1 = 0; diagError = []; ind = find(sum(M,1) == 2*nImgs); if length(ind) > 0 T = Wo(:,ind(1)); else T = mean(W,2); end [o1,e,o2]=svd(W); E=e(1:3,1:3); O1=o1(:,1:3); O2=o2(:,1:3); R=O1*sqrtm(E); S=sqrtm(E)*O2'; try, while iter1 < iterMax1 if ~be_silent t = tic(); iter1 end W_prev_J = W; W = W - T*ones(1,size(W,2)); Woit = Wo - T*ones(1,size(W,2)); Rprev = R; Wprev = W; iterAux = 0; Motion = zeros(size(Wo,1), 3); while iterAux < iterMax2 %Motion = cell(nImgs,1); %parfor i = 1:nImgs for i=1:nImgs range = 2*i-1:2*i; %%%% orig %A_f = projStiefel(R(2*i-1:2*i,:)'); %%%% faster version [U,D,V] = svd(R(range,:)','econ'); c = 0.5*(D(1,1) + D(2,2)); A_f = c*U*V'; %Motion{i} = A_f'; Motion(range,:) = A_f'; end %Motion = cell2mat(Motion); Shape = pinv(Motion)*W; R = W*pinv(Shape); Rprev = R; iterAux = iterAux + 1; end W = Motion*Shape + T*ones(1,size(W,2)); error1 = norm(W(M) - WW(M)); change = norm(W(:) - W_prev_J(:)); if ~be_silent fprintf('Projection error: %f, solution change: %f', error1, change); end W = Motion*Shape.*not(M) + Woit.*M + T*ones(1,size(Wo,2)); iter1 = iter1 + 1; if ~isempty(ind) T = Wo(:,ind(1)); else T = mean(W,2); Motionret=Motion; Tret=T; Shaperet=Shape; end if ~be_silent toc(t) end end catch, Motion=Motioneret; T=Tret; Shape=Shaperet; end duh = Motion*Shape + T*ones(1,size(W,2)); counter = 1; errors = zeros(((size(M,1)/2)),1); for i=1:((size(M,1)/2)) range = (2*(i-1) + 1):(2*i); this_duh = duh(range,:); this_duh = this_duh(M(range,:)); this_WW = WW(range,:); this_WW = this_WW(M(range,:)); % errors(counter) = norm(this_duh - this_WW); [sc1, scaling1] = scale_data(this_WW(1:2:end)', 'zscore'); [sc2, scaling2] = scale_data(this_WW(2:2:end)', 'zscore'); this_sc1 = scale_data(this_duh(1:2:end)', 'zscore', scaling1); this_sc2 = scale_data(this_duh(2:2:end)', 'zscore', scaling2); % this is a custom error function, not the one that is optimized errors(counter) = norm([sc1; sc2] - [this_sc1; this_sc2]); counter = counter + 1; end newMotion = zeros(numel(having_kps) + numel(having_no_kp), 3); newMotion(having_kps,:) = Motion; newT = zeros(numel(having_kps ) + numel(having_no_kp),1); newT(having_kps) = T; Motion = newMotion; T = newT; function W = projStiefel(Wo) [U,D,V] = svd(Wo,'econ'); c = mean(diag(D)); W = c*U*V';
github
yihui-he/reconstructing-pascal-voc-master
collect_imgset_keypoints_mirror.m
.m
reconstructing-pascal-voc-master/src/collect_imgset_keypoints_mirror.m
4,414
utf_8
fb223ff8fd94d952935a3918e7973298
function collect_imgset_keypoints_mirror(exp_dir, imgset, imgset_mirror) dest_dir = [exp_dir 'merged_Correspondences_GT_BRKL/']; load('./voc_kp_metadata.mat', 'metadata'); if(~exist(dest_dir, 'dir')) mkdir(dest_dir); end total_n_objects = 0 ; assert(iscell(imgset)); assert(numel(imgset) == numel(imgset_mirror)); for h=1:numel(imgset_mirror) sb = SegmBrowser(exp_dir, 'ground_truth', imgset{h}); y = sb.get_overlaps_wholes(1:numel(sb.whole_2_img_ids)); [q, classes] = max(y, [], 2); classes = mat2cell(classes, cellfun(@numel, sb.img_2_whole_ids)); img_names = sb.img_names; counter = 1; obj_keypoints = {}; all_rec = []; for i=1:numel(img_names) i var = load([dest_dir img_names{i} '.mat'], 'rec'); if 0 % debugging VOCinit(); GT_rec = PASreadrecord(sprintf(VOCopts.annopath,img_names{i})); GT_rec_ours = load([exp_dir 'SegmentEval/ground_truth/overlap/' img_names{i} '.mat']); GT_rec_ours = GT_rec_ours.Quality{1}; assert(numel(var.rec.objects) == numel(GT_rec_ours)); total_n_objects = total_n_objects + numel(GT_rec_ours); end GT_rec_ours = load([exp_dir 'SegmentEval/ground_truth/overlap/' img_names{i} '.mat']); GT_rec_ours = GT_rec_ours.Quality{1}; if(numel(var.rec.objects) ~= numel(GT_rec_ours)) % here we fix the dessynchronization between PASrecords and our Quality files (see your research notes)!!! var.rec.objects = var.rec.objects(1:numel(GT_rec_ours)); end if 0 % debug I = imread([exp_dir 'JPEGImages/' img_names{i} '.jpg']); imshow(I); hold on; %Iobj = imread([exp_dir 'SegmentationObject/' img_names{i} '.png']); cmap = VOClabelcolormap(256); %imshow(Iobj, cmap); hold on; for j=1:numel(var.rec.objects) if(isempty(var.rec.objects(j).keypoints)) continue; end plot(var.rec.objects(j).keypoints(:,1), var.rec.objects(j).keypoints(:,2), 'o', 'LineWidth', 5, 'Color', cmap(j+1,:)); if 0 % fix object annotation end end end I = imread([exp_dir 'JPEGImages/' img_names{i} '.jpg']); img_size = [size(I,2) size(I,1)]; for j=1:numel(var.rec.objects) if(isempty(var.rec.objects(j).keypoints)) continue; end non_null = (sum(var.rec.objects(j).keypoints,2) ~= 0); var.rec.objects(j).keypoints(non_null, 1) = img_size(1) - var.rec.objects(j).keypoints(non_null,1) + 1; map = metadata.sym_corresp{classes{i}(j)}{1}; var.rec.objects(j).keypoints(:, 1) = swap(var.rec.objects(j).keypoints(:, 1) , map(1,:), map(2,:)); var.rec.objects(j).keypoints(:, 2) = swap(var.rec.objects(j).keypoints(:, 2) , map(1,:), map(2,:)); % swap left-right symmetric dimensions end all_rec= [all_rec var.rec]; %all_rec(i) = var.rec; for j=1:numel(all_rec(i).objects) if(isfield(all_rec(i).objects(j), 'keypoints')) obj_keypoints{counter} = all_rec(i).objects(j).keypoints; else obj_keypoints{counter} = []; end counter = counter + 1; end end rec = all_rec; save([dest_dir imgset_mirror{h} '.mat'], 'rec', 'obj_keypoints', '-V6'); end end function vector = swap(vector, dims1, dims2) vec2 = vector; vec2(dims1) = vector(dims2); vec2(dims2) = vector(dims1); vector = vec2; end
github
yihui-he/reconstructing-pascal-voc-master
regionprops_BB_mine.m
.m
reconstructing-pascal-voc-master/src/regionprops_BB_mine.m
791
utf_8
920c4ed1dd131ce13583e1e7ab4c931a
% returns bounding box even is mask is composed of multiple connected % components function rp_bbox = regionprops_BB_mine(mask, slack) DefaultVal('*slack', '0'); [c_x, c_y] = find(mask); if(isempty(c_x)) % robust to masks with zero pixels. rp_bbox = [1 1 1 1]; else rp_bbox(1) = min(c_y); rp_bbox(2) = min(c_x); rp_bbox(3) = max(c_y) - rp_bbox(1) + 1; rp_bbox(4) = max(c_x) - rp_bbox(2) + 1; if(slack~=0) rp_bbox(1) = max(1, rp_bbox(1)-slack); rp_bbox(2) = max(1, rp_bbox(2)-slack); rp_bbox(3) = min(size(mask,2)-rp_bbox(1), rp_bbox(3)+2*slack); rp_bbox(4) = min(size(mask,1)-rp_bbox(2), rp_bbox(4)+2*slack); end % showboxes(mask,[rp_bbox(1) rp_bbox(2) rp_bbox(1)+rp_bbox(3) rp_bbox(2)+rp_bbox(4)]) end end
github
yihui-he/reconstructing-pascal-voc-master
gen_all_gt_segm_kp_imgset.m
.m
reconstructing-pascal-voc-master/src/gen_all_gt_segm_kp_imgset.m
3,912
utf_8
9a92930b19d9c7f7819f21f949741570
% generate imgset containing only those images where all objects have % keypoints and segmentations and where there's no obvious problem % with the keypoints (eg. keypoints missing on one object, repeated for another) function filename = gen_all_gt_segm_kp_imgset() exp_dir = add_all_paths(); mask_type = 'ground_truth'; base_imgset = 'all_gt_segm'; sb = SegmBrowser(exp_dir, mask_type, base_imgset); corr = CorrespBRKL(exp_dir, base_imgset, sb); n_with_annot = zeros(numel(sb.img_names),1); n_obj = zeros(numel(sb.img_names),1); n_gt_segm = n_obj; selected = false(numel(sb.img_names),1); for i=1:numel(sb.img_names) i %I = sb.get_Imgs(i); %I = I{1}; count_with_kp = arrayfun(@(a) numel(a.keypoints), corr.img_ann(i).objects); n_with_annot(i) = sum(count_with_kp ~= 0); n_obj(i) = numel(count_with_kp); n_gt_segm(i) = numel(sb.img_2_whole_ids{i}); %[F, D] = pooling_local_feats_mask_sift_kp(I, masks, kp, pars) selected(i) = false; if sum(n_with_annot(i)==n_obj(i)) % do more expensive test if(1) masks = sb.get_img_masks(i); this_dist = zeros(numel(corr.img_ann(i).objects),1); for j=1:numel(corr.img_ann(i).objects) kp = ceil(corr.img_ann(i).objects(j).keypoints); visib = logical(corr.img_ann(i).objects(j).visib); kp_ids = find(kp(:,1)~=0.0 | kp(:,2)~=0.0); assert(numel(corr.img_ann(i).objects(j).visib) == numel(kp_ids)); kp_visib = kp(kp_ids(visib),:); kp_visib(kp_visib(:,1) == 0 | kp_visib(:,2) == 0, :) = []; dist = bwdist(masks(:,:,j)); try %MERCIFULNESS = 0; %kp_visib(kp_visib<0 & kp_visib >-MERCIFULNESS) = 1; %kp_visib(kp_visib(:,1) > (size(masks,2)+MERCIFULNESS),1) = size(masks,2); %kp_visib(kp_visib(:,2) > (size(masks,1)+MERCIFULNESS),1) = size(masks,1); dists = dist(sub2ind([size(masks,1) size(masks,2)], kp_visib(:,2), kp_visib(:,1))); this_dist(j) = mean(dists); catch this_dist(j) = inf; end end THRESH = 15; if(max(this_dist)<THRESH) selected(i) = true; end if(~selected(i) && 0) % visualize close all; corr.show_wholes_and_keypoints(sb.img_2_whole_ids{i}); disp('oh oh'); figure; I = imread([exp_dir 'JPEGImages/' sb.img_names{i} '.jpg']); imshow(I); hold on; for j=1:numel(corr.img_ann(i).objects) kp = corr.img_ann(i).objects(j).keypoints; kp(kp(:,1) == 0 & kp(:,2) == 0,:) = []; plot(kp(:,1), kp(:,2), 'o', 'LineWidth', 15, 'Color', cmap(j+1,:)); axis image; end end end end end missing_ann_objs = sum(n_obj) - sum(n_with_annot) %ratio_without_kp = sum(n_no_annot)/sum(n_obj) ratio_zero_kp_img = sum(n_with_annot==n_obj)/numel(n_obj) sel_imgs = sb.img_names(selected); assert(all(n_obj(n_with_annot==n_obj) == n_gt_segm(n_with_annot==n_obj))) if 1 filename = [base_imgset '_kp.txt']; f = fopen([exp_dir 'ImageSets/Segmentation/' filename], 'w'); for i=1:numel(sel_imgs) fprintf(f, '%s\n', sel_imgs{i}); end fclose(f); end
github
yihui-he/reconstructing-pascal-voc-master
reconstruct_GT_puff_baseline_pascal.m
.m
reconstructing-pascal-voc-master/src/reconstruct_GT_puff_baseline_pascal.m
4,817
utf_8
323f0943ea99fc1f3ae34ec276a39de7
function reconstruct_GT_puff_baseline_pascal(sel_class) OFFICE = true; exp_dir = add_all_paths(OFFICE); DefaultVal('*sel_class', '1'); mask_type = 'ground_truth'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Get data of images having ground truth meshes %%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% imgset_all = 'all_gt_segm_kp'; pascal_mask = 'ground_truth'; sb_pascal = SegmBrowser(exp_dir, pascal_mask, imgset_all); y = sb_pascal.get_overlaps_wholes(1:numel(sb_pascal.whole_2_img_ids)); [q, class] = max(y, [], 2); in_class = find(class == sel_class); masks = sb_pascal.get_masks(in_class); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% Reconstruct object instances %%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %all_reconstr = repmat(struct('vertices', single(0), 'faces', int32(0),'dt', single(0)), size(in_class,1), 1); t_total = tic(); out_folder = ['SFM_models/Reconstructions_pascal_Puff_Baseline/' sb_pascal.categories{sel_class} '/']; mkdir(out_folder); save([out_folder 'reconstruction_data'], 'in_class', 'imgset_all','-v7.3'); parfor i=1:numel(masks) tic disp(i); file_name = [out_folder int2str(i) '.mat']; if(exist(file_name,'file')); continue end reconstructions = []; [reconstructions.faces, reconstructions.vertices] = puffball(masks{i}); reconstructions.vertices = reconstructions.vertices'; reconstructions.score = 1; reconstructions.triples = i; if 0 I = sb_pascal.get_Imgs(sb_pascal.whole_2_img_ids(in_class)); I = I{1}; % visualize reconstruction sc(I); hold on; trisurf(reconstructions.faces, reconstructions.vertices(1,:), ... reconstructions.vertices(2,:), reconstructions.vertices(3,:), 'FaceColor', 'red'); axis equal; set(gca,'zdir','reverse'); close all; end mysave(file_name, 'reconstructions', reconstructions); toc end time = toc(t_total) save([out_folder 'reconstruction_data'], 'in_class', 'imgset_all', 'time','-v7.3'); end function [Xvol, Yvol, Zvol, dt] = precompute_data(R, T, Shape, really_all_masks, step, border, faster) %TODO: this should probably be adjusted depending on the class, to ensure %that the volumetric representation covers all the volume it needs. mi = floor(min(Shape,[],2)) -border; ma = ceil(max(Shape,[],2)) + border; [Xvol,Yvol,Zvol] = meshgrid(mi(1):step:ma(1),mi(2):step:ma(2),mi(3):step:ma(3)); vol = [Xvol(:)'; Yvol(:)'; Zvol(:)']; dt = zeros(size(vol,2),size(R,3)); %parfor h=1:size(R,3) for h=1:size(R,3) thisR = R(:,:,h); thisT = T(:,h); mask = really_all_masks{h}; rotVol = thisR*vol; rotVol = bsxfun(@plus,rotVol,thisT); dt(:,h) = distance_from_mask(mask,rotVol,faster); end end function dt = distance_from_mask(mask,rotVol,faster) % Returns a negative value for voxels in the volume and positive value % outside. [M,N] = size(mask); minX = floor(min(rotVol(1,:))-2); minY = floor(min(rotVol(2,:))-2); maxX = ceil(max(rotVol(1,:))+2); maxY = ceil(max(rotVol(2,:))+2); cX = max(0,-minX+1); cY = max(0,-minY+1); aux_mask = false(cY + max(maxY,M),cX + max(maxX,N)); aux_mask(cY+1:cY+M, cX+1:cX+N) = mask; rotVol(1,:) = rotVol(1,:) + cX; rotVol(2,:) = rotVol(2,:) + cY; ind = sub2ind(size(aux_mask),round(rotVol(2,:)),round(rotVol(1,:))); if(faster) dt = -2*double(aux_mask(ind))' + 1; else dt = zeros(size(rotVol,2),1); [x,y] = getXYfromMask(aux_mask); %Discrete approximation of distance, it simply takes the closest point in %terms of the 2D distance transform, and then refines that distance. [~,IDX] = bwdist(aux_mask); sel_points = IDX(ind); d = sqrt((x(sel_points)-rotVol(1,:)').^2 + (y(sel_points)-rotVol(2,:)').^2); dt(~aux_mask(ind)) = d(~aux_mask(ind)); [~,IDX] = bwdist(~aux_mask); sel_points = IDX(ind); d = sqrt((x(sel_points)-rotVol(1,:)').^2 + (y(sel_points)-rotVol(2,:)').^2); dt(aux_mask(ind)) = -d(aux_mask(ind)); end end function [x,y,m] = getXYfromMask(mask) [x,y] = meshgrid(1:size(mask,2),1:size(mask,1)); x = x(:); y = y(:); m = mask(:); end function out = assig2cell(assig) un = unique(assig); n = numel(un); out = cell(n,1); for i=1:n out{i} = find(assig==un(i)); end out(isempty(out)) = []; end
github
yihui-he/reconstructing-pascal-voc-master
evaluate_reconstruction_ranking.m
.m
reconstructing-pascal-voc-master/src/evaluate_reconstruction_ranking.m
7,355
utf_8
5f45c481f720bdbb739c988b2063f828
% sometimes this crashes, (something related to parfor and writing and reading to files) % just remove any .off files and rerun and it should be fine. function evaluate_reconstruction_ranking(exp_dir,reconstr_name,withICP) if(nargin<3) withICP = 0; end for i=1:20 classes{i} = VOC09_id_to_classname(i); end all_errors = cell(numel(classes),1); all_errors_upperbound = []; for i=1:20 filename = ['./Results/ranking_errors_' classes{i} '_' reconstr_name '.mat']; if exist(filename, 'file') continue; end i in_class = []; base_dir = ['./Results/' reconstr_name '/' classes{i} '/']; load([base_dir 'reconstruction_data.mat']); sb = SegmBrowser(exp_dir, 'ground_truth', imgset_all); files = dir([base_dir '*.mat']); files(arrayfun(@(a) strcmp(a.name, 'reconstruction_data.mat'), files)) = []; t_class = tic(); scores = []; class_errors = cell(numel(files),1); class_errors_ICP = class_errors; scores = class_errors; for j=1:numel(files) j gt_mesh = []; % load reconstructed mesh reconstructions = myload([base_dir files(j).name], 'reconstructions'); img_name = sb.img_names{sb.whole_2_img_ids(in_class(reconstructions(1).triples(1)))}; scores{j} = [reconstructions(:).score]; % load ground truth synthetic mesh if 1 load([exp_dir 'MyMeshes/ground_truth/' img_name '.mat'], 'tri', 'vertices'); else tri = myload([exp_dir 'MyMeshes/ground_truth/' img_name '.mat'], 'tri'); % was trying to use parfor but couldn't vertices = myload([exp_dir 'MyMeshes/ground_truth/' img_name '.mat'], 'vertices'); end gt_mesh.faces = tri'; gt_mesh.vertices = vertices; errors = zeros(numel(reconstructions),1); errors_ICP = errors; parfor k=1:numel(reconstructions) if(numel(reconstructions(k).faces)<2) errors(k) = inf; else if(withICP) [icpR,icpT] = icp(gt_mesh.vertices,reconstructions(k).vertices,'Matching','kDtree'); icpCorrected = bsxfun(@plus,icpR*reconstructions(k).vertices,icpT); errors_ICP(k) = hausdorff_surface_error_mex(icpCorrected, reconstructions(k).faces, gt_mesh.vertices, gt_mesh.faces); end errors(k) = hausdorff_surface_error_mex(reconstructions(k).vertices, reconstructions(k).faces, gt_mesh.vertices, gt_mesh.faces); end end class_errors{j} = errors; class_errors_ICP{j} = errors_ICP; end time_per_class = toc(t_class) errors = class_errors; if(withICP) errors_ICP = class_errors_ICP; save(filename, 'errors','errors_ICP','scores'); else save(filename, 'errors','scores'); end end RANDOM_SCORE = [false true]; %plotStyle = {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'b--', 'g--', 'r--', 'c--', 'm--', 'y--', 'k--', 'b:', 'g:', 'r:', 'c:', 'm:', 'y:'}; plotStyle = {'b', 'g', 'r', 'c', 'm', 'b', 'g', 'r', 'c', 'm', 'b', 'g', 'r', 'c', 'm', 'b', 'g', 'r', 'c', 'm'}; all_errors_first = cell(2,20); n_samples = []; for i=1:20 subplot(4,5,i); for k=1:numel(RANDOM_SCORE) filename = ['./Results/ranking_errors_' classes{i} '_' reconstr_name '.mat']; var = load(filename); scores = var.scores; errors = var.errors; %errors = var.errors_ICP; n_samples = [n_samples; cellfun(@numel, scores)]; % fill in any missing values n_proposals = max(cellfun(@numel, scores)); for l=1:numel(scores) if(numel(scores{l}) ~= n_proposals) scores{l} = [scores{l} -inf(1, n_proposals - numel(scores{l}))]; errors{l} = [errors{l}; max(errors{l})*ones(n_proposals - numel(errors{l}),1)]; end end scores = cell2mat(scores)'; errors = cell2mat(errors'); errors(errors==inf) = 100; if RANDOM_SCORE(k) scores = rand(size(scores)); end if(size(errors,1)>1) [~, ids_srt] = sort(scores, 'descend'); for j=1:size(errors,2) errors(:,j) = errors(ids_srt(:,j),j); end end % get min of avg error per rank min_avg = []; %if(fix_me) % errors = errors(1,:); %end for j=1:size(errors,1) if(size(errors,1)>1) min_avg(j) = mean(min(errors(1:j,:),[],1)); else min_avg(j) = mean(errors); end if j==1 all_errors_first{k,i} = min(errors(1:j,:),[],1); end end if(size(errors,1)>1) all_errors_upperbound{i} = min(errors); else all_errors_upperbound{i} = errors; end if RANDOM_SCORE(k) h(i) = plot(1:numel(min_avg), min_avg, [plotStyle{i} 'o'], 'LineWidth', 3); hold on; else h(i) = plot(1:numel(min_avg), min_avg, plotStyle{i}, 'LineWidth', 5); hold on; end end legend({[classes{i} ' - predicted'], [classes{i} ' - random']}); end figure; cmap = VOClabelcolormap(256); for i=1:20 plot(i, mean(all_errors_first{2,i}), 'x', 'MarkerSize', 15, 'LineWidth', 5, 'Color', cmap(i+1,:)); hold on; plot(i, mean(all_errors_first{1,i}), 'o', 'MarkerSize', 15, 'LineWidth', 5, 'Color', cmap(i+1,:)); hold on; plot(i, mean(all_errors_upperbound{i}), 's', 'MarkerSize', 15, 'LineWidth', 5, 'Color', cmap(i+1,:)); hold on; fprintf('%s:\t\t %f \t %f \t %f\n', classes{i}, mean(all_errors_first{1,i}), mean(all_errors_upperbound{i}), mean(all_errors_first{2,i})); classes{i} = VOC09_id_to_classname(i); end set(gca, 'Xlim', [0 21]); xticklabel_rotate(1:20, 45, classes, 'FontSize', 15) set(gca,'FontSize',15); legend('Random', 'Top-ranked', 'Best available'); all_errors_upperbound = cell2mat(all_errors_upperbound); fprintf('\n\n'); mean_error_pred = mean(cell2mat(all_errors_first(1,:))'); mean_error_rand = mean(cell2mat(all_errors_first(2,:))'); mean_error_upperbound = mean(all_errors_upperbound); fprintf('Mean error using predicted: %f\nMean error with random selection: %f\n', mean_error_pred, mean_error_rand); fprintf('Lower bound on error of a selection function: %f\n', mean_error_upperbound); fprintf('Average number of proposals per image: %f\n', mean(n_samples)); end
github
yihui-he/reconstructing-pascal-voc-master
cam_refinement.m
.m
reconstructing-pascal-voc-master/src/cam_refinement.m
4,387
utf_8
08acc8f4e9ed942cc7b81d9b99f095ec
function [R,T,best_en] = cam_refinement(Rot,Tr,Shape,mask,projections,use_dt) % Refines the camera position based on the mask, so that all points % reproject inside the mask % minimizes: %weigths.proj*(keypoints - (rot*shape+tr))^2 + weights.dt*dist_mask(rot*shape +tr); if(use_dt) weights.proj = 1; weights.dt = 1; else weights.proj = 1; weights.dt = 0; end r = Rot(1:2,:); t = Tr(1:2); dt = get_distance_transform(mask,weights); %Precompute part of the gradient n_points = size(Shape,2); grad_t1 = [ones(n_points,1); zeros(n_points,1)]; grad_t2 = [zeros(n_points,1); ones(n_points,1)]; grad_r1 = [Shape(1,:) zeros(1,n_points)]'; grad_r2 = [Shape(2,:) zeros(1,n_points)]'; grad_r3 = [Shape(3,:) zeros(1,n_points)]'; grad_r4 = [zeros(1,n_points) Shape(1,:)]'; grad_r5 = [zeros(1,n_points) Shape(2,:)]'; grad_r6 = [zeros(1,n_points) Shape(3,:)]'; projections = projections(:); nan_proj = isnan(projections); step = 10^-4; n_iter=20000; coord = bsxfun(@plus,r*Shape,t); coord = coord'; best_en=get_energy(coord,projections,dt,weights); en = best_en+1; dt_fx = zeros(n_points, 1); dt_fy = dt_fx; for k =1:n_iter coord = bsxfun(@plus,r*Shape,t); coord = coord'; if(weights.dt~=0) [dt_fx,dt_fy] = get_dt_gradient(dt,coord); end repr = weights.proj*2*(coord(:) - projections); repr(nan_proj) = 0; grad = [dt_fx;dt_fy] + repr; grad_r = [sum(grad.*grad_r1) sum(grad.*grad_r2) sum(grad.*grad_r3);... sum(grad.*grad_r4) sum(grad.*grad_r5) sum(grad.*grad_r6)]; grad_t = [sum(grad.*grad_t1); sum(grad.*grad_t2)]; while(en>best_en) if(step < 10^-7) if(any(grad_r(:)~=0)) step = 10^-2; grad_r(:) = 0; else break end end r1 = r-step*grad_r; r1 = projStiefel(r1); t1 = t-step*grad_t; c = bsxfun(@plus,r1*Shape,t1)'; en=get_energy(c,projections,dt,weights); if(isnan(en)); en = best_en+1; end step = step/2; end if(en>best_en && step < 10^-7 && all(grad_r(:)==0)) break; end step = step*4; r = r1; t = t1; best_en = en; if(best_en==0) break; end en = best_en+1; end scale = norm(r(1,:)); R_3 = cross((1/scale)*r(1,:), (1/scale)*r(2,:)); R = [r; scale*R_3]; T =[t;0]; end function en=get_energy(coord,projections,dt,weights) en = (coord(:) - projections).^2; en = weights.proj*sum(en(~isnan(en))); if(weights.dt ~=0) coord(:,2) = round(coord(:,2))+floor(dt.tolerance/2)*dt.M; coord(:,1) = round(coord(:,1))+floor(dt.tolerance/2)*dt.N; if(any(coord(:,1)<1) || any(coord(:,1)>size(dt.function,2)) || any(coord(:,2)>size(dt.function,1)) || any(coord(:,2)<1)) en = nan; return; end a = dt.function(sub2ind(size(dt.function),coord(:,2),coord(:,1))); en = en + sum(a); end end function r = projStiefel(r) [U,D,V] = svd(r,'econ'); c = (D(1,1) + D(2,2))/2; %c = mean(diag(D)); r = c*U*V'; end function [dt_fx,dt_fy] = get_dt_gradient(dt,coord) ind = sub2ind(size(dt.function),round(coord(:,2))+floor(dt.tolerance/2)*dt.M,round(coord(:,1))+floor(dt.tolerance/2)*dt.N); dt_fx = dt.fx(ind); dt_fy = dt.fy(ind); end function distance_transform = get_distance_transform(mask,weights) tol = 3; distance_transform.tolerance = tol; [M,N] = size(mask); distance_transform.M = M; distance_transform.N = N; aux = zeros(tol*M,tol*N); aux(floor(tol/2)*M+1:ceil(tol/2)*M,floor(tol/2)*N+1:ceil(tol/2)*N) = mask; distance_transform.function = weights.dt*double(bwdist(aux)).^2; [distance_transform.x,distance_transform.y] = meshgrid(1:tol*N,1:tol*M); distance_transform.x = distance_transform.x - floor(tol/2)*N; distance_transform.y = distance_transform.y - floor(tol/2)*M; [distance_transform.fx,distance_transform.fy] = gradient(distance_transform.function); end
github
yihui-he/reconstructing-pascal-voc-master
normalize.m
.m
reconstructing-pascal-voc-master/src/normalize.m
1,601
utf_8
688deea9c3947acdbcc4ae85e6551565
% Copyright (C) 2010 Joao Carreira % % This code is part of the extended implementation of the paper: % % J. Carreira, C. Sminchisescu, Constrained Parametric Min-Cuts for Automatic Object Segmentation, IEEE CVPR 2010 % function [Feats] = normalize(Feats, scaling) if(iscell(Feats)) scaling.to_subtract = double(scaling.to_subtract); scaling.to_divide = double(scaling.to_divide); for i=1:length(Feats) Feats{i} = double(Feats{i}); Feats{i} = single(full(spdiags(scaling.to_divide',0,size( Feats{i},1),size( Feats{i},1))*( Feats{i} - repmat(scaling.to_subtract,1,size( Feats{i},2))))); end else % break Feats into 1000 vectors chunks to save memory MAX_CHUNK_SIZE = 30000; n_chunks = ceil(size(Feats,2)/MAX_CHUNK_SIZE); chunk_size = repmat(MAX_CHUNK_SIZE,n_chunks,1); the_mod = mod(size(Feats,2),MAX_CHUNK_SIZE); if(the_mod) chunk_size(end) = the_mod; end previous_id = 0; for i=1:n_chunks interval = previous_id+1:previous_id + chunk_size(i); FeatsChunk = double(Feats(:,interval)); scaling.to_divide = double(scaling.to_divide); scaling.to_subtract = double(scaling.to_subtract); Feats(:,interval) = single(full(spdiags(scaling.to_divide',0,size(FeatsChunk,1),size(FeatsChunk,1))*(FeatsChunk - repmat(scaling.to_subtract,1,size(FeatsChunk,2))))); previous_id = previous_id + chunk_size(i); end Feats(isnan(Feats)) = 0; % when a feature is constant in all training examples it gets NaN here end end
github
yihui-he/reconstructing-pascal-voc-master
reconstruct_pascal_getall.m
.m
reconstructing-pascal-voc-master/src/reconstruct_pascal_getall.m
10,752
utf_8
034311e75946795443f89c7cd9ec4006
function reconstruct_pascal_getall(sel_class, n_iter_1, n_iter_2, N_SAMPLES_PER_OBJ, MAX_DEV, name, refinement, imprinting) DefaultVal('*refinement', 'true'); DefaultVal('*imprinting', 'true'); exp_dir = add_all_paths(); mask_type = 'ground_truth'; imgset_pascal = 'all_gt_segm_kp'; imgset_pascal_mirror = 'all_gt_segm_mirror_kp'; imgset_all = imgset_pascal; imgset_all_mirror = imgset_pascal_mirror; load('voc_kp_metadata.mat'); kp_names = metadata.kp_names{sel_class}; sb_all = SegmBrowser(exp_dir, mask_type, imgset_all); sb_all_mirror = SegmBrowser(exp_dir, mask_type, imgset_all_mirror); sfm_folder = ['./Results/']; if(metadata.articulated(sel_class)) largest_rigid = true; else largest_rigid = false; end [in_class, filename_sfm, filename_ref, sel_kp_ids] = compute_and_cache_sfm_model(exp_dir, sfm_folder, sel_class, n_iter_1, n_iter_2, largest_rigid, imgset_all); load([filename_sfm '.mat']); if(refinement) var = load([filename_ref '.mat'], 'R', 'T'); R = var.R; T = var.T; end [Shape, R, k] = postprocess_sfm(Shape, R); if 0 show_3d_model(Shape, kp_names(sel_kp_ids), 'convex_hull'); axis equal; end if 0 % visualize some cameras to see if it's ok figure; viz_ids = 1:20; Is = sb_all.get_Imgs(sb_all.whole_2_img_ids(in_class(viz_ids))); the_masks = sb_all.get_masks(in_class(viz_ids)); show_cameras_sv(Shape, kp_names(sel_kp_ids), R(:,:,viz_ids), T(:,viz_ids), Is, the_masks); end corr = CorrespBRKL(exp_dir, imgset_all, sb_all); corr_mirror = CorrespBRKL(exp_dir, imgset_all_mirror, sb_all_mirror); kp_obj = corr.obj_keypoints(in_class); kp_obj = cellfun(@(a) a(:,1:2), kp_obj, 'UniformOutput', false); kp_obj_mirror = corr_mirror.obj_keypoints(in_class); kp_obj_mirror = cellfun(@(a) a(:,1:2), kp_obj_mirror, 'UniformOutput', false); all_kp = [kp_obj kp_obj_mirror]; for i=1:numel(all_kp) all_kp{i}(isnan(all_kp{i})) = 0; end n_kp = cellfun(@(a) sum(a(:,1)~=0 | a(:,2) ~= 0), kp_obj)'; % collect masks, should perhaps fill any holes all_masks = sb_all.get_masks(in_class); all_sym_masks = sb_all_mirror.get_masks(in_class); really_all_masks = [all_masks; all_sym_masks]; if 0 areas = compute_mask_areas(sb_all); areas = areas(in_class); end max_angle_deviations = [MAX_DEV MAX_DEV MAX_DEV]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%% Get data of images having ground truth meshes %%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% test_mask = 'ground_truth'; sb_test = SegmBrowser(exp_dir, test_mask, imgset_pascal); corr_test = CorrespBRKL(exp_dir, imgset_pascal, sb_test); y = sb_test.get_overlaps_wholes(1:numel(sb_test.whole_2_img_ids)); [q, class] = max(y, [], 2); in_class_test = find(class == sel_class); sb_test_mirror = SegmBrowser(exp_dir, test_mask, imgset_pascal_mirror); corr_test_mirror = CorrespBRKL(exp_dir, imgset_pascal_mirror, sb_test_mirror); kp_test = corr_test.obj_keypoints(in_class_test); kp_test = cellfun(@(a) a(:,1:2), kp_test, 'UniformOutput', false); kp_test_mirror = corr_test_mirror.obj_keypoints(in_class_test); kp_test_mirror = cellfun(@(a) a(:,1:2), kp_test_mirror, 'UniformOutput', false); all_kp_test = [kp_test kp_test_mirror]; masks_test = sb_test.get_masks(in_class_test); masks_test_mirror = sb_test_mirror.get_masks(in_class_test); all_masks_test = [masks_test; masks_test_mirror]; % gets ids of gt within the pascal+gt set ids_all = sb_all.whole_2_img_ids(in_class); test_ids = [ids_all; ids_all+(size(R,3)/2)]; pascal_ids = test_ids; R_test = R; T_test = T; R_pascal = R; T_pascal = T; kp_pascal = kp_obj; kp_pascal_mirror = kp_obj_mirror; all_kp_pascal = [kp_pascal kp_pascal_mirror]; masks_pascal = sb_all.get_masks(in_class); masks_pascal_mirror = sb_all_mirror.get_masks(in_class); all_masks_pascal = [masks_pascal; masks_pascal_mirror]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%% Sample triplets of object images %%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Reconstruct object using a single view from the test % object and 2 others from a pool of examples of the same category from % the pascal voc data [test_ids_sel, pascal_ids_sel, axs] = view_comb_sampling_general(R_test, R_pascal, N_SAMPLES_PER_OBJ, max_angle_deviations); axis_masks = get_average_mask(axs, R, T, really_all_masks); ids = [test_ids_sel pascal_ids_sel]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%% Reconstruct object instances %%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% N_VOXELS = 60; if largest_rigid filename_precomp = ['./SFM_models/precomp_dt_' sb_all.categories{sel_class} '_' imgset_all '_largest_rigid.mat']; else filename_precomp = ['./SFM_models/precomp_dt_' sb_all.categories{sel_class} '_' imgset_all '.mat']; end t_total = tic(); flags.is_articulated = metadata.articulated(sel_class); flags.rot_symmetry = metadata.view_based(sel_class); flags.imprinted = imprinting; if(flags.rot_symmetry) flags.rot_axis = get_rot_axis(Shape,metadata.bottom_top{sel_class}); end flags.angle_step = pi/2; out_folder = ['SFM_models/' name '/' sb_all.categories{sel_class} '/']; mkdir(out_folder); save([out_folder 'reconstruction_data'], 'in_class', 'imgset_all', 'ids', 'N_VOXELS', 'max_angle_deviations','-v7.3'); obj_ids = unique(test_ids_sel); for i=1:numel(obj_ids) tic disp(i); file_name = [out_folder int2str(i) '.mat']; if(exist(file_name,'file')); continue end ids_sel = ids(ids(:,1)==obj_ids(i),:); ids_sel = unique(ids_sel, 'rows'); reconstructions = sel_best_reconstruction_getall(ids_sel,R,T,all_kp,really_all_masks, N_VOXELS,axis_masks,flags); if 0 t = reconstructions.triples(1:end/2); t(t==0) = []; the_masks = [all_masks(t); all_sym_masks(t)]; figure; Is = [sb_all.get_Imgs(sb_all.whole_2_img_ids(in_class(t)));sb_all_mirror.get_Imgs(sb_all_mirror.whole_2_img_ids(in_class(t)))]; subplot_auto_transparent_multiple_imgs(the_masks, Is); end if(numel(reconstructions) == 1 && isempty(reconstructions.triples)) theR = []; theT = []; else allids = arrayfun(@(a) a.triples(1), reconstructions); assert(numel(unique(allids))==1); theR = R(:,:,allids(1)); theT = T(:,allids(1)); for j=1:numel(reconstructions) reconstructions(j).vertices = bsxfun(@plus,theR*reconstructions(j).vertices',theT); end end if 0 I = sb_all.get_Imgs(sb_all.whole_2_img_ids(in_class(ids_sel(1,1)))); I = I{1}; % visualize reconstruction sc(I); hold on; rec_id = 10; trisurf(reconstructions(rec_id).faces, reconstructions(rec_id).vertices(1,:), ... reconstructions(rec_id).vertices(2,:), reconstructions(rec_id).vertices(3,:), 'FaceColor', 'blue'); axis equal; set(gca,'zdir','reverse'); end save(file_name, 'reconstructions','ids_sel', 'theR', 'theT', '-v7.3'); toc close all; end time = toc(t_total) save([out_folder 'reconstruction_data'], 'in_class', 'imgset_all', 'N_VOXELS', 'max_angle_deviations','time','flags', 'Shape', 'axis_masks', '-v7.3'); end function [Xvol, Yvol, Zvol, dt] = precompute_data(R, T, Shape, really_all_masks, step, border, faster) %TODO: this should probably be adjusted depending on the class, to ensure %that the volumetric representation covers all the volume it needs. mi = floor(min(Shape,[],2)) -border; ma = ceil(max(Shape,[],2)) + border; [Xvol,Yvol,Zvol] = meshgrid(mi(1):step:ma(1),mi(2):step:ma(2),mi(3):step:ma(3)); vol = [Xvol(:)'; Yvol(:)'; Zvol(:)']; dt = zeros(size(vol,2),size(R,3)); %parfor h=1:size(R,3) for h=1:size(R,3) thisR = R(:,:,h); thisT = T(:,h); mask = really_all_masks{h}; rotVol = thisR*vol; rotVol = bsxfun(@plus,rotVol,thisT); dt(:,h) = distance_from_mask(mask,rotVol,faster); end end function dt = distance_from_mask(mask,rotVol,faster) % Returns a negative value for voxels in the volume and positive value % outside. [M,N] = size(mask); minX = floor(min(rotVol(1,:))-2); minY = floor(min(rotVol(2,:))-2); maxX = ceil(max(rotVol(1,:))+2); maxY = ceil(max(rotVol(2,:))+2); cX = max(0,-minX+1); cY = max(0,-minY+1); aux_mask = false(cY + max(maxY,M),cX + max(maxX,N)); aux_mask(cY+1:cY+M, cX+1:cX+N) = mask; rotVol(1,:) = rotVol(1,:) + cX; rotVol(2,:) = rotVol(2,:) + cY; ind = sub2ind(size(aux_mask),round(rotVol(2,:)),round(rotVol(1,:))); if(faster) dt = -2*double(aux_mask(ind))' + 1; else dt = zeros(size(rotVol,2),1); [x,y] = getXYfromMask(aux_mask); %Discrete approximation of distance, it simply takes the closest point in %terms of the 2D distance transform, and then refines that distance. [~,IDX] = bwdist(aux_mask); sel_points = IDX(ind); d = sqrt((x(sel_points)-rotVol(1,:)').^2 + (y(sel_points)-rotVol(2,:)').^2); dt(~aux_mask(ind)) = d(~aux_mask(ind)); [~,IDX] = bwdist(~aux_mask); sel_points = IDX(ind); d = sqrt((x(sel_points)-rotVol(1,:)').^2 + (y(sel_points)-rotVol(2,:)').^2); dt(aux_mask(ind)) = -d(aux_mask(ind)); end end function [x,y,m] = getXYfromMask(mask) [x,y] = meshgrid(1:size(mask,2),1:size(mask,1)); x = x(:); y = y(:); m = mask(:); end function out = assig2cell(assig) un = unique(assig); n = numel(un); out = cell(n,1); for i=1:n out{i} = find(assig==un(i)); end out(isempty(out)) = []; end
github
yihui-he/reconstructing-pascal-voc-master
puffball.m
.m
reconstructing-pascal-voc-master/src/puffball.m
2,705
utf_8
0a191a968a1f9911e80ae2417db3f7c1
function [tri, coord] = puffball(mask) %Weighted skeleton, where each non-zero value corresponds to the maximum %size of a sphere that can be centered there. wSkel = get_SkelRadius(mask); heightFunction = puffbalIInflation(mask,wSkel); [tri,coord] = mesh_from_height(mask, heightFunction); end function [tri, coord] = mesh_from_height(mask, rec) [M,N] = size(mask); [x,y] = meshgrid(1:N,1:M); tri = delaunay(x,y); ind_tri = mask(tri); ind_tri = ind_tri(:,1) | ind_tri(:,2) | ind_tri(:,3); tri = tri(ind_tri,:); aux = unique(tri); boundary = setdiff(aux, find(mask)); points=zeros(M*N,1); nPoints = length(aux); points(aux) = 1:nPoints; tri = points(tri); boundary = points(boundary); x = x(aux); y = y(aux); z = rec(aux); for k =1:length(boundary) pBound = boundary(k); sel = sum(tri==pBound,2)>0; selPoints = setdiff(unique(tri(sel,:)),pBound); x1 = median(x(selPoints)); y1 = median(y(selPoints)); x(pBound) = x1; y(pBound) = y1; end points = zeros(nPoints,1); points(boundary) = boundary; points(points==0) = nPoints + (1:(nPoints-length(boundary))); reflected_tri = points(tri); tri = [tri; reflected_tri]; x = [x;x]; y = [y;y]; z = [z; -z]; x(boundary + nPoints) = []; y(boundary + nPoints) = []; z(boundary + nPoints) = []; coord = [x y z]; %figure; trisurf(tri,x,y,z,'FaceColor','r'); %axis equal %set(gca,'YDir','rev'); end function [ h ] = puffbalIInflation( mask,wSkel ) % TAKE THE UNION (SOFT-MAX) OF MAXIMAL SPHERES % [Y, X] = meshgrid(1:size(mask,2),1:size(mask,1)); h = ones(size(mask)); [y,x] = find(wSkel); k = 1; for i = 1:length(x) r = wSkel(y(i),x(i))^2 - (X-y(i)).^2 - (Y-x(i)).^2; h(r>0) = h(r>0)+exp(k*sqrt(r(r>0))); end h = log(h)/k; end function [wSkel, allRadius] = get_SkelRadius(mask) %Weighted skeleton, where each non-zero value corresponds to the maximum %size of a sphere that can be centered there. % CALCULATE GRASSFIRE HEIGHT FUNCTION % % A 3x3-tap filter to smoothly erode an anti-aliased edge fil = [0.1218 0.4123 0.1218; 0.4123 0.9750 0.4123; ... 0.1218 0.4123 0.1218]/1.2404; nmask = double(mask); allRadius = zeros(size(mask)); while ~isempty(find(nmask,1)) allRadius = allRadius+nmask/1.67; % Each iteration erodes the edge .6 pixels nmaskpad = padarray(nmask,[1 1],'replicate'); nmaskpad = conv2(nmaskpad,fil,'same')-1.4241; nmask = max(min(nmaskpad(2:end-1,2:end-1),1),0); end % LOCATE THE MEDIAL AXIS % [dx, dy] = gradient(allRadius); dsurf = sqrt(dx.^2+dy.^2); % Medial axis points have a grassfire gradient measurably less than 1 radThreshold = min(max(allRadius(:)),2); wSkel = bwmorph(dsurf<0.958&allRadius>=radThreshold,'skel',Inf).*allRadius; end
github
yihui-he/reconstructing-pascal-voc-master
sel_best_reconstruction_getall.m
.m
reconstructing-pascal-voc-master/src/sel_best_reconstruction_getall.m
9,550
utf_8
d5c6f71127bf609e4861602155ba9ac1
function [fv2,statistics] = sel_best_reconstruction_getall(all_triples,R,T,kp,really_all_masks, N_VOXELS,axis_masks,flags) %flags is a structure with the following fields: % %flags.is_articulated %flags.rot_symmetry %flags.rot_axis (only important if rot_symmetry == 1) %flags.angle_step (only important if rot_symmetry == 1) if(sum(abs(R(:,:,all_triples(1,1)))) == 0) % If the rotation wasn't estimated. fv2.vertices = []; fv2.faces = []; fv2.triples = []; return end n_images = size(R,3)/2; if ~flags.is_articulated all_triples = [all_triples all_triples+n_images]; end thisR = R(:,:,all_triples(1,1)); thisT = T(:,all_triples(1,1)); mask = really_all_masks{all_triples(1,1)}; thisKP = kp{all_triples(1,1)}; old_triples = all_triples; if flags.rot_symmetry selR = thisR; old_triples = old_triples(1); ref_id = 1; if(isfield(flags,'angle_step')) angle_step = flags.angle_step; else angle_step = pi/4; end for th = angle_step:angle_step:(2*pi - angle_step); switch flags.rot_axis case 'x' r1 = [1 0 0;0 cos(th) -sin(th); 0 sin(th) cos(th)]; case 'y' r1 = [cos(th) 0 sin(th);0 1 0; -sin(th) 0 cos(th) ]; case 'z' r1 = [cos(th) -sin(th) 0 ; sin(th) cos(th) 0; 0 0 1]; end r1 = thisR*r1; selR = cat(3,selR,r1); end selT = repmat(thisT, [1 size(selR,3)]); all_triples = 1:size(selR,3); selMasks = cell(size(all_triples)); for k =1:size(selR,3) selMasks{k} = mask; end [Xvol, Yvol, Zvol, dt,vol] = precompute_data(selR,selT, selMasks , N_VOXELS, ref_id); else un_ids = unique(all_triples(:)); un_ids(un_ids==0) = []; ind = zeros(max(un_ids),1); ind(un_ids) = 1:length(un_ids); all_triples(all_triples~=0) = ind(all_triples(all_triples~=0)); ref_id = all_triples(1); [Xvol, Yvol, Zvol, dt,vol] = precompute_data(R(:,:,un_ids), T(:,un_ids), really_all_masks(un_ids), N_VOXELS,ref_id); end dt = single(dt); siz = size(Xvol); n_triples = size(all_triples,1); not_projected = ones(n_triples,1)*size(thisKP,1); dist_proj = 10*ones(n_triples,1); area_beforeFilling = zeros(n_triples,1); all_reconstr = repmat(struct('vertices', single(0), 'faces', int32(0)), n_triples, 1); voxel_bondary = true(siz); voxel_bondary(2:end-1,2:end-1,2:end-1) = false; %set to 1 to plot all of the reconstructions. plot_debug = 0; if(plot_debug) scrsz = get(0,'ScreenSize'); h = figure(100); set(h,'Position',[1 1 scrsz(3) scrsz(4)]); end all_dt_models = single(zeros(size(dt,1),size(all_triples,1))); for k =1:size(all_triples,1) ids_sel = all_triples(k,:); ids_sel(ids_sel == 0) = []; volRec = max(dt(:,ids_sel),[],2); if(flags.imprinted) [volRec,area_beforeFilling(k)] = imprinted_VisualHull(vol,volRec,mask,thisR,thisT,siz); end volRec = 1-(2*(volRec<0)); volRec = reshape(volRec,siz); volRec(voxel_bondary) = abs(volRec(voxel_bondary)); all_dt_models(:,k) = volRec(:); fv2 = isosurface(Xvol,Yvol,Zvol,volRec,0); if(isempty(fv2.faces)) disp('empty volume!') continue; end new_vertices = bsxfun(@plus,thisR*(fv2.vertices)',thisT)'; not_projected(k) = get_points_reprojection(fv2.faces,new_vertices,thisKP); dist_proj(k) = main_projections(fv2.faces,fv2.vertices,axis_masks); all_reconstr(k).vertices = single(fv2.vertices); all_reconstr(k).faces = int32(fv2.faces); if(plot_debug) %Plotting stuff figure(100); subplot(4,5,k); hold all; trisurf(fv2.faces,new_vertices(:,1),new_vertices(:,2),new_vertices(:,3),'FaceColor','red'); axis equal; axis tight; view([0 0 1]) set(gca,'ydir','rev'); set(gca,'zdir','rev'); title(num2str(k)); axis off; end end fv2 = all_reconstr; [scores] = get_ranking(not_projected, dist_proj); statistics.not_projected = not_projected; statistics.dist_proj = dist_proj; statistics.scores = scores; statistics.area_beforeFilling = area_beforeFilling; for i=1:numel(fv2) fv2(i).score = scores(i); fv2(i).dt = all_dt_models(:,i); fv2(i).triples = old_triples(i,:); end end function [volRec,area_beforeFilling] = imprinted_VisualHull(vol,volRec,mask,thisR,thisT,siz) vol = bsxfun(@plus,thisR*vol,thisT); [M,N] = size(mask); x = vol(1,:); y = vol(2,:); ma = false(size(x)); sel_ind = x >0.5 & x<N & y>0.5 & y<M; ind = sub2ind(size(mask),round(y(sel_ind)),round(x(sel_ind))); ma(sel_ind) = mask(ind); volRec = reshape(volRec,siz); min_voxel = repmat(min(volRec,[],3),[1 1 size(volRec,3)]); ma = ma(:)'; ma = reshape(ma,siz); area_beforeFilling = sum(sum(ma(:,:,1) & min_voxel(:,:,1)<0))/sum(sum(ma(:,:,1))); volRec(ma & min_voxel>0 ) = volRec(ma & min_voxel>0) - (min_voxel(ma & min_voxel>0) + 0.0001); volRec = volRec(:); end function dist_main = main_projections(tri,coord,axis_masks) % returns the distance between the projections into the planes aligned with the main axis and the % average mask for those planes m = axis_masks.size; edge = zeros(2,0,'uint32'); coord = coord*axis_masks.scale; coord = coord + m/2; projections = zeros(m,m,3); P = [ 0 0 1 0; 0 1 0 0 ; 0 0 0 1]; projections(:,:,1) = RenderTriMex(P, m, m, coord', edge, uint32(tri-1)')>0; P = [ 0 0 1 0;1 0 0 0 ; 0 0 0 1]; projections(:,:,2) = RenderTriMex(P, m, m, coord', edge, uint32(tri-1)')>0; P = [ 0 1 0 0; 1 0 0 0; 0 0 0 1]; projections(:,:,3) = RenderTriMex(P, m, m, coord', edge, uint32(tri-1)')>0; dist_main = 0; for k =1:3 if(axis_masks.exemplars(k)~=0); dist_main = dist_main + sum(sum(abs(projections(:,:,k) - axis_masks.masks(:,:,k)))); end end dist_main = dist_main/(m*m); end function [not_projected,thisKP_3D] = get_points_reprojection(tri,rot_vertices,thisKP) %Returns the number of points that does not reproject inside the shape TR2D = TriRep(tri,rot_vertices(:,1:2)); TR3D = TriRep(tri,rot_vertices); n_tri = size(tri,1); not_projected = 0; thisKP_3D = zeros(size(thisKP,1),3); for p = 1:size(thisKP,1) if(thisKP(p,1)==0 && thisKP(p,2)==0); continue; end; B = cartToBary(TR2D,(1:n_tri)',repmat(thisKP(p,:),[n_tri 1])); sel_triangles = B>=0 & B<=1; sel_triangles = find(sum(sel_triangles,2) == 3); if(~isempty(sel_triangles)) PC = baryToCart(TR3D,sel_triangles,B(sel_triangles,:)); [a,b] = min(PC(:,3)); thisKP_3D(p,:) = PC(b,:); else not_projected = not_projected+1; end end end function [Xvol, Yvol, Zvol, dt, vol] = precompute_data(R, T, really_all_masks, n_voxels,ref_id) lim = get_vol_limits(really_all_masks, R, T,ref_id); for i=1:3 step(i) = (lim(i,2) - lim(i,1)) / n_voxels; end [Xvol,Yvol,Zvol] = meshgrid(lim(1,1):step(1):lim(1,2),lim(2,1):step(2):lim(2,2),lim(3,1):step(3):lim(3,2)); sz = size(Xvol); vol = [Xvol(:)'; Yvol(:)'; Zvol(:)']; refR = R(:,:,ref_id); refT = T(:,ref_id); vol = refR\bsxfun(@minus,vol, refT); Xvol = reshape(vol(1,:)',sz); Yvol = reshape(vol(2,:)',sz); Zvol = reshape(vol(3,:)',sz); dt = zeros(size(vol,2),size(R,3)); for h=1:size(R,3) thisR = R(:,:,h); thisT = T(:,h); mask = really_all_masks{h}; rotVol = thisR*vol; rotVol = bsxfun(@plus,rotVol,thisT); dt(:,h) = distance_from_mask(mask,rotVol); end end function dt = distance_from_mask(mask,rotVol) % Returns a negative value for voxels in the volume and positive value % outside. [M,N] = size(mask); minX = floor(min(rotVol(1,:))-2); minY = floor(min(rotVol(2,:))-2); maxX = ceil(max(rotVol(1,:))+2); maxY = ceil(max(rotVol(2,:))+2); cX = max(0,-minX+1); cY = max(0,-minY+1); aux_mask = false(cY + max(maxY,M),cX + max(maxX,N)); aux_mask(cY+1:cY+M, cX+1:cX+N) = mask; rotVol(1,:) = rotVol(1,:) + cX; rotVol(2,:) = rotVol(2,:) + cY; ind = sub2ind(size(aux_mask),round(rotVol(2,:)),round(rotVol(1,:))); dt = zeros(size(rotVol,2),1); [x,y] = getXYfromMask(aux_mask); [~,IDX] = bwdist(aux_mask); sel_points = IDX(ind); d = sqrt((x(sel_points)-rotVol(1,:)').^2 + (y(sel_points)-rotVol(2,:)').^2); dt(~aux_mask(ind)) = d(~aux_mask(ind)); [~,IDX] = bwdist(~aux_mask); sel_points = IDX(ind); d = sqrt((x(sel_points)-rotVol(1,:)').^2 + (y(sel_points)-rotVol(2,:)').^2); dt(aux_mask(ind)) = -d(aux_mask(ind)); end function [x,y,m] = getXYfromMask(mask) [x,y] = meshgrid(1:size(mask,2),1:size(mask,1)); x = x(:); y = y(:); m = mask(:); end function [limits] = get_vol_limits(masks, R, T,ref_id) refR = R(:,:,ref_id); refT = T(:,ref_id); min_x = inf; min_y = min_x; min_z = min_x; max_x = -inf; max_y = max_x; max_z = max_x; for h=1:size(R,3) % get edgels bw = bwboundaries(masks{h}); bw = bw{1}; x = bw(:,2); y = bw(:,1); z = zeros(size(bw,1),1); coord = [x'; y';z']; thisR = R(:,:,h); thisT = T(:,h); coord = thisR\(bsxfun(@minus, coord, thisT)); coord = bsxfun(@plus, refR*coord, refT); min_x = min([min_x coord(1,:)]); max_x = max([max_x coord(1,:)]); min_y = min([min_y coord(2,:)]); max_y = max([max_y coord(2,:)]); min_z = min([min_z coord(3,:)]); max_z = max([max_z coord(3,:)]); end limits = [min_x max_x; min_y max_y; min_z max_z]; end
github
yihui-he/reconstructing-pascal-voc-master
subplot_auto_transparent.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/subplot_auto_transparent.m
2,761
utf_8
188f00f27307f9049757d2bfe1176afa
% Copyright (C) 2010 Joao Carreira % % This code is part of the extended implementation of the paper: % % J. Carreira, C. Sminchisescu, Constrained Parametric Min-Cuts for Automatic Object Segmentation, IEEE CVPR 2010 % %function h = subplot_auto_transparent(segments, I, titles) function [Imgs] = subplot_auto_transparent(segments, I, titles, voc_cmap_ids, grid_type) segments(segments==inf) = 10000; border_side = 0.05; border_top = 0.05; if(length(size(I))==2) I = repmat(I, [1 1 3]); end if(issparse(segments)) segments = full(segments); end if(size(segments,1) ~= size(I,1)) n_imgs = size(segments,2); else n_imgs = size(segments,3); segments = reshape(segments, size(segments,1) * size(segments,2), n_imgs); end n_rows = round(sqrt(n_imgs)); n_cols = ceil(n_imgs/n_rows); assert(n_cols*n_rows >= n_imgs); counter = 1; if(exist('voc_cmap_ids', 'var') && ~isempty(voc_cmap_ids)) cmap = VOClabelcolormap(); assert(size(segments,2) == numel(voc_cmap_ids)); for i=1:size(segments,2) bground{i} = zeros(size(I,1),size(I,2),3); bground{i}(:,:,1) = cmap(voc_cmap_ids(i),1); bground{i}(:,:,2) = cmap(voc_cmap_ids(i),2); bground{i}(:,:,3) = cmap(voc_cmap_ids(i),3); bground{i} = uint8(255*bground{i}); end else bground = zeros(size(I,1),size(I,2),3); bground(:,:,2) = 255; end Imgs = cell(n_imgs,1); for i=1:n_imgs if(size(segments,1) ~= size(I,1)) alpha_chann = reshape(segments(:,i), size(I,1), size(I,2))*0.5; else alpha_chann = segments(:,:,i)*0.5; end %sc(sc(I).*sc(alpha_chann)) if(exist('voc_cmap_ids', 'var') && ~isempty(voc_cmap_ids)) Imgs{i} = immerge(I, bground{i}, alpha_chann); else Imgs{i} = immerge(I, bground, alpha_chann); end counter = counter + 1; end %montage_new(Imgs, titles, 'Size', [n_rows n_cols], 'Border', 0.1); if(~exist('grid_type', 'var')) grid_type = []; end if(exist('titles', 'var') && ~isempty(titles)) if(~iscell(titles)) % if not a cell assumes they're numbers for i=1:length(titles) new_titles{i} = sprintf('%f', titles(i)); end titles = new_titles; end if(~exist('grid_type', 'var')) montage_new(Imgs, titles, 'Border', [border_top border_side]); else montage_new(Imgs, titles, 'Border', [border_top border_side], 'Size', grid_type); end else montage_new(Imgs, [], 'Border', [border_top border_side], 'Size', grid_type); end % hold on; % for i=1:n_imgs % if(nargin==3) % h(counter) = subplot(n_rows,n_cols,i); title(titles{i}); % end % end
github
yihui-he/reconstructing-pascal-voc-master
create_transparent_multiple_colors.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/create_transparent_multiple_colors.m
3,650
utf_8
684d20c449e8916275aac6ee636b84e1
%function I = create_transparent_multiple_colors(segments, I, titles) function merged_Img = create_transparent_multiple_colors(segments, I, use_voc_colors, labels, transparency, intensities) DefaultVal('*use_voc_colors', 'false'); DefaultVal('*transparency', '0.8'); DefaultVal('*intensities', '[]'); if(isempty(intensities)) intensities = 0.5*ones(size(segments,3),1); end % if(size(segments,3) == 1 && numel(unique(segments)) > 1) % segments = labels2binary(segments); % segments(:,1) = []; % remove 0 label % end if(length(size(I))==2) I = repmat(I, [1 1 3]); end if(issparse(segments)) segments = full(segments); end if(size(I,1) == size(segments,1)) segments = double(reshape(segments, [size(segments,1)*size(segments,2)], size(segments,3))); end n_segms = size(segments,2); merged_Img = I; bground = zeros(size(merged_Img,1), size(merged_Img,2), size(merged_Img,3)); assert(size(segments,2) == numel(intensities)); for i=1:n_segms if(use_voc_colors) if(exist('labels', 'var') && ~isempty(labels)) if(labels(i) == 21) % background bground = get_new_bg_voc(bground, segments(:,i), 0); else bground = get_new_bg_voc(bground, segments(:,i), labels(i)); end else bground = get_new_bg_voc(bground, segments(:,i), i); end else bground = get_new_bg_intensities(bground, segments(:,i), intensities(i)); end alpha_chann = double(reshape(segments(:,i), size(I,1), size(I,2)))*transparency; merged_Img = immerge(merged_Img, bground, alpha_chann); end end function bground = get_new_bg_voc(previous_bg, mask, i) bground = zeros(size(previous_bg)); cmap = VOClabelcolormap(256); bground(:,:,1) = cmap(i+1,1)*255; bground(:,:,2) = cmap(i+1,2)*255; bground(:,:,3) = cmap(i+1,3)*255; mask_rs = repmat(reshape(mask,size(bground,1), size(bground,2)),[1 1 3]); bground = bground.*mask_rs; bground = previous_bg + bground; end function bground = get_new_bg_intensities(previous_bg, mask, intensity) cmap = colormap('jet'); intensity = max(1, round((intensity*size(cmap,1)))); intensity = max(0, intensity); %end %max_intens = max(intensities); bground = zeros(size(previous_bg)); bground(:,:,1) = cmap(intensity,1); bground(:,:,2) = cmap(intensity,2); bground(:,:,3) = cmap(intensity,3); bground = 255*bground; mask_rs = repmat(reshape(mask,size(bground,1), size(bground,2)),[1 1 3]); bground = bground.*mask_rs; bground = previous_bg + bground; end function bground = get_new_bg(previous_bg, mask, i) bground = zeros(size(previous_bg)); if(i==1) bground(:,:,2) = 255; elseif(i==2) bground(:,:,1) = 255; elseif(i==3) bground(:,:,3) = 255; elseif(i==4) bground(:,:,1) = 255; bground(:,:,2) = 255; elseif(i==5) bground(:,:,1) = 255; bground(:,:,3) = 255; elseif(i==6) bground(:,:,2) = 255; bground(:,:,3) = 255; elseif(i==7) bground(:,:,1) = 125; bground(:,:,2) = 255; elseif(i==7) bground(:,:,1) = 125; bground(:,:,3) = 255; elseif(i==8) bground(:,:,2) = 125; bground(:,:,3) = 255; elseif(i>=9) bground(:,:,1) = rand()*255; bground(:,:,2) = rand()*255; bground(:,:,3) = rand()*255; end mask_rs = repmat(reshape(mask,size(bground,1), size(bground,2)),[1 1 3]); bground = bground.*mask_rs; bground = previous_bg + bground; end
github
yihui-he/reconstructing-pascal-voc-master
subplot_auto_transparent_parts.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/subplot_auto_transparent_parts.m
2,461
utf_8
91078f7661ffb5b11fda99cc06c46ce6
%function h = subplot_auto_transparent(segments, I, titles) function [Imgs] = subplot_auto_transparent_parts(whole_segment, part_segments, I, titles, grid_type) if(isempty(part_segments)) Imgs = []; return; end part_segments(part_segments==inf) = 10000; border_side = 0.05; border_top = 0.05; if(length(size(I))==2) I = repmat(I, [1 1 3]); end if(issparse(part_segments)) part_segments = full(part_segments); end if(size(part_segments,1) ~= size(I,1)) n_imgs = size(part_segments,2); else n_imgs = size(part_segments,3); part_segments = reshape(part_segments, size(part_segments,1) * size(part_segments,2), n_imgs); end n_rows = round(sqrt(n_imgs)); n_cols = ceil(n_imgs/n_rows); assert(n_cols*n_rows >= n_imgs); counter = 1; % sets the color of the whole bground = zeros(size(I,1),size(I,2),3); bground(:,:,3) = 255; % sets the color of the parts bground_parts = zeros(size(I,1),size(I,2),3); bground_parts(:,:,1) = 255; bground_parts(:,:,2) = 255; Imgs = cell(n_imgs,1); if(size(part_segments,1) ~= size(I,1)) alpha_chann_whole = reshape(whole_segment, size(I,1), size(I,2))*0.5; else alpha_chann_whole = whole_segment*0.5; end for i=1:n_imgs if(size(part_segments,1) ~= size(I,1)) alpha_chann_part = reshape(part_segments(:,i), size(I,1), size(I,2))*0.5; else alpha_chann_part = part_segments(:,:,i)*0.5; end Imgs{i} = immerge(I, bground, alpha_chann_whole); Imgs{i} = immerge(Imgs{i}, bground_parts, alpha_chann_part); counter = counter + 1; end %montage_new(Imgs, titles, 'Size', [n_rows n_cols], 'Border', 0.1); if(~exist('grid_type', 'var')) grid_type = []; end if(exist('titles', 'var') && ~isempty(titles)) if(~iscell(titles)) % if not a cell assumes they're numbers for i=1:length(titles) new_titles{i} = sprintf('%f', titles(i)); end titles = new_titles; end if(~exist('grid_type', 'var')) montage_new(Imgs, titles, 'Border', [border_top border_side]); else montage_new(Imgs, titles, 'Border', [border_top border_side], 'Size', grid_type); end else montage_new(Imgs, [], 'Border', [border_top border_side], 'Size', grid_type); end % hold on; % for i=1:n_imgs % if(nargin==3) % h(counter) = subplot(n_rows,n_cols,i); title(titles{i}); % end % end
github
yihui-he/reconstructing-pascal-voc-master
SvmSegm_study_segment_quality.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/SvmSegm_study_segment_quality.m
9,068
utf_8
21b9677e95348739b7b27093457cfe01
%function SvmSegm_study_segment_quality(exp_dir, segm_name, the_imgset, segm_quality_type) function SvmSegm_study_segment_quality(exp_dir, segm_name, the_imgset, segm_quality_type, class_label) DefaultVal('class_label', '[]'); if(~iscell(segm_name)) segm_name = {segm_name}; end % can write segment statistics into [exp MyStatistics] % one file per segmentation algorithm %statistics_dir = [exp_dir 'MyStatistics/']; %if(~exist(statistics_dir, 'dir')) % mkdir(statistics_dir); %end if(~iscell(the_imgset)) img_names =textread([exp_dir '/ImageSets/Segmentation/' the_imgset '.txt'], '%s'); else if(5 > numel(the_imgset)) error('if it''s a imgset, don''t pass as cell!'); end img_names = the_imgset; end segm_eval_dir = [exp_dir 'SegmentEval/']; Q = {}; for i=1:numel(segm_name) mask_type = segm_name; direct = [segm_eval_dir mask_type{i} '/' segm_quality_type '/' ]; if(~exist(direct, 'dir')) error('directory doesn''t exist'); end thisQ = cell(numel(img_names),1); for j=1:numel(img_names) if(exist([direct img_names{j} '.mat'], 'file')) Quality = myload([direct img_names{j} '.mat'], 'Quality'); if(~iscell(Quality)) % for backward data compatibility Quality = {Quality}; end thisQ{j} = Quality; else disp('didnt find a file'); [direct img_names{j} '.mat'] end end if(isempty(Q)) Q = thisQ; else for j=1:numel(thisQ) for k = 1:numel(thisQ{j}) for l=1:numel(thisQ{j}{k}) Q{j}{k}(l).q = [Q{j}{k}(l).q; thisQ{j}{k}(l).q]; Q{j}{k}(l).sz = [Q{j}{k}(l).sz; thisQ{j}{k}(l).sz]; end end end end %Q = cellfun(@conc, Q, thisQ, 'UniformOutput', false); end counter = 1; if(~isempty(class_label)) cells_to_remove = false(numel(Q),1); for j=1:numel(Q) % iterate over images to_remove = ([Q{j}{1}(:).class] ~= class_label); Q{j}{1}(to_remove) = []; if(isempty(Q{j}{1})) cells_to_remove(j) = true; end end Q(cells_to_remove) = []; end avg_img_overlap = zeros(numel(Q),1); for i=1:numel(Q) % iterate over images avg_gt_overlap = zeros(numel(Q{i}),1); for j=1:numel(Q{i}) % iterate over gt segmentations max_gt_overlaps = zeros(numel(Q{i}{j}),1); mean_gt_overlaps = max_gt_overlaps; for k=1:numel(Q{i}{j}) % iterate over regions in the gt segmentation if(Q{i}{j}(k).class<255) if(~isempty(Q{i}{j}(k).q)) m(counter) = max(Q{i}{j}(k).q); avg(counter) = mean(Q{i}{j}(k).q); mean_gt_overlaps(k) = mean(Q{i}{j}(k).q); else m(counter) = 0; avg(counter) = 0; mean_gt_overlaps(k) = 0; end max_gt_overlaps(k) = m(counter); counter = counter + 1; end end avg_gt_overlap(j) = mean(max_gt_overlaps); end avg_img_overlap(i) = mean(avg_gt_overlap); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% disp(['Dataset Avg Best ' segm_quality_type ':']); avg_best = mean(m) std_dev = std(m) avg_avg = mean(avg) avg_img_overlap(isnan(avg_img_overlap)) = []; disp(['Img Avg Best' segm_quality_type ':']); avg_best = mean(avg_img_overlap) std_dev = std(avg_img_overlap) disp(['Img Best Segmentation Covering with ' segm_quality_type ' score (avg over multiple GT):']); best_single_coverage = zeros(numel(Q), 1); best_single_coverage_best_GT = zeros(numel(Q), 1); for i=1:numel(Q) % iterate over images this_image_best_single_coverage = zeros(numel(Q{i}),1); for j=1:numel(Q{i}) % iterate over gt segmentations max_val = []; n_pixels_in_segments = []; total_n_pixels_gt = 0; the_k= []; for k=1:numel(Q{i}{j}) % iterate over regions in the image if(Q{i}{j}(k).class >= 255) continue; end if(~isempty(Q{i}{j}(k).q)) [max_val(k), id] = max(Q{i}{j}(k).q); n_pixels_in_segments(k) = Q{i}{j}(k).sz(id); else max_val(k) = 0; n_pixels_in_segments(k) = 0; end total_n_pixels_gt= total_n_pixels_gt + Q{i}{j}(k).object_sz; the_k = [the_k k]; end max_val = max_val'; if(~isempty(the_k)) this_image_best_single_coverage(j) = (1/total_n_pixels_gt) * ([Q{i}{j}(the_k).object_sz]*max_val); else this_image_best_single_coverage(j) = -1; end end best_single_coverage(i) = mean(this_image_best_single_coverage); % average over humans if(isempty(this_image_best_single_coverage)) this_image_best_single_coverage = -1; end best_single_coverage_best_GT(i) = max(this_image_best_single_coverage); % best over humans end % remove the ones we haven't computed best_single_coverage_best_GT(best_single_coverage_best_GT == -1) = []; best_single_coverage(best_single_coverage==-1) = []; best_single_coverage(isnan(best_single_coverage)) = []; avg_best_covering = mean(best_single_coverage) std_dev_covering = std(best_single_coverage) disp(['Img Best Segmentation Covering with ' segm_quality_type ' score (best over multiple GT) :']); avg_best_single_covering = mean(best_single_coverage_best_GT) std_dev_single_covering = mean(best_single_coverage_best_GT) n_segms = 0; num_Q = 0; for i=1:numel(Q) % count the number of segments we've got if(~isempty(Q{i})) n_segms = n_segms + numel(Q{i}{1}(1).sz); num_Q = num_Q + 1; end end avg_num_segments = sum(n_segms) / num_Q %visualize_bad_examples(exp_dir, segm_name{1}, img_names, best_single_coverage) %save([statistics_dir cell2mat(mask_type) '.mat'], 'avg_best', 'std_dev', 'avg_best_covering', 'std_dev_covering', ... % 'avg_num_segments'); end function visualize_bad_examples(exp_dir, segm_name, img_names, best_single_coverage_best_GT, overlap_type) [sorted_vals, ids] = sort(best_single_coverage_best_GT, 'descend'); %[sorted_vals, ids] = sort(best_single_coverage_best_GT); for i=1:numel(ids) I = imread([exp_dir 'JPEGImages/' img_names{ids(i)} '.jpg']); Quality = myload([exp_dir 'SegmentEval/' segm_name '/' overlap_type '/' img_names{ids(i)} '.mat'], 'Quality'); if(~iscell(Quality)) % for backward data compatibility Quality = {Quality}; end % load segments sorted_vals(i) load([exp_dir 'MySegmentsMat/' segm_name '/' img_names{ids(i)} '.mat']); SvmSegm_show_best_segments(I,Quality, masks); figure; %subplot_auto_transparent(masks, I); % load all ground truth segmentations files = dir([exp_dir 'SegmentationObject/' img_names{ids(i)} '*']); %files = dir([exp_dir 'SegmentationSurfaces/' img_names{ids(i)} '*']); for j=1:numel(files) %filenames{j} = [exp_dir 'SegmentationSurfaces/' files(j).name]; filenames{j} = [exp_dir 'SegmentationObject/' files(j).name]; %gt{j} = imread([exp_dir 'SegmentationObject/' files(i).name]); end map = VOClabelcolormap(256); subplot(1,2,1), montage(filenames, map); subplot(1,2,2), sc(I); pause; close all; end end function res = conc(old,new) res = old; if(isfield(old, 'q')) for i=1:numel(new) res(i).q = [old(i).q; new(i).q]; res(i).sz = [old(i).sz; new(i).sz]; end else res = new; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % histogram gt segments with respect to their size, then see avg quality per bin % disp(['Segment Quality with gt segment size']); % duh = [Q{:}]; % gt_sizes = [duh(:).object_sz]; % [pos, sz] = hist(log10(gt_sizes), 30) % [pos, bin] = histc(log10(gt_sizes), [0 sz inf]); % % 10.^sz % for i=1:30 % qual_hist(i) = sum(m(bin==i))/sum(bin==i); % end % qual_hist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
yihui-he/reconstructing-pascal-voc-master
subplot_auto_transparent_multiple_imgs.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/subplot_auto_transparent_multiple_imgs.m
2,014
utf_8
d81c1bc1a30614034d8e3c52877170bd
%function h = subplot_auto_transparent(segments, I, titles) function [Imgs, handles] = subplot_auto_transparent_multiple_imgs(segments, I, titles, voc_cmap_ids, grid_type) border_side = 0.05; border_top = 0.05; for i=1:numel(I) if(length(size(I{i}))==2) I{i} = repmat(I{i}, [1 1 3]); end counter = 1; if(exist('voc_cmap_ids', 'var') && ~isempty(voc_cmap_ids)) cmap = VOClabelcolormap(); assert(size(segments,2) == numel(voc_cmap_ids)); bground{i} = zeros(size(I,1),size(I,2),3); bground{i}(:,:,1) = cmap(voc_cmap_ids(i),1); bground{i}(:,:,2) = cmap(voc_cmap_ids(i),2); bground{i}(:,:,3) = cmap(voc_cmap_ids(i),3); bground{i} = uint8(255*bground{i}); else bground{i} = zeros(size(I{i},1),size(I{i},2),3); bground{i}(:,:,2) = 255; end end Imgs = I; n_imgs = numel(Imgs); for i=1:n_imgs alpha_chann = segments{i}*0.5; %sc(sc(I).*sc(alpha_chann)) Imgs{i} = immerge(Imgs{i}, bground{i}, alpha_chann); counter = counter + 1; end %montage_new(Imgs, titles, 'Size', [n_rows n_cols], 'Border', 0.1); if(~exist('grid_type', 'var')) grid_type = []; end if(exist('titles', 'var') && ~isempty(titles)) if(~iscell(titles)) % if not a cell assumes they're numbers for i=1:length(titles) new_titles{i} = sprintf('%f', titles(i)); end titles = new_titles; end if(~exist('grid_type', 'var')) handles = montage_new(Imgs, titles, 'Border', [border_top border_side]); else handles = montage_new(Imgs, titles, 'Border', [border_top border_side], 'Size', grid_type); end else handles = montage_new(Imgs, [], 'Border', [border_top border_side], 'Size', grid_type); end % hold on; % for i=1:n_imgs % if(nargin==3) % h(counter) = subplot(n_rows,n_cols,i); title(titles{i}); % end % end
github
yihui-he/reconstructing-pascal-voc-master
test_SegmBrowser.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/test_SegmBrowser.m
1,945
utf_8
6f119003d6ae9e17e0586114c290e539
% Joao Carreira September 2012 % Run this in debug mode and do step by step for checking the outputs it gives function test_SegmBrowser() % run this after setting up the VOC dataset (see in VOC_experiment % folder) exp_dir = '../../VOC_experiment/VOC/'; mask_type = 'CPMC_segms_150_sp_approx'; imgset = 'train11'; overlap_type = 'overlap'; addpath('../'); addpath('../../external_src/'); addpath('../../external_src/immerge/'); % first time it runs it may take a few seconds, then it caches everything % it needs b = SegmBrowser(exp_dir, mask_type, imgset, overlap_type); % % Images, objects and segments have numerical identifiers that apply % given the imgset % % If you want to get features for both ThreeAmigos and GroundTruth masks, % I suggest you create two SegmBrowser objects, one for each type. % imgname = '2007_000032'; % get id of the image img_id = b.img_names_to_ids(imgname); % show image b.show_imgs(img_id); if 1 % get segment (whole) ids for that image segment_ids = b.img_2_whole_ids(img_id); % show first 50 segments for image b.show_wholes(segment_ids{1}(1:50)) % show best segments for that image b.show_best_masks(imgname); % get overlaps for image overlap_img = b.get_overlaps_img(b.img_names{img_id}); end if 1 % get labels for all segments (by finding max overlap) [labels] = b.get_labels_wholes(); % get img object ids and overlaps for a particular class, one cell for % each image [img_ids, obj_ids, Q] = b.collect_category_imgs(1) % show objects in first image of this category b.show_objects(obj_ids{1}); % get overlap for all segments of class 1 [overlap_class] = b.get_overlap_wholes_objclass(1); end % to get all best masks for cow, not sure if useful categ_masks = b.collect_all_category_best_masks('cow'); end
github
yihui-he/reconstructing-pascal-voc-master
subplot_auto_transparent_parts_multiple_imgs.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/subplot_auto_transparent_parts_multiple_imgs.m
1,518
utf_8
b998d26146d60227cdfe498683e72ebe
%function h = subplot_auto_transparent(segments, I, titles) function [Imgs] = subplot_auto_transparent_parts_multiple_imgs(whole_segments, part_segments, I, titles) border_side = 0.05; border_top = 0.05; Imgs = I; for i=1:numel(I) if(length(size(I{i}))==2) I{i} = repmat(I{i}, [1 1 3]); end % sets the color of the whole bground = zeros(size(I{i},1),size(I{i},2),3); bground(:,:,3) = 255; % sets the color of the parts bground_parts = zeros(size(I{i},1),size(I{i},2),3); bground_parts(:,:,1) = 255; bground_parts(:,:,2) = 255; alpha_chann_whole = reshape(whole_segments{i}, size(I{i},1), size(I{i},2))*0.5; alpha_chann_part = part_segments{i}*0.5; Imgs{i} = immerge(I{i}, bground, alpha_chann_whole); Imgs{i} = immerge(Imgs{i}, bground_parts, alpha_chann_part); end if(exist('titles', 'var') && ~isempty(titles)) if(~iscell(titles)) % if not a cell assumes they're numbers for i=1:length(titles) new_titles{i} = sprintf('%f', titles(i)); end titles = new_titles; end if(~exist('grid_type', 'var')) montage_new(Imgs, titles, 'Border', [border_top border_side]); end else montage_new(Imgs, [], 'Border', [border_top border_side]); end % hold on; % for i=1:n_imgs % if(nargin==3) % h(counter) = subplot(n_rows,n_cols,i); title(titles{i}); % end % end end
github
yihui-he/reconstructing-pascal-voc-master
subplot_auto_transparent_parts_noov.m
.m
reconstructing-pascal-voc-master/src/SegmBrowser/subplot_auto_transparent_parts_noov.m
2,811
utf_8
a7b44e92af8526f4c46cc3a01df16eb6
%function h = subplot_auto_transparent(segments, I, titles) function [Imgs] = subplot_auto_transparent_parts_noov(whole_segment, part_segments, I, voc_color_ids, titles, grid_type) DefaultVal('*voc_color_ids', '[]'); if(isempty(part_segments)) Imgs = []; return; end if(~iscell(whole_segment)) whole_segment = {whole_segment}; part_segments = {part_segments}; I = {I}; else assert(iscell(part_segments)); assert(iscell(I)); end border_side = 0.05; border_top = 0.05; n_rows = 1; n_cols = numel(I); counter = 1; cmap = VOClabelcolormap(256); n_imgs = numel(I); Imgs = cell(n_imgs,1); for h=1:n_imgs if(length(size(I{h}))==2) I{h} = repmat(I{h}, [1 1 3]); end if(issparse(part_segments{h})) part_segments{h} = full(part_segments{h}); end if(size(part_segments,1) ~= size(I,1)) alpha_chann_whole = reshape(whole_segment{h}, size(I{h},1), size(I{h},2))*0.5; else alpha_chann_whole = whole_segment{h}*0.5; end Imgs{h} = I{h}; bground = zeros(size(I{h},1),size(I{h},2),3); bground(:,:,3) = 255; if(isempty(part_segments{h})) Imgs{h} = immerge(Imgs{h}, bground, alpha_chann_whole); else for i=1:size(part_segments{h},3) alpha_chann_part = part_segments{h}(:,:,i)*0.7; if(~isempty(voc_color_ids)) c_id = voc_color_ids{h}(i); else c_id = i; end bground_parts = zeros(size(I{h},1),size(I{h},2),3); bground_parts(:,:,1) = cmap(c_id, 1)*255; bground_parts(:,:,2) = cmap(c_id, 2)*255; bground_parts(:,:,3) = cmap(c_id, 3)*255; Imgs{h} = immerge(Imgs{h}, bground_parts, alpha_chann_part); % counter = counter + 1; end end end %montage_new(Imgs, titles, 'Size', [n_rows n_cols], 'Border', 0.1); if(~exist('grid_type', 'var')) grid_type = []; end if(exist('titles', 'var') && ~isempty(titles)) if(~iscell(titles)) % if not a cell assumes they're numbers for i=1:length(titles) new_titles{i} = sprintf('%f', titles(i)); end titles = new_titles; end if(~exist('grid_type', 'var')) montage_new(Imgs, titles, 'Border', [border_top border_side]); else montage_new(Imgs, titles, 'Border', [border_top border_side], 'Size', grid_type); end else montage_new(Imgs, [], 'Border', [border_top border_side], 'Size', grid_type); end % hold on; % for i=1:n_imgs % if(nargin==3) % h(counter) = subplot(n_rows,n_cols,i); title(titles{i}); % end % end
github
zzlyw/machine-learning-exercises-master
submit.m
.m
machine-learning-exercises-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
zzlyw/machine-learning-exercises-master
submitWithConfiguration.m
.m
machine-learning-exercises-master/machine-learning-ex2/ex2/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
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('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); 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(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); 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 % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
zzlyw/machine-learning-exercises-master
savejson.m
.m
machine-learning-exercises-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
zzlyw/machine-learning-exercises-master
loadjson.m
.m
machine-learning-exercises-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
zzlyw/machine-learning-exercises-master
loadubjson.m
.m
machine-learning-exercises-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
zzlyw/machine-learning-exercises-master
saveubjson.m
.m
machine-learning-exercises-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
zzlyw/machine-learning-exercises-master
submit.m
.m
machine-learning-exercises-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
github
zzlyw/machine-learning-exercises-master
submitWithConfiguration.m
.m
machine-learning-exercises-master/machine-learning-ex4/ex4/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
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('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); 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(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); 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 % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
zzlyw/machine-learning-exercises-master
savejson.m
.m
machine-learning-exercises-master/machine-learning-ex4/ex4/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
zzlyw/machine-learning-exercises-master
loadjson.m
.m
machine-learning-exercises-master/machine-learning-ex4/ex4/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
zzlyw/machine-learning-exercises-master
loadubjson.m
.m
machine-learning-exercises-master/machine-learning-ex4/ex4/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
zzlyw/machine-learning-exercises-master
saveubjson.m
.m
machine-learning-exercises-master/machine-learning-ex4/ex4/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
zzlyw/machine-learning-exercises-master
submit.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/submit.m
1,318
utf_8
bfa0b4ffb8a7854d8e84276e91818107
function submit() addpath('./lib'); conf.assignmentSlug = 'support-vector-machines'; conf.itemName = 'Support Vector Machines'; conf.partArrays = { ... { ... '1', ... { 'gaussianKernel.m' }, ... 'Gaussian Kernel', ... }, ... { ... '2', ... { 'dataset3Params.m' }, ... 'Parameters (C, sigma) for Dataset 3', ... }, ... { ... '3', ... { 'processEmail.m' }, ... 'Email Preprocessing', ... }, ... { ... '4', ... { 'emailFeatures.m' }, ... 'Email Feature Extraction', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases x1 = sin(1:10)'; x2 = cos(1:10)'; ec = 'the quick brown fox jumped over the lazy dog'; wi = 1 + abs(round(x1 * 1863)); wi = [wi ; wi]; if partId == '1' sim = gaussianKernel(x1, x2, 2); out = sprintf('%0.5f ', sim); elseif partId == '2' load('ex6data3.mat'); [C, sigma] = dataset3Params(X, y, Xval, yval); out = sprintf('%0.5f ', C); out = [out sprintf('%0.5f ', sigma)]; elseif partId == '3' word_indices = processEmail(ec); out = sprintf('%d ', word_indices); elseif partId == '4' x = emailFeatures(wi); out = sprintf('%d ', x); end end
github
zzlyw/machine-learning-exercises-master
porterStemmer.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/porterStemmer.m
9,902
utf_8
7ed5acd925808fde342fc72bd62ebc4d
function stem = porterStemmer(inString) % Applies the Porter Stemming algorithm as presented in the following % paper: % Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, % no. 3, pp 130-137 % Original code modeled after the C version provided at: % http://www.tartarus.org/~martin/PorterStemmer/c.txt % The main part of the stemming algorithm starts here. b is an array of % characters, holding the word to be stemmed. The letters are in b[k0], % b[k0+1] ending at b[k]. In fact k0 = 1 in this demo program (since % matlab begins indexing by 1 instead of 0). k is readjusted downwards as % the stemming progresses. Zero termination is not in fact used in the % algorithm. % To call this function, use the string to be stemmed as the input % argument. This function returns the stemmed word as a string. % Lower-case string inString = lower(inString); global j; b = inString; k = length(b); k0 = 1; j = k; % With this if statement, strings of length 1 or 2 don't go through the % stemming process. Remove this conditional to match the published % algorithm. stem = b; if k > 2 % Output displays per step are commented out. %disp(sprintf('Word to stem: %s', b)); x = step1ab(b, k, k0); %disp(sprintf('Steps 1A and B yield: %s', x{1})); x = step1c(x{1}, x{2}, k0); %disp(sprintf('Step 1C yields: %s', x{1})); x = step2(x{1}, x{2}, k0); %disp(sprintf('Step 2 yields: %s', x{1})); x = step3(x{1}, x{2}, k0); %disp(sprintf('Step 3 yields: %s', x{1})); x = step4(x{1}, x{2}, k0); %disp(sprintf('Step 4 yields: %s', x{1})); x = step5(x{1}, x{2}, k0); %disp(sprintf('Step 5 yields: %s', x{1})); stem = x{1}; end % cons(j) is TRUE <=> b[j] is a consonant. function c = cons(i, b, k0) c = true; switch(b(i)) case {'a', 'e', 'i', 'o', 'u'} c = false; case 'y' if i == k0 c = true; else c = ~cons(i - 1, b, k0); end end % mseq() measures the number of consonant sequences between k0 and j. If % c is a consonant sequence and v a vowel sequence, and <..> indicates % arbitrary presence, % <c><v> gives 0 % <c>vc<v> gives 1 % <c>vcvc<v> gives 2 % <c>vcvcvc<v> gives 3 % .... function n = measure(b, k0) global j; n = 0; i = k0; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; while true while true if i > j return end if cons(i, b, k0) break; end i = i + 1; end i = i + 1; n = n + 1; while true if i > j return end if ~cons(i, b, k0) break; end i = i + 1; end i = i + 1; end % vowelinstem() is TRUE <=> k0,...j contains a vowel function vis = vowelinstem(b, k0) global j; for i = k0:j, if ~cons(i, b, k0) vis = true; return end end vis = false; %doublec(i) is TRUE <=> i,(i-1) contain a double consonant. function dc = doublec(i, b, k0) if i < k0+1 dc = false; return end if b(i) ~= b(i-1) dc = false; return end dc = cons(i, b, k0); % cvc(j) is TRUE <=> j-2,j-1,j has the form consonant - vowel - consonant % and also if the second c is not w,x or y. this is used when trying to % restore an e at the end of a short word. e.g. % % cav(e), lov(e), hop(e), crim(e), but % snow, box, tray. function c1 = cvc(i, b, k0) if ((i < (k0+2)) || ~cons(i, b, k0) || cons(i-1, b, k0) || ~cons(i-2, b, k0)) c1 = false; else if (b(i) == 'w' || b(i) == 'x' || b(i) == 'y') c1 = false; return end c1 = true; end % ends(s) is TRUE <=> k0,...k ends with the string s. function s = ends(str, b, k) global j; if (str(length(str)) ~= b(k)) s = false; return end % tiny speed-up if (length(str) > k) s = false; return end if strcmp(b(k-length(str)+1:k), str) s = true; j = k - length(str); return else s = false; end % setto(s) sets (j+1),...k to the characters in the string s, readjusting % k accordingly. function so = setto(s, b, k) global j; for i = j+1:(j+length(s)) b(i) = s(i-j); end if k > j+length(s) b((j+length(s)+1):k) = ''; end k = length(b); so = {b, k}; % rs(s) is used further down. % [Note: possible null/value for r if rs is called] function r = rs(str, b, k, k0) r = {b, k}; if measure(b, k0) > 0 r = setto(str, b, k); end % step1ab() gets rid of plurals and -ed or -ing. e.g. % caresses -> caress % ponies -> poni % ties -> ti % caress -> caress % cats -> cat % feed -> feed % agreed -> agree % disabled -> disable % matting -> mat % mating -> mate % meeting -> meet % milling -> mill % messing -> mess % meetings -> meet function s1ab = step1ab(b, k, k0) global j; if b(k) == 's' if ends('sses', b, k) k = k-2; elseif ends('ies', b, k) retVal = setto('i', b, k); b = retVal{1}; k = retVal{2}; elseif (b(k-1) ~= 's') k = k-1; end end if ends('eed', b, k) if measure(b, k0) > 0; k = k-1; end elseif (ends('ed', b, k) || ends('ing', b, k)) && vowelinstem(b, k0) k = j; retVal = {b, k}; if ends('at', b, k) retVal = setto('ate', b(k0:k), k); elseif ends('bl', b, k) retVal = setto('ble', b(k0:k), k); elseif ends('iz', b, k) retVal = setto('ize', b(k0:k), k); elseif doublec(k, b, k0) retVal = {b, k-1}; if b(retVal{2}) == 'l' || b(retVal{2}) == 's' || ... b(retVal{2}) == 'z' retVal = {retVal{1}, retVal{2}+1}; end elseif measure(b, k0) == 1 && cvc(k, b, k0) retVal = setto('e', b(k0:k), k); end k = retVal{2}; b = retVal{1}(k0:k); end j = k; s1ab = {b(k0:k), k}; % step1c() turns terminal y to i when there is another vowel in the stem. function s1c = step1c(b, k, k0) global j; if ends('y', b, k) && vowelinstem(b, k0) b(k) = 'i'; end j = k; s1c = {b, k}; % step2() maps double suffices to single ones. so -ization ( = -ize plus % -ation) maps to -ize etc. note that the string before the suffix must give % m() > 0. function s2 = step2(b, k, k0) global j; s2 = {b, k}; switch b(k-1) case {'a'} if ends('ational', b, k) s2 = rs('ate', b, k, k0); elseif ends('tional', b, k) s2 = rs('tion', b, k, k0); end; case {'c'} if ends('enci', b, k) s2 = rs('ence', b, k, k0); elseif ends('anci', b, k) s2 = rs('ance', b, k, k0); end; case {'e'} if ends('izer', b, k) s2 = rs('ize', b, k, k0); end; case {'l'} if ends('bli', b, k) s2 = rs('ble', b, k, k0); elseif ends('alli', b, k) s2 = rs('al', b, k, k0); elseif ends('entli', b, k) s2 = rs('ent', b, k, k0); elseif ends('eli', b, k) s2 = rs('e', b, k, k0); elseif ends('ousli', b, k) s2 = rs('ous', b, k, k0); end; case {'o'} if ends('ization', b, k) s2 = rs('ize', b, k, k0); elseif ends('ation', b, k) s2 = rs('ate', b, k, k0); elseif ends('ator', b, k) s2 = rs('ate', b, k, k0); end; case {'s'} if ends('alism', b, k) s2 = rs('al', b, k, k0); elseif ends('iveness', b, k) s2 = rs('ive', b, k, k0); elseif ends('fulness', b, k) s2 = rs('ful', b, k, k0); elseif ends('ousness', b, k) s2 = rs('ous', b, k, k0); end; case {'t'} if ends('aliti', b, k) s2 = rs('al', b, k, k0); elseif ends('iviti', b, k) s2 = rs('ive', b, k, k0); elseif ends('biliti', b, k) s2 = rs('ble', b, k, k0); end; case {'g'} if ends('logi', b, k) s2 = rs('log', b, k, k0); end; end j = s2{2}; % step3() deals with -ic-, -full, -ness etc. similar strategy to step2. function s3 = step3(b, k, k0) global j; s3 = {b, k}; switch b(k) case {'e'} if ends('icate', b, k) s3 = rs('ic', b, k, k0); elseif ends('ative', b, k) s3 = rs('', b, k, k0); elseif ends('alize', b, k) s3 = rs('al', b, k, k0); end; case {'i'} if ends('iciti', b, k) s3 = rs('ic', b, k, k0); end; case {'l'} if ends('ical', b, k) s3 = rs('ic', b, k, k0); elseif ends('ful', b, k) s3 = rs('', b, k, k0); end; case {'s'} if ends('ness', b, k) s3 = rs('', b, k, k0); end; end j = s3{2}; % step4() takes off -ant, -ence etc., in context <c>vcvc<v>. function s4 = step4(b, k, k0) global j; switch b(k-1) case {'a'} if ends('al', b, k) end; case {'c'} if ends('ance', b, k) elseif ends('ence', b, k) end; case {'e'} if ends('er', b, k) end; case {'i'} if ends('ic', b, k) end; case {'l'} if ends('able', b, k) elseif ends('ible', b, k) end; case {'n'} if ends('ant', b, k) elseif ends('ement', b, k) elseif ends('ment', b, k) elseif ends('ent', b, k) end; case {'o'} if ends('ion', b, k) if j == 0 elseif ~(strcmp(b(j),'s') || strcmp(b(j),'t')) j = k; end elseif ends('ou', b, k) end; case {'s'} if ends('ism', b, k) end; case {'t'} if ends('ate', b, k) elseif ends('iti', b, k) end; case {'u'} if ends('ous', b, k) end; case {'v'} if ends('ive', b, k) end; case {'z'} if ends('ize', b, k) end; end if measure(b, k0) > 1 s4 = {b(k0:j), j}; else s4 = {b(k0:k), k}; end % step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. function s5 = step5(b, k, k0) global j; j = k; if b(k) == 'e' a = measure(b, k0); if (a > 1) || ((a == 1) && ~cvc(k-1, b, k0)) k = k-1; end end if (b(k) == 'l') && doublec(k, b, k0) && (measure(b, k0) > 1) k = k-1; end s5 = {b(k0:k), k};
github
zzlyw/machine-learning-exercises-master
submitWithConfiguration.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
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('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); 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(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); 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 % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
zzlyw/machine-learning-exercises-master
savejson.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/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
zzlyw/machine-learning-exercises-master
loadjson.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/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
zzlyw/machine-learning-exercises-master
loadubjson.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/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
zzlyw/machine-learning-exercises-master
saveubjson.m
.m
machine-learning-exercises-master/machine-learning-ex6/ex6/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
zzlyw/machine-learning-exercises-master
submit.m
.m
machine-learning-exercises-master/machine-learning-ex7/ex7/submit.m
1,438
utf_8
665ea5906aad3ccfd94e33a40c58e2ce
function submit() addpath('./lib'); conf.assignmentSlug = 'k-means-clustering-and-pca'; conf.itemName = 'K-Means Clustering and PCA'; conf.partArrays = { ... { ... '1', ... { 'findClosestCentroids.m' }, ... 'Find Closest Centroids (k-Means)', ... }, ... { ... '2', ... { 'computeCentroids.m' }, ... 'Compute Centroid Means (k-Means)', ... }, ... { ... '3', ... { 'pca.m' }, ... 'PCA', ... }, ... { ... '4', ... { 'projectData.m' }, ... 'Project Data (PCA)', ... }, ... { ... '5', ... { 'recoverData.m' }, ... 'Recover Data (PCA)', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = reshape(sin(1:165), 15, 11); Z = reshape(cos(1:121), 11, 11); C = Z(1:5, :); idx = (1 + mod(1:15, 3))'; if partId == '1' idx = findClosestCentroids(X, C); out = sprintf('%0.5f ', idx(:)); elseif partId == '2' centroids = computeCentroids(X, idx, 3); out = sprintf('%0.5f ', centroids(:)); elseif partId == '3' [U, S] = pca(X); out = sprintf('%0.5f ', abs([U(:); S(:)])); elseif partId == '4' X_proj = projectData(X, Z, 5); out = sprintf('%0.5f ', X_proj(:)); elseif partId == '5' X_rec = recoverData(X(:,1:5), Z, 5); out = sprintf('%0.5f ', X_rec(:)); end end
github
zzlyw/machine-learning-exercises-master
submitWithConfiguration.m
.m
machine-learning-exercises-master/machine-learning-ex7/ex7/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
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('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); 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(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); 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 % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
zzlyw/machine-learning-exercises-master
savejson.m
.m
machine-learning-exercises-master/machine-learning-ex7/ex7/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
zzlyw/machine-learning-exercises-master
loadjson.m
.m
machine-learning-exercises-master/machine-learning-ex7/ex7/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
zzlyw/machine-learning-exercises-master
loadubjson.m
.m
machine-learning-exercises-master/machine-learning-ex7/ex7/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
zzlyw/machine-learning-exercises-master
saveubjson.m
.m
machine-learning-exercises-master/machine-learning-ex7/ex7/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
zzlyw/machine-learning-exercises-master
submit.m
.m
machine-learning-exercises-master/machine-learning-ex5/ex5/submit.m
1,765
utf_8
b1804fe5854d9744dca981d250eda251
function submit() addpath('./lib'); conf.assignmentSlug = 'regularized-linear-regression-and-bias-variance'; conf.itemName = 'Regularized Linear Regression and Bias/Variance'; conf.partArrays = { ... { ... '1', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Cost Function', ... }, ... { ... '2', ... { 'linearRegCostFunction.m' }, ... 'Regularized Linear Regression Gradient', ... }, ... { ... '3', ... { 'learningCurve.m' }, ... 'Learning Curve', ... }, ... { ... '4', ... { 'polyFeatures.m' }, ... 'Polynomial Feature Mapping', ... }, ... { ... '5', ... { 'validationCurve.m' }, ... 'Validation Curve', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases X = [ones(10,1) sin(1:1.5:15)' cos(1:1.5:15)']; y = sin(1:3:30)'; Xval = [ones(10,1) sin(0:1.5:14)' cos(0:1.5:14)']; yval = sin(1:10)'; if partId == '1' [J] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', J); elseif partId == '2' [J, grad] = linearRegCostFunction(X, y, [0.1 0.2 0.3]', 0.5); out = sprintf('%0.5f ', grad); elseif partId == '3' [error_train, error_val] = ... learningCurve(X, y, Xval, yval, 1); out = sprintf('%0.5f ', [error_train(:); error_val(:)]); elseif partId == '4' [X_poly] = polyFeatures(X(2,:)', 8); out = sprintf('%0.5f ', X_poly); elseif partId == '5' [lambda_vec, error_train, error_val] = ... validationCurve(X, y, Xval, yval); out = sprintf('%0.5f ', ... [lambda_vec(:); error_train(:); error_val(:)]); end end
github
zzlyw/machine-learning-exercises-master
submitWithConfiguration.m
.m
machine-learning-exercises-master/machine-learning-ex5/ex5/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
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('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); 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(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); 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 % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
zzlyw/machine-learning-exercises-master
savejson.m
.m
machine-learning-exercises-master/machine-learning-ex5/ex5/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
zzlyw/machine-learning-exercises-master
loadjson.m
.m
machine-learning-exercises-master/machine-learning-ex5/ex5/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
zzlyw/machine-learning-exercises-master
loadubjson.m
.m
machine-learning-exercises-master/machine-learning-ex5/ex5/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
zzlyw/machine-learning-exercises-master
saveubjson.m
.m
machine-learning-exercises-master/machine-learning-ex5/ex5/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
zzlyw/machine-learning-exercises-master
submit.m
.m
machine-learning-exercises-master/machine-learning-ex3/ex3/submit.m
1,567
utf_8
1dba733a05282b2db9f2284548483b81
function submit() addpath('./lib'); conf.assignmentSlug = 'multi-class-classification-and-neural-networks'; conf.itemName = 'Multi-class Classification and Neural Networks'; conf.partArrays = { ... { ... '1', ... { 'lrCostFunction.m' }, ... 'Regularized Logistic Regression', ... }, ... { ... '2', ... { 'oneVsAll.m' }, ... 'One-vs-All Classifier Training', ... }, ... { ... '3', ... { 'predictOneVsAll.m' }, ... 'One-vs-All Classifier Prediction', ... }, ... { ... '4', ... { 'predict.m' }, ... 'Neural Network Prediction Function' ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxdata) % 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; Xm = [ -1 -1 ; -1 -2 ; -2 -1 ; -2 -2 ; ... 1 1 ; 1 2 ; 2 1 ; 2 2 ; ... -1 1 ; -1 2 ; -2 1 ; -2 2 ; ... 1 -1 ; 1 -2 ; -2 -1 ; -2 -2 ]; ym = [ 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 ]'; t1 = sin(reshape(1:2:24, 4, 3)); t2 = cos(reshape(1:2:40, 4, 5)); if partId == '1' [J, grad] = lrCostFunction([0.25 0.5 -0.5]', X, y, 0.1); out = sprintf('%0.5f ', J); out = [out sprintf('%0.5f ', grad)]; elseif partId == '2' out = sprintf('%0.5f ', oneVsAll(Xm, ym, 4, 0.1)); elseif partId == '3' out = sprintf('%0.5f ', predictOneVsAll(t1, Xm)); elseif partId == '4' out = sprintf('%0.5f ', predict(t1, t2, Xm)); end end
github
zzlyw/machine-learning-exercises-master
submitWithConfiguration.m
.m
machine-learning-exercises-master/machine-learning-ex3/ex3/lib/submitWithConfiguration.m
5,562
utf_8
4ac719ea6570ac228ea6c7a9c919e3f5
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('\n!! Submission failed: %s\n', e.message); fprintf('\n\nFunction: %s\nFileName: %s\nLineNumber: %d\n', ... e.stack(1,1).name, e.stack(1,1).file, e.stack(1,1).line); fprintf('\nPlease correct your code and resubmit.\n'); return end if isfield(response, 'errorMessage') fprintf('!! Submission failed: %s\n', response.errorMessage); elseif isfield(response, 'errorCode') fprintf('!! Submission failed: %s\n', response.message); 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(); responseBody = getResponse(submissionUrl, body); jsonResponse = validateResponse(responseBody); response = loadjson(jsonResponse); 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 % use urlread or curl to send submit results to the grader and get a response function response = getResponse(url, body) % try using urlread() and a secure connection params = {'jsonBody', body}; [response, success] = urlread(url, 'post', params); if (success == 0) % urlread didn't work, try curl & the peer certificate patch if ispc % testing note: use 'jsonBody =' for a test case json_command = sprintf('echo jsonBody=%s | curl -k -X POST -d @- %s', body, url); else % it's linux/OS X, so use the other form json_command = sprintf('echo ''jsonBody=%s'' | curl -k -X POST -d @- %s', body, url); end % get the response body for the peer certificate patch method [code, response] = system(json_command); % test the success code if (code ~= 0) fprintf('[error] submission with curl() was not successful\n'); end end end % validate the grader's response function response = validateResponse(resp) % test if the response is json or an HTML page isJson = length(resp) > 0 && resp(1) == '{'; isHtml = findstr(lower(resp), '<html'); if (isJson) response = resp; elseif (isHtml) % the response is html, so it's probably an error message printHTMLContents(resp); error('Grader response is an HTML message'); else error('Grader sent no response'); end end % parse a HTML response and print it's contents function printHTMLContents(response) strippedResponse = regexprep(response, '<[^>]+>', ' '); strippedResponse = regexprep(strippedResponse, '[\t ]+', ' '); fprintf(strippedResponse); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Service configuration % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function submissionUrl = submissionUrl() submissionUrl = 'https://www-origin.coursera.org/api/onDemandProgrammingImmediateFormSubmissions.v1'; end
github
zzlyw/machine-learning-exercises-master
savejson.m
.m
machine-learning-exercises-master/machine-learning-ex3/ex3/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
zzlyw/machine-learning-exercises-master
loadjson.m
.m
machine-learning-exercises-master/machine-learning-ex3/ex3/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
zzlyw/machine-learning-exercises-master
loadubjson.m
.m
machine-learning-exercises-master/machine-learning-ex3/ex3/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