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
wmacnair/TreeTop-master
plot_fig.m
.m
TreeTop-master/TreeTop/private/plot_fig.m
858
utf_8
c0d30c22fa37f091bceb6dc215bb3867
%% plot_fig: function plot_fig(fig, name_stem, file_ext, fig_size) plot_file = sprintf('%s.%s', name_stem, file_ext); % set up figure units = 'inches'; set_up_figure_size(fig, units, fig_size) % do plot switch file_ext case 'png' r = 300; % pixels per inch print(fig, '-dpng', sprintf('-r%d', r), plot_file); case 'eps' print(fig, '-depsc', plot_file); case 'pdf' print(fig, '-dpdf', plot_file); otherwise error('invalid plot extension') end close(fig) end %% set_up_figure_size: helper function to make figure ok for printing to pdf function [] = set_up_figure_size(fig, units, fig_size) set(fig, 'units', units); set(fig, 'paperunits', units); set(fig, 'paperposition', [0, 0, fig_size]); set(fig, 'papersize', fig_size); set(fig, 'position', [0, 0, fig_size]); set(fig, 'paperpositionmode', 'manual'); end
github
wmacnair/TreeTop-master
plot_contingency_table.m
.m
TreeTop-master/TreeTop/private/plot_contingency_table.m
2,989
utf_8
4476340d0f46aebd6b9dd05bb505a3a5
%% plot_contingency_table: function plot_contingency_table(branches, celltypes, row_order, col_order) % do crosstab of branches against gates [branch_xtab, ~, ~, labels] = crosstab(branches, celltypes); % calculate NMI between them [~, ~, branch_int] = unique(branches); [~, ~, cell_int] = unique(celltypes); this_nmi = nmi(branch_int, cell_int); % mess about with labels row_labels = labels(:, 1); row_labels = row_labels(~cellfun(@isempty, row_labels)); col_labels = labels(:, 2); col_labels = col_labels(~cellfun(@isempty, col_labels)); % normalize by celltype normed_xtab = bsxfun(@rdivide, branch_xtab, sum(branch_xtab, 1)); other_normed = bsxfun(@rdivide, branch_xtab, sum(branch_xtab, 2)); % % % put clusters in right order % % [~, row_order] = sort(row_labels); % % row_labels = row_labels(row_order); % % normed_xtab = normed_xtab(row_order, :); % % get right order for celltypes in right order % link = linkage(normed_xtab', 'complete'); % dist_mat = pdist(normed_xtab'); % col_order = optimalleaforder(link, dist_mat); % % get right order for clusters % link = linkage(other_normed, 'complete'); % dist_mat = pdist(other_normed); % row_order = optimalleaforder(link, dist_mat); % % put everything in order % row_labels = row_labels(row_order); % col_labels = col_labels(col_order); % normed_xtab = normed_xtab(row_order, col_order); if exist('row_order', 'var') && ~isempty(row_order) if ~isequal(sort(row_labels(:)), sort(row_order(:))) error('row_order does not match row labels') end row_idx = cellfun(@(this_label) find(strcmp(this_label, row_labels)), row_order); row_labels = row_labels(row_idx); normed_xtab = normed_xtab(row_idx, :); end if exist('col_order', 'var') && ~isempty(col_order) if ~isequal(sort(col_labels(:)), sort(col_order(:))) error('col_order does not match col labels') end col_idx = cellfun(@(this_label) find(strcmp(this_label, col_labels)), col_order); col_labels = col_labels(col_idx); normed_xtab = normed_xtab(:, col_idx); end % add text of NMI over top val_labels = arrayfun(@(x) sprintf('%.1f', x), normed_xtab, 'unif', false); [mesh_x, mesh_y] = meshgrid(1:size(normed_xtab, 2), 1:size(normed_xtab, 1)); non_zero_idx = normed_xtab(:) > 0; % plot heatmap of celltypes per cluster, normalized by celltype total (?) imagesc(normed_xtab) text(mesh_x(non_zero_idx), mesh_y(non_zero_idx), val_labels(non_zero_idx), 'FontSize', 8, 'HorizontalAlignment', 'center') % add labels ax = gca; set(gca,'TickLabelInterpreter','none') col_ticks = 1:size(normed_xtab, 2); xlim([min(col_ticks)-0.5, max(col_ticks)+0.5]) set(ax, 'XTick', col_ticks); set(ax, 'XTickLabel', col_labels); ax.XTickLabelRotation = 45; row_ticks = 1:size(normed_xtab, 1); set(ax, 'YTick', row_ticks); set(ax, 'YTickLabel', row_labels); % add title title({'Allocation of gates to branches', sprintf('(NMI = %.2f)', this_nmi)}) end
github
wmacnair/TreeTop-master
fca_readfcs_3_1.m
.m
TreeTop-master/TreeTop/private/fca_readfcs_3_1.m
19,308
utf_8
5806366bf7585fcde160efc7aeb30af3
function [fcsdat, fcshdr, fcsdatscaled, fcsdatcomp] = fca_readfcs(filename) % [fcsdat, fcshdr, fcsdatscaled, fcsdat_comp] = fca_readfcs(filename); % % % Read FCS 2.0 and FCS 3.0 type flow cytometry data file and put the list mode % parameters to the fcsdat array with the size of [NumOfPar TotalEvents]. % Some important header data are stored in the fcshdr structure: % TotalEvents, NumOfPar, starttime, stoptime and specific info for parameters % as name, range, bitdepth, logscale(yes-no) and number of decades. % % [fcsdat, fcshdr] = fca_readfcs; % Without filename input the user can select the desired file % using the standard open file dialog box. % % [fcsdat, fcshdr, fcsdatscaled] = fca_readfcs(filename); % Supplying the third output the fcsdatscaled array contains the scaled % parameters. It might be useful for logscaled parameters, but no effect % in the case of linear parameters. The log scaling is the following % operation for the "ith" parameter: % fcsdatscaled(:,i) = ... % 10.^(fcsdat(:,i)/fcshdr.par(i).range*fcshdr.par(i).decade;); % % %[fcsdat, fcshdr, fcsdatscaled, fcsdat_comp] = fca_readfcs(filename); % In that case the script will calculate the compensated fluorescence % intensities (fcsdat_comp) if spillover data exist in the header % % Ver May/24/2014 % 2006-2014 / University of Debrecen, Institute of Nuclear Medicine % Laszlo Balkay % [email protected] % % History % 14/08/2006 I made some changes in the code by the suggestion of % Brian Harms <[email protected]> and Ivan Cao-Berg <[email protected]> % (given at the user reviews area of Mathwork File exchage) The program should work % in the case of Becton EPics DLM FCS2.0, CyAn Summit FCS3.0 and FACSDiva type % list mode files. % % 29/01/2008 Updated to read the BD LSR II file format and including the comments of % Allan Moser (Cira Discovery Sciences, Inc.) % % 24/01/2009 Updated to read the Partec CyFlow format file. Thanks for % Gavin A Price (GAP) % % 20/09/2010 Updated to read the Accuri C6 format file. Thanks for % Rob Egbert, University of Washington % % 07/11/2011 Updated to read Luminex 100 data file. Thanks for % Ofir Goldberger, Stanford University % % 11/05/2013 The fluorescence compensation is implemeted into the code. % Thanks for Rick Stanton, J. Craig Venter Institute, La Jolla, San Diego % % 12/02/2013 % MOre accurate compensation correction and amplification gain scaling is added. % Thanks for Rachel Finck(RLF); Garry Nolan's lab at Stanford University % Appropriate byte offset for the data segment is included for large % file size (100Mbyte>). % Thanks for Andrea Pagnani(AP) /Politecnico Torino, Human Genetics Foundation % and RLF % % 16/05/2014 % The FCS 3.0 standard enables the mixture of word lengths in the data, this % upgrade modified the code according to. The linefeed (ASCII code 10) as % the mnemonic separator was also added. % Thanks for William Peria /Fred Hutchinson Cancer Research Center % if noarg was supplied if nargin == 0 [FileName, FilePath] = uigetfile('*.*','Select fcs2.0 file'); filename = [FilePath,FileName]; if FileName == 0; fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; return; end else filecheck = dir(filename); if size(filecheck,1) == 0 hm = msgbox([filename,': The file does not exist!'], ... 'FcAnalysis info','warn'); fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; return; end end % if filename arg. only contain PATH, set the default dir to this % before issuing the uigetfile command. This is an option for the "fca" % tool [FilePath, FileNameMain, fext] = fileparts(filename); FilePath = [FilePath filesep]; FileName = [FileNameMain, fext]; if isempty(FileNameMain) currend_dir = cd; cd(FilePath); [FileName, FilePath] = uigetfile('*.*','Select FCS file'); filename = [FilePath,FileName]; if FileName == 0; fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; return; end cd(currend_dir); end %fid = fopen(filename,'r','ieee-be'); fid = fopen(filename,'r','b'); fcsheader_1stline = fread(fid,64,'char'); fcsheader_type = char(fcsheader_1stline(1:6)'); % %reading the header % if strcmp(fcsheader_type,'FCS1.0') hm = msgbox('FCS 1.0 file type is not supported!','FcAnalysis info','warn'); fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; fclose(fid); return; elseif strcmp(fcsheader_type,'FCS2.0') || strcmp(fcsheader_type,'FCS3.0') || strcmp(fcsheader_type,'FCS3.1') % 3.1 hack; FCS2.0 or FCS3.0 or FCS3.1 types fcshdr.fcstype = fcsheader_type; FcsHeaderStartPos = str2num(char(fcsheader_1stline(11:18)')); FcsHeaderStopPos = str2num(char(fcsheader_1stline(19:26)')); FcsDataStartPos = str2num(char(fcsheader_1stline(27:34)')); status = fseek(fid,FcsHeaderStartPos,'bof'); fcsheader_main = fread(fid,FcsHeaderStopPos-FcsHeaderStartPos+1,'char');%read the main header warning off MATLAB:nonIntegerTruncatedInConversionToChar; fcshdr.filename = FileName; fcshdr.filepath = FilePath; % "The first character of the primary TEXT segment contains the % delimiter" (FCS standard) if fcsheader_main(1) == 12 mnemonic_separator = 'FF'; elseif fcsheader_main(1) == 9 % added by RLF August 2010 mnemonic_separator = 'TAB'; elseif fcsheader_main(1) == 10 mnemonic_separator = 'LF'; else mnemonic_separator = char(fcsheader_main(1)); end % % if the file size larger than ~100Mbyte the previously defined % FcsDataStartPos = 0. In that case the $BEGINDATA parameter stores the correct value % This option was suggested by AP and RLF % if ~FcsDataStartPos FcsDataStartPos = str2num(get_mnemonic_value('$BEGINDATA',fcsheader_main, mnemonic_separator)); end % if mnemonic_separator == '@';% WinMDI hm = msgbox([FileName,': The file can not be read (Unsupported FCS type: WinMDI histogram file)'],'FcAnalysis info','warn'); fcsdat = []; fcshdr = [];fcsdatscaled= []; fcsdat_comp= []; fclose(fid); return; end fcshdr.TotalEvents = str2num(get_mnemonic_value('$TOT',fcsheader_main, mnemonic_separator)); if fcshdr.TotalEvents == 0 fcsdat = 0; fcsdatscaled = 0; return end fcshdr.NumOfPar = str2num(get_mnemonic_value('$PAR',fcsheader_main, mnemonic_separator)); % if strcmp(mnemonic_separator,'LF') % fcshdr.NumOfPar = fcshdr.NumOfPar + 1; % end % fcshdr.Creator = get_mnemonic_value('CREATOR',fcsheader_main, mnemonic_separator); %%%%%%comp matrix reader added by RLF 12_15_10 comp = get_mnemonic_value('SPILL',fcsheader_main,mnemonic_separator); if ~isempty(comp) %%% compcell=regexp(comp,',','split'); nc=str2double(compcell{1}); fcshdr.CompLabels=compcell(2:nc+1); fcshdr.CompMat=reshape(str2double(compcell(nc+2:end)'),[nc nc])'; else fcshdr.CompLabels=[]; fcshdr.CompMat=[]; end plate = get_mnemonic_value('PLATE NAME',fcsheader_main,mnemonic_separator); if ~isempty(plate) fcshdr.plate=plate; end %%%%%%%%%%%% RLF for i=1:fcshdr.NumOfPar fcshdr.par(i).name = get_mnemonic_value(['$P',num2str(i),'N'],fcsheader_main, mnemonic_separator); fcshdr.par(i).name2 = get_mnemonic_value(['$P',num2str(i),'S'],fcsheader_main, mnemonic_separator); fcshdr.par(i).range = str2num(get_mnemonic_value(['$P',num2str(i),'R'],fcsheader_main, mnemonic_separator)); fcshdr.par(i).bit = str2num(get_mnemonic_value(['$P',num2str(i),'B'],fcsheader_main, mnemonic_separator)); %============== Changed way that amplification type is treated --- ARM ================== par_exponent_str= (get_mnemonic_value(['$P',num2str(i),'E'],fcsheader_main, mnemonic_separator)); if isempty(par_exponent_str) % There is no "$PiE" mnemonic in the Lysys format % in that case the PiDISPLAY mnem. shows the LOG or LIN definition islogpar = get_mnemonic_value(['P',num2str(i),'DISPLAY'],fcsheader_main, mnemonic_separator); if strcmp(islogpar,'LOG') par_exponent_str = '5,1'; else % islogpar = LIN case par_exponent_str = '0,0'; end end par_exponent= str2num(par_exponent_str); fcshdr.par(i).decade = par_exponent(1); if fcshdr.par(i).decade == 0 fcshdr.par(i).log = 0; fcshdr.par(i).logzero = 0; else fcshdr.par(i).log = 1; if (par_exponent(2) == 0) fcshdr.par(i).logzero = 1; else fcshdr.par(i).logzero = par_exponent(2); end end gain_str = get_mnemonic_value(['$P',num2str(i),'G'],fcsheader_main, mnemonic_separator); % added by RLF if ~isempty(gain_str) % added by RLF fcshdr.par(i).gain=str2double(gain_str); else fcshdr.par(i).gain=1; end %============================================================================================ end fcshdr.starttime = get_mnemonic_value('$BTIM',fcsheader_main, mnemonic_separator); fcshdr.stoptime = get_mnemonic_value('$ETIM',fcsheader_main, mnemonic_separator); fcshdr.cytometry = get_mnemonic_value('$CYT',fcsheader_main, mnemonic_separator); fcshdr.date = get_mnemonic_value('$DATE',fcsheader_main, mnemonic_separator); fcshdr.byteorder = get_mnemonic_value('$BYTEORD',fcsheader_main, mnemonic_separator); if strcmp(fcshdr.byteorder, '1,2,3,4') machineformat = 'ieee-le'; elseif strcmp(fcshdr.byteorder, '4,3,2,1') machineformat = 'ieee-be'; end fcshdr.datatype = get_mnemonic_value('$DATATYPE',fcsheader_main, mnemonic_separator); fcshdr.system = get_mnemonic_value('$SYS',fcsheader_main, mnemonic_separator); fcshdr.project = get_mnemonic_value('$PROJ',fcsheader_main, mnemonic_separator); fcshdr.experiment = get_mnemonic_value('$EXP',fcsheader_main, mnemonic_separator); fcshdr.cells = get_mnemonic_value('$Cells',fcsheader_main, mnemonic_separator); fcshdr.creator = get_mnemonic_value('CREATOR',fcsheader_main, mnemonic_separator); else hm = msgbox([FileName,': The file can not be read (Unsupported FCS type)'],'FcAnalysis info','warn'); fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; fclose(fid); return; end % %reading the events % status = fseek(fid,FcsDataStartPos,'bof'); if strcmp(fcsheader_type,'FCS2.0') if strcmp(mnemonic_separator,'\') || strcmp(mnemonic_separator,'FF')... %ordinary or FacsDIVA FCS2.0 || strcmp(mnemonic_separator,'/') || strcmp(mnemonic_separator,'TAB') % added by GAP 1/22/09 %added by RLF 09/02/10 if fcshdr.par(1).bit == 16 fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16',machineformat)'); fcsdat_orig = uint16(fcsdat);%// if strcmp(fcshdr.byteorder,'1,2')...% this is the Cytomics data || strcmp(fcshdr.byteorder, '1,2,3,4') %added by GAP 1/22/09 fcsdat = bitor(bitshift(fcsdat,-8),bitshift(fcsdat,8)); end new_xrange = 1024; for i=1:fcshdr.NumOfPar if fcshdr.par(i).range > 4096 fcsdat(:,i) = fcsdat(:,i)*new_xrange/fcshdr.par(i).range; fcshdr.par(i).range = new_xrange; end end elseif fcshdr.par(1).bit == 32 if fcshdr.datatype ~= 'F' fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint32')'); else % 'LYSYS' case fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'float32')'); end else bittype = ['ubit',num2str(fcshdr.par(1).bit)]; fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],bittype, 'ieee-le')'; end elseif strcmp(mnemonic_separator,'!');% Becton EPics DLM FCS2.0 fcsdat_ = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16', 'ieee-le')'; fcsdat = zeros(fcshdr.TotalEvents,fcshdr.NumOfPar); for i=1:fcshdr.NumOfPar bintmp = dec2bin(fcsdat_(:,i)); fcsdat(:,i) = bin2dec(bintmp(:,7:16)); % only the first 10bit is valid for the parameter end end fclose(fid); elseif strcmp(fcsheader_type,'FCS3.0') || strcmp(fcsheader_type,'FCS3.1') % 3.1 hack if strcmp(mnemonic_separator,'|') && strcmp(fcshdr.datatype,'I') % CyAn Summit FCS3.0 fcsdat_ = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16',machineformat)'); fcsdat = zeros(size(fcsdat_)); new_xrange = 1024; for i=1:fcshdr.NumOfPar fcsdat(:,i) = fcsdat_(:,i)*new_xrange/fcshdr.par(i).range; fcshdr.par(i).range = new_xrange; end elseif strcmp(mnemonic_separator,'/') if findstr(lower(fcshdr.cytometry),'accuri') % Accuri C6, this condition added by Rob Egbert, University of Washington 9/17/2010 fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'int32',machineformat)'); elseif findstr(lower(fcshdr.cytometry),'partec')%this block added by GAP 6/1/09 for Partec, copy/paste from above fcsdat = uint16(fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16',machineformat)'); %fcsdat = bitor(bitshift(fcsdat,-8),bitshift(fcsdat,8)); elseif findstr(lower(fcshdr.cytometry),'lx') % Luminex data fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'int32',machineformat)'; fcsdat = mod(fcsdat,1024); else % 3.1 hack warning('HAAAAAAAAAAAAAAAAAAAAAAAACK\nthis hack done for combination of mnemonic_separator == %s and datatype == D ', mnemonic_separator) if strcmp(fcshdr.datatype,'D') fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'double',machineformat)'; elseif strcmp(fcshdr.datatype,'F') fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'float32',machineformat)'; elseif strcmp(fcshdr.datatype,'I') fcsdat = fread(fid,[sum([fcshdr.par.bit]/16) fcshdr.TotalEvents],'uint16',machineformat)'; % sum: William Peria, 16/05/2014 end end else % ordinary FCS 3.0 if strcmp(fcshdr.datatype,'D') fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'double',machineformat)'; elseif strcmp(fcshdr.datatype,'F') fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'float32',machineformat)'; elseif strcmp(fcshdr.datatype,'I') fcsdat = fread(fid,[sum([fcshdr.par.bit]/16) fcshdr.TotalEvents],'uint16',machineformat)'; % sum: William Peria, 16/05/2014 end end fclose(fid); end %% this is for Ricardo Khouri converting Partec to FacsDIVA_FCS20 format %% 28/01/2013 save_FacsDIVA_FCS20 = 0; if strcmp(fcshdr.cytometry ,'partec PAS') && save_FacsDIVA_FCS20 fcsheader_main2 = fcsheader_main; sep_place = strfind(char(fcsheader_main'),'/'); fcsheader_main2(sep_place) = 12; fcsheader_1stline2 = fcsheader_1stline; fcsheader_1stline2(31:34) = double(num2str(FcsHeaderStopPos+1)); fcsheader_1stline2(43:50) = double(' 0'); fcsheader_1stline2(51:58) = double(' 0'); FileSize = length(fcsheader_main2(:))+ length(fcsheader_1stline2(1:FcsHeaderStartPos))+ 2*length(fcsdat_orig(:)); space_char(1:8-length(num2str(FileSize)))= ' '; fcsheader_1stline2(35:42) = double([space_char,num2str(FileSize)]); fid2 = fopen([FilePath, FileNameMain,'_', fext],'w','b'); fwrite(fid2,[fcsheader_1stline2(1:FcsHeaderStartPos)],'char'); fwrite(fid2,fcsheader_main2,'char'); fwrite(fid2,fcsdat_orig','uint16'); fclose(fid2); end %calculate the scaled events (for log scales) %RLF added gain division if nargout>2 fcsdatscaled = zeros(size(fcsdat)); for i = 1 : fcshdr.NumOfPar Xlogdecade = fcshdr.par(i).decade; XChannelMax = fcshdr.par(i).range; Xlogvalatzero = fcshdr.par(i).logzero; if fcshdr.par(i).gain~=1 fcsdatscaled(:,i) = double(fcsdat(:,i))./fcshdr.par(i).gain; elseif fcshdr.par(i).log fcsdatscaled(:,i) = Xlogvalatzero*10.^(double(fcsdat(:,i))/XChannelMax*Xlogdecade); else fcsdatscaled(:,i) = fcsdat(:,i); end end end if nargout>3 && ~isempty(fcshdr.CompLabels) %RLF. applied to fcsdatscaled rather than fcsdat. compcols=zeros(1,nc); colLabels={fcshdr.par.name}; for i=1:nc compcols(i)=find(strcmp(fcshdr.CompLabels{i},colLabels)); end fcsdatcomp = fcsdatscaled; fcsdatcomp(:,compcols) = fcsdatcomp(:,compcols)/fcshdr.CompMat; else fcsdatcomp=[]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mneval = get_mnemonic_value(mnemonic_name,fcsheader,mnemonic_separator) if strcmp(mnemonic_separator,'\') || strcmp(mnemonic_separator,'!') ... || strcmp(mnemonic_separator,'|') || strcmp(mnemonic_separator,'@')... || strcmp(mnemonic_separator, '/') mnemonic_startpos = findstr(char(fcsheader'),[mnemonic_name,mnemonic_separator]); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length; next_slashes = findstr(char(fcsheader(mnemonic_stoppos+1:end)'),mnemonic_separator); next_slash = next_slashes(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos+1:next_slash-1)'); elseif strcmp(mnemonic_separator,'FF') mnemonic_startpos = findstr(char(fcsheader'),mnemonic_name); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length ; next_formfeeds = find( fcsheader(mnemonic_stoppos+1:end) == 12); next_formfeed = next_formfeeds(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos + 1 : next_formfeed-1)'); elseif strcmp(mnemonic_separator,'TAB') %added by RLF August 2010 mnemonic_startpos = findstr(char(fcsheader'),mnemonic_name); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length ; next_formfeeds = find( fcsheader(mnemonic_stoppos+1:end) == 9); next_formfeed = next_formfeeds(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos + 1 : next_formfeed-1)'); elseif strcmp(mnemonic_separator, 'LF') % William Peria, 16/05/2014 mnemonic_startpos = findstr(char(fcsheader'),mnemonic_name); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length ; next_linefeeds = find( fcsheader(mnemonic_stoppos+1:end) == 10); next_linefeed = next_linefeeds(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos + 1 : next_linefeed-1)'); end
github
wmacnair/TreeTop-master
get_treetop_outputs.m
.m
TreeTop-master/TreeTop/private/get_treetop_outputs.m
3,876
utf_8
1586e5cc275b9c45526eb6eb5d33c6d4
%% get_treetop_outputs: open up saved variables from trees section function [treetop_struct] = get_treetop_outputs(input_struct) fprintf('getting treetop outputs\n'); % unpack output_dir = input_struct.output_dir; save_stem = input_struct.save_stem; % get all data (= node_idx_array, tree_array, tree_dist_array, celltype_vector) tree_variables_file = fullfile(output_dir, 'tree_variables.mat'); load(tree_variables_file, 'outlier_idx', 'downsample_idx', 'tree_cell', 'cell_assignments', 'tree_dist_cell', 'centroids_idx', 'node_idx_array', 'celltype_vector', 'density'); % get weight values samples_file = fullfile(output_dir, sprintf('%s_sample_counts.txt', save_stem)); samples_struct = importdata(samples_file); sample_counts = samples_struct.data; sample_names = samples_struct.colheaders; % get marker values used_file = fullfile(output_dir, sprintf('%s_mean_used_markers.txt', save_stem)); used_struct = importdata(used_file); mean_used = used_struct.data; extra_file = fullfile(output_dir, sprintf('%s_mean_extra_markers.txt', save_stem)); if exist(extra_file, 'file') extra_struct = importdata(extra_file); mean_extra = extra_struct.data; else mean_extra = []; end % get used marker values used_file = fullfile(output_dir, sprintf('%s_all_used_markers.mat', save_stem)); load(used_file, 'used_data'); % used_values = used_data(centroids_idx, :); % get extra marker values, if they exist extra_file = fullfile(output_dir, sprintf('%s_all_extra_markers.mat', save_stem)); if exist(extra_file, 'file') load(extra_file, 'extra_data'); % extra_data = extra_data(centroids_idx, :); else extra_data = []; end % convert celltype_vector to nominal celltype_vector = categorical(celltype_vector); % assemble into struct treetop_struct = struct( ... 'tree_cell', {tree_cell}, ... 'tree_dist_cell', {tree_dist_cell}, ... 'used_values', {mean_used}, ... 'extra_values', {mean_extra}, ... 'sample_counts', {sample_counts}, ... 'sample_names', {sample_names}, ... 'centroids_idx', {centroids_idx}, ... 'outlier_idx', {outlier_idx}, ... 'downsample_idx', {downsample_idx}, ... 'cell_assignments', {cell_assignments}, ... 'density', {density}, ... 'node_idx_array', {node_idx_array}, ... 'used_data', {used_data}, ... 'extra_data', {extra_data}, ... 'celltype_vector', {celltype_vector} ... ); % if done, get scores and branches scores_file = fullfile(output_dir, sprintf('%s branching scores.txt', save_stem)); if exist(scores_file, 'file') scores_struct = importdata(scores_file); branch_scores = scores_struct.data; % get branches branches_file = fullfile(output_dir, sprintf('%s best branches.txt', save_stem)); branches_struct = importdata(branches_file); best_branches = branches_struct.data; % add to treetop_struct treetop_struct.branch_scores = branch_scores; treetop_struct.best_branches = best_branches; end % if done, get significance calculations for each marker output_file = fullfile(input_struct.output_dir, sprintf('%s marker significance.mat', input_struct.save_stem)); if exist(output_file, 'file') load(output_file, 'mean_tree_dist', 'anova_results') treetop_struct.mean_tree_dist = mean_tree_dist; treetop_struct.anova_used = anova_results.anova_used; treetop_struct.anova_extra = anova_results.anova_extra; end % check whether cell_assignments_top exists file_details = who('-file', tree_variables_file); if ismember('cell_assignments_top', file_details) load(tree_variables_file, 'cell_assignments_top') treetop_struct.cell_assignments_top = cell_assignments_top; end if ismember('branch_parent_point', file_details) load(tree_variables_file, 'branch_parent_point') treetop_struct.branch_parent_point = branch_parent_point; end end
github
wmacnair/TreeTop-master
fca_readfcs.m
.m
TreeTop-master/TreeTop/private/fca_readfcs.m
17,790
utf_8
e8db0d0a0d4cd9f97addebbf00a99de9
function [fcsdat, fcshdr, fcsdatscaled, fcsdatcomp] = fca_readfcs(filename) % [fcsdat, fcshdr, fcsdatscaled, fcsdat_comp] = fca_readfcs(filename); % % % Read FCS 2.0 and FCS 3.0 type flow cytometry data file and put the list mode % parameters to the fcsdat array with the size of [NumOfPar TotalEvents]. % Some important header data are stored in the fcshdr structure: % TotalEvents, NumOfPar, starttime, stoptime and specific info for parameters % as name, range, bitdepth, logscale(yes-no) and number of decades. % % [fcsdat, fcshdr] = fca_readfcs; % Without filename input the user can select the desired file % using the standard open file dialog box. % % [fcsdat, fcshdr, fcsdatscaled] = fca_readfcs(filename); % Supplying the third output the fcsdatscaled array contains the scaled % parameters. It might be useful for logscaled parameters, but no effect % in the case of linear parameters. The log scaling is the following % operation for the "ith" parameter: % fcsdatscaled(:,i) = ... % 10.^(fcsdat(:,i)/fcshdr.par(i).range*fcshdr.par(i).decade;); % % %[fcsdat, fcshdr, fcsdatscaled, fcsdat_comp] = fca_readfcs(filename); % In that case the script will calculate the compensated fluorescence % intensities (fcsdat_comp) if spillover data exist in the header % % Ver Dec/03/2013 % 2006-2013 / University of Debrecen, Institute of Nuclear Medicine % Laszlo Balkay % [email protected] % % History % 14/08/2006 I made some changes in the code by the suggestion of % Brian Harms <[email protected]> and Ivan Cao-Berg <[email protected]> % (given at the user reviews area of Mathwork File exchage) The program should work % in the case of Becton EPics DLM FCS2.0, CyAn Summit FCS3.0 and FACSDiva type % list mode files. % % 29/01/2008 Updated to read the BD LSR II file format and including the comments of % Allan Moser (Cira Discovery Sciences, Inc.) % % 24/01/2009 Updated to read the Partec CyFlow format file. Thanks for % Gavin A Price (GAP) % % 20/09/2010 Updated to read the Accuri C6 format file. Thanks for % Rob Egbert, University of Washington % % 07/11/2011 Updated to read Luminex 100 data file. Thanks for % Ofir Goldberger, Stanford University % % 11/05/2013 The fluorescence compensation is implemeted into the code. % Thanks for Rick Stanton, J. Craig Venter Institute, La Jolla, San Diego % % 12/02/2013 % MOre accurate compensation correction and amplification gain scaling is added. % Thanks for Rachel Finck(RLF); Garry Nolan's lab at Stanford University % Appropriate byte offset for the data segment is included for large % file size (100Mbyte>). % Thanks for Andrea Pagnani(AP) /Politecnico Torino, Human Genetics Foundation % and RLF % % if noarg was supplied if nargin == 0 [FileName, FilePath] = uigetfile('*.*','Select fcs2.0 file'); filename = [FilePath,FileName]; if FileName == 0; fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; return; end else filecheck = dir(filename); if size(filecheck,1) == 0 hm = msgbox([filename,': The file does not exist!'], ... 'FcAnalysis info','warn'); fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; return; end end % if filename arg. only contain PATH, set the default dir to this % before issuing the uigetfile command. This is an option for the "fca" % tool [FilePath, FileNameMain, fext] = fileparts(filename); FilePath = [FilePath filesep]; FileName = [FileNameMain, fext]; if isempty(FileNameMain) currend_dir = cd; cd(FilePath); [FileName, FilePath] = uigetfile('*.*','Select FCS file'); filename = [FilePath,FileName]; if FileName == 0; fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; return; end cd(currend_dir); end %fid = fopen(filename,'r','ieee-be'); fid = fopen(filename,'r','b'); fcsheader_1stline = fread(fid,64,'char'); fcsheader_type = char(fcsheader_1stline(1:6)'); % %reading the header % if strcmp(fcsheader_type,'FCS1.0') hm = msgbox('FCS 1.0 file type is not supported!','FcAnalysis info','warn'); fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; fclose(fid); return; elseif strcmp(fcsheader_type,'FCS2.0') || strcmp(fcsheader_type,'FCS3.0') % FCS2.0 or FCS3.0 types fcshdr.fcstype = fcsheader_type; FcsHeaderStartPos = str2num(char(fcsheader_1stline(11:18)')); FcsHeaderStopPos = str2num(char(fcsheader_1stline(19:26)')); FcsDataStartPos = str2num(char(fcsheader_1stline(27:34)')); status = fseek(fid,FcsHeaderStartPos,'bof'); fcsheader_main = fread(fid,FcsHeaderStopPos-FcsHeaderStartPos+1,'char');%read the main header warning off MATLAB:nonIntegerTruncatedInConversionToChar; fcshdr.filename = FileName; fcshdr.filepath = FilePath; % "The first character of the primary TEXT segment contains the % delimiter" (FCS standard) if fcsheader_main(1) == 12 mnemonic_separator = 'FF'; elseif fcsheader_main(1) == 9 % added by RLF August 2010 mnemonic_separator = 'TAB'; else mnemonic_separator = char(fcsheader_main(1)); end % % if the file size larger than ~100Mbyte the previously defined % FcsDataStartPos = 0. In that case the $BEGINDATA parameter stores the correct value % This option was suggested by AP and RLF % if ~FcsDataStartPos FcsDataStartPos = str2num(get_mnemonic_value('$BEGINDATA',fcsheader_main, mnemonic_separator)); end % if mnemonic_separator == '@';% WinMDI hm = msgbox([FileName,': The file can not be read (Unsupported FCS type: WinMDI histogram file)'],'FcAnalysis info','warn'); fcsdat = []; fcshdr = [];fcsdatscaled= []; fcsdat_comp= []; fclose(fid); return; end fcshdr.TotalEvents = str2num(get_mnemonic_value('$TOT',fcsheader_main, mnemonic_separator)); % fcshdr.TotalEvents = min(str2num(get_mnemonic_value('$TOT',fcsheader_main, mnemonic_separator)),fcs_cell_limit); if fcshdr.TotalEvents == 0 fcsdat = 0; fcsdatscaled = 0; return end fcshdr.NumOfPar = str2num(get_mnemonic_value('$PAR',fcsheader_main, mnemonic_separator)); fcshdr.Creator = get_mnemonic_value('CREATOR',fcsheader_main, mnemonic_separator); %%%%%%comp matrix reader added by RLF 12_15_10 comp = get_mnemonic_value('SPILL',fcsheader_main,mnemonic_separator); if ~isempty(comp) %%% compcell=regexp(comp,',','split'); nc=str2double(compcell{1}); fcshdr.CompLabels=compcell(2:nc+1); fcshdr.CompMat=reshape(str2double(compcell(nc+2:end)'),[nc nc])'; else fcshdr.CompLabels=[]; fcshdr.CompMat=[]; end plate = get_mnemonic_value('PLATE NAME',fcsheader_main,mnemonic_separator); if ~isempty(plate) fcshdr.plate=plate; end %%%%%%%%%%%% RLF for i=1:fcshdr.NumOfPar fcshdr.par(i).name = get_mnemonic_value(['$P',num2str(i),'N'],fcsheader_main, mnemonic_separator); fcshdr.par(i).name2 = get_mnemonic_value(['$P',num2str(i),'S'],fcsheader_main, mnemonic_separator); fcshdr.par(i).range = str2num(get_mnemonic_value(['$P',num2str(i),'R'],fcsheader_main, mnemonic_separator)); fcshdr.par(i).bit = str2num(get_mnemonic_value(['$P',num2str(i),'B'],fcsheader_main, mnemonic_separator)); %============== Changed way that amplification type is treated --- ARM ================== par_exponent_str= (get_mnemonic_value(['$P',num2str(i),'E'],fcsheader_main, mnemonic_separator)); if isempty(par_exponent_str) % There is no "$PiE" mnemonic in the Lysys format % in that case the PiDISPLAY mnem. shows the LOG or LIN definition islogpar = get_mnemonic_value(['P',num2str(i),'DISPLAY'],fcsheader_main, mnemonic_separator); if strcmp(islogpar,'LOG') par_exponent_str = '5,1'; else % islogpar = LIN case par_exponent_str = '0,0'; end end par_exponent= str2num(par_exponent_str); fcshdr.par(i).decade = par_exponent(1); if fcshdr.par(i).decade == 0 fcshdr.par(i).log = 0; fcshdr.par(i).logzero = 0; else fcshdr.par(i).log = 1; if (par_exponent(2) == 0) fcshdr.par(i).logzero = 1; else fcshdr.par(i).logzero = par_exponent(2); end end gain_str = get_mnemonic_value(['$P',num2str(i),'G'],fcsheader_main, mnemonic_separator); % added by RLF if ~isempty(gain_str) % added by RLF fcshdr.par(i).gain=str2double(gain_str); else fcshdr.par(i).gain=1; end %============================================================================================ end fcshdr.starttime = get_mnemonic_value('$BTIM',fcsheader_main, mnemonic_separator); fcshdr.stoptime = get_mnemonic_value('$ETIM',fcsheader_main, mnemonic_separator); fcshdr.cytometry = get_mnemonic_value('$CYT',fcsheader_main, mnemonic_separator); fcshdr.date = get_mnemonic_value('$DATE',fcsheader_main, mnemonic_separator); fcshdr.byteorder = get_mnemonic_value('$BYTEORD',fcsheader_main, mnemonic_separator); if strcmp(fcshdr.byteorder, '1,2,3,4') machineformat = 'ieee-le'; elseif strcmp(fcshdr.byteorder, '4,3,2,1') machineformat = 'ieee-be'; end fcshdr.datatype = get_mnemonic_value('$DATATYPE',fcsheader_main, mnemonic_separator); fcshdr.system = get_mnemonic_value('$SYS',fcsheader_main, mnemonic_separator); fcshdr.project = get_mnemonic_value('$PROJ',fcsheader_main, mnemonic_separator); fcshdr.experiment = get_mnemonic_value('$EXP',fcsheader_main, mnemonic_separator); fcshdr.cells = get_mnemonic_value('$Cells',fcsheader_main, mnemonic_separator); fcshdr.creator = get_mnemonic_value('CREATOR',fcsheader_main, mnemonic_separator); else hm = msgbox([FileName,': The file can not be read (Unsupported FCS type)'],'FcAnalysis info','warn'); fcsdat = []; fcshdr = []; fcsdatscaled= []; fcsdat_comp= []; fclose(fid); return; end % %reading the events % status = fseek(fid,FcsDataStartPos,'bof'); if strcmp(fcsheader_type,'FCS2.0') if strcmp(mnemonic_separator,'\') || strcmp(mnemonic_separator,'FF')... %ordinary or FacsDIVA FCS2.0 || strcmp(mnemonic_separator,'/') || strcmp(mnemonic_separator,'TAB') % added by GAP 1/22/09 %added by RLF 09/02/10 if fcshdr.par(1).bit == 16 fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16',machineformat)'); fcsdat_orig = uint16(fcsdat);%// if strcmp(fcshdr.byteorder,'1,2')...% this is the Cytomics data || strcmp(fcshdr.byteorder, '1,2,3,4') %added by GAP 1/22/09 fcsdat = bitor(bitshift(fcsdat,-8),bitshift(fcsdat,8)); end new_xrange = 1024; for i=1:fcshdr.NumOfPar if fcshdr.par(i).range > 4096 fcsdat(:,i) = fcsdat(:,i)*new_xrange/fcshdr.par(i).range; fcshdr.par(i).range = new_xrange; end end elseif fcshdr.par(1).bit == 32 if fcshdr.datatype ~= 'F' fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint32')'); else % 'LYSYS' case fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'float32')'); end else bittype = ['ubit',num2str(fcshdr.par(1).bit)]; fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],bittype, 'ieee-le')'; end elseif strcmp(mnemonic_separator,'!');% Becton EPics DLM FCS2.0 fcsdat_ = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16', 'ieee-le')'; fcsdat = zeros(fcshdr.TotalEvents,fcshdr.NumOfPar); for i=1:fcshdr.NumOfPar bintmp = dec2bin(fcsdat_(:,i)); fcsdat(:,i) = bin2dec(bintmp(:,7:16)); % only the first 10bit is valid for the parameter end end fclose(fid); elseif strcmp(fcsheader_type,'FCS3.0') if strcmp(mnemonic_separator,'|') && strcmp(fcshdr.datatype,'I') % CyAn Summit FCS3.0 fcsdat_ = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16',machineformat)'); fcsdat = zeros(size(fcsdat_)); new_xrange = 1024; for i=1:fcshdr.NumOfPar fcsdat(:,i) = fcsdat_(:,i)*new_xrange/fcshdr.par(i).range; fcshdr.par(i).range = new_xrange; end elseif strcmp(mnemonic_separator,'/') && ... ( ~isempty(findstr(lower(fcshdr.cytometry),'accuri')) || ~isempty(findstr(lower(fcshdr.cytometry),'partec')) || ~isempty(findstr(lower(fcshdr.cytometry),'lx')) ) if findstr(lower(fcshdr.cytometry),'accuri') % Accuri C6, this condition added by Rob Egbert, University of Washington 9/17/2010 fcsdat = (fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'int32',machineformat)'); elseif findstr(lower(fcshdr.cytometry),'partec')%this block added by GAP 6/1/09 for Partec, copy/paste from above fcsdat = uint16(fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'uint16',machineformat)'); %fcsdat = bitor(bitshift(fcsdat,-8),bitshift(fcsdat,8)); elseif findstr(lower(fcshdr.cytometry),'lx') % Luminex data fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'int32',machineformat)'; fcsdat = mod(fcsdat,1024); end else % ordinary FCS 3.0 if strcmp(fcshdr.datatype,'D') fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'double',machineformat)'; elseif strcmp(fcshdr.datatype,'F') fcsdat = fread(fid,[fcshdr.NumOfPar fcshdr.TotalEvents],'float32',machineformat)'; end end fclose(fid); end %% this is for Ricardo Khouri converting Partec to FacsDIVA_FCS20 format %% 28/01/2013 save_FacsDIVA_FCS20 = 0; if strcmp(fcshdr.cytometry ,'partec PAS') && save_FacsDIVA_FCS20 fcsheader_main2 = fcsheader_main; sep_place = strfind(char(fcsheader_main'),'/'); fcsheader_main2(sep_place) = 12; fcsheader_1stline2 = fcsheader_1stline; fcsheader_1stline2(31:34) = double(num2str(FcsHeaderStopPos+1)); fcsheader_1stline2(43:50) = double(' 0'); fcsheader_1stline2(51:58) = double(' 0'); FileSize = length(fcsheader_main2(:))+ length(fcsheader_1stline2(1:FcsHeaderStartPos))+ 2*length(fcsdat_orig(:)); space_char(1:8-length(num2str(FileSize)))= ' '; fcsheader_1stline2(35:42) = double([space_char,num2str(FileSize)]); fid2 = fopen([FilePath, FileNameMain,'_', fext],'w','b'); fwrite(fid2,[fcsheader_1stline2(1:FcsHeaderStartPos)],'char'); fwrite(fid2,fcsheader_main2,'char'); fwrite(fid2,fcsdat_orig','uint16'); fclose(fid2); end %calculate the scaled events (for log scales) %RLF added gain division if nargout>2 fcsdatscaled = zeros(size(fcsdat)); for i = 1 : fcshdr.NumOfPar Xlogdecade = fcshdr.par(i).decade; XChannelMax = fcshdr.par(i).range; Xlogvalatzero = fcshdr.par(i).logzero; if fcshdr.par(i).gain~=1 fcsdatscaled(:,i) = double(fcsdat(:,i))./fcshdr.par(i).gain; elseif fcshdr.par(i).log fcsdatscaled(:,i) = Xlogvalatzero*10.^(double(fcsdat(:,i))/XChannelMax*Xlogdecade); else fcsdatscaled(:,i) = fcsdat(:,i); end end end if nargout>3 && ~isempty(fcshdr.CompLabels) %RLF. applied to fcsdatscaled rather than fcsdat. compcols=zeros(1,nc); colLabels={fcshdr.par.name}; for i=1:nc compcols(i)=find(strcmp(fcshdr.CompLabels{i},colLabels)); end fcsdatcomp = fcsdatscaled; fcsdatcomp(:,compcols) = fcsdatcomp(:,compcols)/fcshdr.CompMat; else fcsdatcomp=[]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mneval = get_mnemonic_value(mnemonic_name,fcsheader,mnemonic_separator) if strcmp(mnemonic_separator,'\') || strcmp(mnemonic_separator,'!') ... || strcmp(mnemonic_separator,'|') || strcmp(mnemonic_separator,'@')... || strcmp(mnemonic_separator, '/') % added by GAP 1/22/08 mnemonic_startpos = findstr(char(fcsheader'),[mnemonic_name,mnemonic_separator]); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length; next_slashes = findstr(char(fcsheader(mnemonic_stoppos+1:end)'),mnemonic_separator); next_slash = next_slashes(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos+1:next_slash-1)'); elseif strcmp(mnemonic_separator,'FF') mnemonic_startpos = findstr(char(fcsheader'),mnemonic_name); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length ; next_formfeeds = find( fcsheader(mnemonic_stoppos+1:end) == 12); next_formfeed = next_formfeeds(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos + 1 : next_formfeed-1)'); elseif strcmp(mnemonic_separator,'TAB') %added by RLF August 2010 mnemonic_startpos = findstr(char(fcsheader'),mnemonic_name); if isempty(mnemonic_startpos) mneval = []; return; end mnemonic_length = length(mnemonic_name); mnemonic_stoppos = mnemonic_startpos + mnemonic_length ; next_formfeeds = find( fcsheader(mnemonic_stoppos+1:end) == 9); next_formfeed = next_formfeeds(1) + mnemonic_stoppos; mneval = char(fcsheader(mnemonic_stoppos + 1 : next_formfeed-1)'); end
github
wmacnair/TreeTop-master
all_distance_fn_par.m
.m
TreeTop-master/TreeTop/private/all_distance_fn_par.m
2,177
utf_8
0111e9215c526a0edbdd98b7ef9feb27
%% all_distance_fn_par: flexible and memory-safe distance calculation function % expects X, Y to be formatted as n observations by d features for both function dist = all_distance_fn_par(X, Y, metric) switch metric case 'L1' dist = comp_dist_L1(X, Y); case 'L2' dist = comp_dist_euclidean(X, Y); case 'angle' dist = comp_dist_angle(X, Y); case 'corr' dist = comp_dist_corr(X, Y); otherwise error('invalid metric selected'); end end %% comp_dist_euclidean: function dist = comp_dist_euclidean(X, Y) % X has size m*d, Y n*d m = size(X, 1); n = size(Y, 1); dist = zeros(m,n); parfor ii = 1:m dist(ii,:) = sqrt(sum((repmat(X(ii,:),n,1) - Y).^2,2)); end end %% comp_dist_L1: function dist = comp_dist_L1(X, Y) % set up m = size(X, 1); n = size(Y, 1); dist = zeros(m, n); parfor ii = 1:m dist(ii,:) = sum(abs(repmat(X(ii,:), n, 1) - Y),2); end end %% comp_dist_corr: function dist = comp_dist_corr(X, Y) corr = calc_corr(X,Y); dist = 1-corr; end %% comp_dist_angle: function dist = comp_dist_angle(X, Y) % L2-normalization X = bsxfun(@times, X, 1./sqrt(sum(X.^2, 2))); Y = bsxfun(@times, Y, 1./sqrt(sum(Y.^2, 2))); % dot_prod = X*Y'; % dist = acos(dot_prod)/pi; % set up m = size(X, 1); n = size(Y, 1); dist = zeros(m, n); parfor ii = 1:m dot_prod = X(ii, :) * Y'; dist(ii, :) = real(acos(dot_prod)/pi); end end %% comp_dist_abs_corr: function dist = comp_dist_abs_corr(X, Y) corr = calc_corr(X,Y); dist = 1-abs(corr); end %% calc_corr: function [corr] = calc_corr(X, Y) % set up m = size(X, 1); n = size(Y, 1); corr = zeros(m, n); % zero-mean X = bsxfun(@minus, X, mean(X, 1)); Y = bsxfun(@minus, Y, mean(Y, 1)); % L2-normalization X = bsxfun(@times, X, 1./sqrt(sum(X.^2, 1))); Y = bsxfun(@times, Y, 1./sqrt(sum(Y.^2, 1))); % calculation correlation parfor ii = 1:m corr(ii,:) = X(ii,:) * Y'; end end %% per_gene_normalization: my guess at what this function should be function [X_out] = per_gene_normalization(X_in) X_norm = arrayfun(@(idx) norm(X_in(idx,:)), (1:size(X_in,1))'); X_out = bsxfun(@rdivide, X_in, X_norm); end
github
wmacnair/TreeTop-master
better_gscatter.m
.m
TreeTop-master/TreeTop/private/better_gscatter.m
1,701
utf_8
7b9b02b3e7528d59cc93bd3ce63b64c9
%% better_gscatter: gscatter looks rubbish. this is a bit better % consider adding ishold stuff function [h_legend] = better_gscatter(x, y, g, options) % sort out holding hold_status = ishold; if ~hold_status hold on end % get palette ctype = 'qual'; palette = 'Set1'; point_size = 10; legend_flag = false; location = 'EastOutside'; if nargin > 3 if isfield(options, 'palette') palette = options.palette; end if isfield(options, 'size') point_size = options.size; end if isfield(options, 'legend') legend_flag = options.legend; end if isfield(options, 'leg_pos') location = options.leg_pos; end end % get names [g_vals, ~, g_idx] = unique(g); if ~iscell(g_vals) g_vals = arrayfun(@num2str, g_vals, 'unif', false); end % get g n_cols = length(g_vals); h = zeros(n_cols, 1); if n_cols > 11 max_cols = 11; pal_mat_short = cbrewer('div', 'RdYlBu', max_cols); x_vals = (0:max_cols - 1) / (max_cols - 1); x_queries = (0:n_cols - 1) / (n_cols - 1); pal_mat = arrayfun(@(jj) interp1(x_vals, pal_mat_short(:,jj), x_queries)', 1:size(pal_mat_short,2), 'uniformoutput', false); pal_mat = [pal_mat{:}]; elseif n_cols > 9 & n_cols <= 11 pal_mat = cbrewer('div', 'RdYlBu', n_cols); elseif n_cols < 3 pal_mat = cbrewer(ctype, palette, 3); else pal_mat = cbrewer(ctype, palette, n_cols); end for ii = 1:n_cols this_idx = g_idx == ii; h(ii) = plot(x(this_idx), y(this_idx), '.', 'color', pal_mat(ii, :), 'markersize', point_size*2); end if legend_flag h_legend = legend(h, g_vals{:}, 'Location', location); else h_legend = []; end if ~hold_status hold off end end
github
wmacnair/TreeTop-master
get_all_files.m
.m
TreeTop-master/TreeTop/private/get_all_files.m
5,693
utf_8
4289b6b50fc67a156bf66aa6288d9d22
%% get_all_files: loads all files function all_struct = get_all_files(input_struct) % either get from mat file if isfield(input_struct, 'mat_file') all_struct = get_from_mat_file(input_struct); return end % or from fcs % unpack filenames = input_struct.filenames; file_annot = input_struct.file_annot; used_markers = input_struct.used_markers; extra_markers = input_struct.extra_markers; % define storage variables n_files = length(input_struct.filenames); used_cell = cell(n_files, 1); extra_cell = cell(n_files, 1); celltype_cell = cell(n_files, 1); % celltype file for index celltype_file = fullfile(input_struct.data_dir, filenames{1}); [~, celltype_hdr] = fca_readfcs_3_1(celltype_file); marker_names = {celltype_hdr.par.name2}'; empty_idx = cellfun(@isempty, marker_names); non_empty_markers = marker_names(~empty_idx); % if name2 didn't work, then try name if numel(intersect(used_markers, non_empty_markers)) ~= numel(used_markers) marker_names = {celltype_hdr.par.name}'; empty_idx = cellfun(@isempty, marker_names); non_empty_markers = marker_names(~empty_idx); end % check we can find all requested markers in the first file if numel(intersect(used_markers, non_empty_markers)) ~= numel(used_markers) error('file marker names don''t match those requested in input_struct') end % match used and extra markers to fcs files, check no duplicate marker names used_idx = cellfun(@(test_str) find(strcmp(test_str, marker_names)), used_markers, 'unif', false); if ~all(cellfun(@length, used_idx) == 1) error('some names in used_markers match fcs file more than once') end extra_idx = cellfun(@(test_str) find(strcmp(test_str, marker_names)), extra_markers, 'unif', false); if ~all(cellfun(@length, extra_idx) == 1) error('some names in extra_markers match fcs file more than once') end % check we can find all the markers we requested used_idx = cell2mat(used_idx); extra_idx = cell2mat(extra_idx); if numel(used_idx) ~= numel(used_markers) | numel(extra_idx) ~= numel(extra_markers) error('markers didn''t match those in file...') end % loop through all files fprintf('opening %d files:\n', n_files) for ii = 1:n_files fprintf('.') this_file = fullfile(input_struct.data_dir, filenames{ii}); [fcsdat, fcshdr] = fca_readfcs_3_1(this_file); % restrict to markers of interest used_data = fcsdat(:, used_idx); extra_data = fcsdat(:, extra_idx); % do arcsinh used_data = flow_arcsinh(used_data, input_struct.used_cofactor); extra_data = flow_arcsinh(extra_data, input_struct.extra_cofactor); n_cells = size(used_data, 1); % store used_cell{ii} = used_data; extra_cell{ii} = extra_data; celltype_cell{ii} = repmat(file_annot(ii), n_cells, 1); end fprintf('\n') % put all together fprintf('combining into one matrix\n') used_data = cell2mat(used_cell); extra_data = cell2mat(extra_cell); all_celltype = vertcat(celltype_cell{:}); % assemble into output struct all_struct = struct( ... 'used_data', {used_data}, ... 'extra_data', {extra_data}, ... 'all_labels', {all_celltype}, ... 'used_markers', {used_markers}, ... 'extra_markers', {extra_markers} ... ); end %% get_from_mat_file: function all_struct = get_from_mat_file(input_struct) % unpack used_markers = input_struct.used_markers; extra_markers = input_struct.extra_markers; % load file load(fullfile(input_struct.data_dir, input_struct.mat_file), 'all_struct') % double check a couple of things fields_list = fieldnames(all_struct); input_required = {'all_data', 'all_markers', 'all_labels'}; missing_fields = setdiff(input_required, fields_list); if ~isempty(missing_fields) error(sprintf('the following fields are missing from the variable all_struct in file %s:\n%s', mat_file, strjoin(missing_fields, ', '))) end % then subdivide appropriately all_markers = all_struct.all_markers; used_idx = ismember(all_markers, input_struct.used_markers); n_missing = length(used_markers) - sum(used_idx); if n_missing > 0 error('%d markers not found in data', n_missing) end all_struct = all_struct; all_struct.used_data = all_struct.all_data(:, used_idx); all_struct.used_markers = input_struct.used_markers; all_struct.all_labels = all_struct.all_labels; if isempty(extra_markers) all_struct.extra_data = []; all_struct.extra_markers = {}; else extra_idx = ismember(all_markers, input_struct.extra_markers); if sum(extra_idx) < length(extra_markers) error('missing extra marker') end if sum(extra_idx) > length(extra_markers) error('extra extra marker') end all_struct.extra_data = all_struct.all_data(:, extra_idx); all_struct.extra_markers = input_struct.extra_markers; n_missing = length(used_markers) - sum(used_idx); if n_missing > 0 error('%d markers not found in data', n_missing) end end end %% flow_arcsinh: % cofactor can be one signal number, for all channels % can be a vector, one element for one channel % if cofactor == 0, then it means linear, no transform. function [data] = flow_arcsinh(data, cofactor) if length(cofactor)~=1 && length(cofactor) ~= size(data, 2) error('wrong input of cofactors; data not transformed') end if length(cofactor)==1 if cofactor==0 return else data = log( data(:,:)/cofactor + sqrt((data(:,:)/cofactor).^2+1) ); return end end if length(cofactor) == size(data,1) for i=1:size(data,1) if cofactor(i)==0 continue; else data(i,:) = log( data(i,:)/cofactor(i) + sqrt((data(i,:)/cofactor(i)).^2+1) ); end end end end
github
wmacnair/TreeTop-master
all_distance_fn.m
.m
TreeTop-master/TreeTop/private/all_distance_fn.m
1,928
utf_8
48c71406add1e518651b4f91e3ab523a
%% all_distance_fn: flexible and memory-safe distance calculation function % expects X, Y to be formatted as n observations by d features for both function dist = all_distance_fn(X, Y, metric) switch metric case 'L1' dist = comp_dist_L1(X, Y); case 'L2' dist = comp_dist_euclidean(X, Y); case 'angle' dist = comp_dist_angle(X, Y); case 'corr' dist = comp_dist_corr(X, Y); otherwise error('invalid metric selected'); end end %% comp_dist_euclidean: function dist = comp_dist_euclidean(X, Y) % X has size m*d, Y n*d m = size(X, 1); n = size(Y, 1); dist = zeros(m,n); for ii = 1:m dist(ii,:) = sqrt(sum((repmat(X(ii,:),n,1) - Y).^2,2)); end end %% comp_dist_L1: function dist = comp_dist_L1(X, Y) % set up m = size(X, 1); n = size(Y, 1); dist = zeros(m, n); for ii = 1:m dist(ii,:) = sum(abs(repmat(X(ii,:), n, 1) - Y),2); end end %% comp_dist_corr: function dist = comp_dist_corr(X, Y) corr = calc_corr(X,Y); dist = 1-corr; end %% comp_dist_angle: function dist = comp_dist_angle(X, Y) % L2-normalization X = bsxfun(@times, X, 1./sqrt(sum(X.^2, 2))); Y = bsxfun(@times, Y, 1./sqrt(sum(Y.^2, 2))); % dot_prod = X*Y'; % dist = acos(dot_prod)/pi; % set up m = size(X, 1); n = size(Y, 1); dist = zeros(m, n); for ii = 1:m dot_prod = X(ii, :) * Y'; dist(ii, :) = real(acos(dot_prod)/pi); end end %% comp_dist_abs_corr: function dist = comp_dist_abs_corr(X, Y) corr = calc_corr(X,Y); dist = 1-abs(corr); end %% calc_corr: function [corr] = calc_corr(X, Y) % set up m = size(X, 1); n = size(Y, 1); corr = zeros(m, n); % zero-mean X = bsxfun(@minus, X, mean(X, 1)); Y = bsxfun(@minus, Y, mean(Y, 1)); % L2-normalization X = bsxfun(@times, X, 1./sqrt(sum(X.^2, 1))); Y = bsxfun(@times, Y, 1./sqrt(sum(Y.^2, 1))); % calculation correlation for ii = 1:m corr(ii,:) = X(ii,:) * Y'; end end
github
sibirbil/VBYO-master
ex0.m
.m
VBYO-master/kodlar/YuksekBasarimliHesaplama/Matlab/ex0.m
307
utf_8
a46204430cb95f7303b507c1d434a901
function total = ex0() clear A; for i = 1:10 A(i) = i*1000000; end B = zeros(10,1); tic for i = 1:length(A) B(i) = f(A(i)); end total = sum(B); toc end function total = f(n) total = 0; for i = 1:n total = total + 1/i; end end
github
djangraw/FelixScripts-master
pop_logisticregression_fast.m
.m
FelixScripts-master/MATLAB/LogReg/pop_logisticregression_fast.m
12,958
utf_8
e956b7f27c65b85e6cd62272eff529df
% pop_logisticregression() - Determine linear discriminating vector between two datasets. % using logistic regression. % % Usage: % >> pop_logisticregression_fast( ALLEEG, datasetlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show, LOO, bootstrap); % % Inputs: % ALLEEG - array of datasets % datasetlist - list of datasets % chansubset - vector of channel subset for dataset 1 [1:min(Dset1,Dset2)] % chansubset2 - vector of channel subset for dataset 2 [chansubset] % trainingwindowlength - Length of training window in samples [all] % trainingwindowoffset - Offset(s) of training window(s) in samples [1] % regularize - regularize [1|0] -> [yes|no] [0] % lambda - regularization constant for weight decay. [1e-6] % Makes logistic regression into a support % vector machine for large lambda % (cf. Clay Spence) % lambdasearch - [1|0] -> search for optimal regularization % constant lambda % eigvalratio - if the data does not fill D-dimensional % space, i.e. rank(x)<D, you should specify % a minimum eigenvalue ratio relative to the % largest eigenvalue of the SVD. All dimensions % with smaller eigenvalues will be eliminated % prior to the discrimination. % vinit - initialization for faster convergence [zeros(D+1,1)] % show - display discrimination boundary during training [0] % LOO - run leave-one-out analysis [0] % bootstrap - run bootstrapping to compute significance Az levels [0] % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Adam Gerson % and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5/21/2005, Fixed bug in leave one out script, Adam function [ALLEEG, eegTimes, Az_loo, Az_perm_dist, com] = pop_logisticregression_fast(ALLEEG, setlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show,LOO,bootstrap); showaz=1; com = ''; if nargin < 1 help pop_logisticregression; return; end; if isempty(ALLEEG) error('pop_logisticregression(): cannot process empty sets of data'); end; if nargin < 2 % which set to save % ----------------- uilist = { { 'style' 'text' 'string' 'Enter two datasets to compare (ex: 1 3):' } ... { 'style' 'edit' 'string' [ '1 2' ] } ... { 'style' 'text' 'string' 'Enter channel subset ([] = all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Enter channel subset for dataset 2 ([] = same as dataset 1):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Training Window Length (samples [] = all):' } ... { 'style' 'edit' 'string' '50' } ... { 'style' 'text' 'string' 'Training Window Offset (samples, 1 = epoch start):' } ... { 'style' 'edit' 'string' '1' } ... { 'style' 'text' 'string' 'Regularize' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Regularization constant for weight decay' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Search for optimal regularization constant' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Eigenvalue ratio for subspace reduction' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Initial discrimination vector [channels+1 x 1] for faster convergence (optional)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Display discrimination boundary' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Leave One Out' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} }; result = inputgui( { [2 .5] [2 .5] [2 .5] [2 .5] [2 .5] [3.1 .4 .15] [2 .5] [3.1 .4 .15] [2 .5] [2 .5] [3.1 .4 .15] [3.1 .4 .15] }, ... uilist, 'pophelp(''pop_logisticregression'')', ... 'Logistic Regression -- pop_logisticregression()'); if length(result) == 0 return; end; setlist = eval( [ '[' result{1} ']' ] ); chansubset = eval( [ '[' result{2} ']' ] ); if isempty( chansubset ), chansubset = 1:min(ALLEEG(setlist(1)).nbchan,ALLEEG(setlist(2)).nbchan); end; chansubset2 = eval( [ '[' result{3} ']' ] ); if isempty(chansubset2), chansubset2=chansubset; end trainingwindowlength = str2num(result{4}); if isempty(trainingwindowlength) trainingwindowlength = ALLEEG(setlist(1)).pnts; end; trainingwindowoffset = str2num(result{5}); if isempty(trainingwindowoffset) trainingwindowoffset = 1; end; regularize=result{6}; if isempty(regularize), regularize=0; end lambda=str2num(result{7}); if isempty(lambda), lambda=1e-6; end lambdasearch=result{8}; if isempty(lambdasearch), lambdasearch=0; end eigvalratio=str2num(result{9}); if isempty(eigvalratio), eigvalratio=1e-6; end vinit=eval([ '[' result{10} ']' ]); if isempty(vinit), vinit=zeros(length(chansubset)+1,1); end vinit=vinit(:); % Column vector show=result{11}; if isempty(show), show=0; end LOO=result{12}; if isempty(LOO), LOO=0; end bootstrap=result{13}; if isempty(bootstrap) bootstrap=0; end end; truth=[zeros(trainingwindowlength.*ALLEEG(setlist(1)).trials,1); ones(trainingwindowlength.*ALLEEG(setlist(2)).trials,1)]; truthmean=([zeros(ALLEEG(setlist(1)).trials,1); ones(ALLEEG(setlist(2)).trials,1)]); N=ALLEEG(setlist(1)).trials+ALLEEG(setlist(2)).trials; if LOO == 0 bootstrap = 0; else if bootstrap == 1; logistMode = 'loo_and_bootstrap'; else; logistMode = 'loo'; end Az_loo = zeros(length(trainingwindowoffset),1); cv = []; cv.numFolds = N; cv.outTrials = cell(1,N); for n=1:N cv.outTrials{n} = (n-1)*trainingwindowlength+1:n*trainingwindowlength; end end try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(1)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 1'); end if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(2)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 2'); end if (length(chansubset)~=length(chansubset2)), error('Number of channels from each dataset must be equal.'); end nperms = 250; truth_perms = zeros(trainingwindowlength*N,nperms); for n=1:nperms truth_perms(:,n) = reshape(repmat(assertVec(truthmean(randperm(N)),'row'),trainingwindowlength,1),N*trainingwindowlength,1); end ALLEEG(setlist(1)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan); % In case a subset of channels are used, assign unused electrodes in scalp projection to NaN ALLEEG(setlist(1)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan)'; ALLEEG(setlist(2)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan)'; ALLEEG(setlist(1)).icasphere=eye(ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icasphere=eye(ALLEEG(setlist(2)).nbchan); timesArr = ALLEEG(setlist(1)).times; eegTimes = zeros(length(trainingwindowoffset),1); Az_perm_dist = cell(length(trainingwindowoffset),1); for i=1:length(trainingwindowoffset), x=cat(3,ALLEEG(setlist(1)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:), ... ALLEEG(setlist(2)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:)); eegTimes(i) = mean(timesArr(trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1)); x=x(:,:)'; % Rearrange data for logist.m [D x trials)]' %v=logist(x,truth)'; v = logist(x,truth,vinit,show,regularize,lambda,lambdasearch,eigvalratio); y = x*v(1:end-1) + v(end); bp = bernoull(1,y); [Az,Ry,Rx] = rocarea(bp,truth); if showaz, fprintf('Window Onset: %d; Az: %6.2f\n',trainingwindowoffset(i),Az); end a = (y-mean(y)) \ x; ALLEEG(setlist(1)).icaweights(i,chansubset)=v(1:end-1)'; ALLEEG(setlist(2)).icaweights(i,chansubset2)=v(1:end-1)'; ALLEEG(setlist(1)).icawinv(chansubset,i)=a'; % consider replacing with asetlist1 ALLEEG(setlist(2)).icawinv(chansubset2,i)=a'; % consider replacing with asetlist2 if LOO % LOO [ws_loo,ys_loo,Az_loo(i),Az_perm_dist{i}] = logist_fast(x',truth,lambda,logistMode,cv,truth_perms);%_and_bootstrap disp(['Az LOO: ',num2str(Az_loo(i))]); figure(102);plot(eegTimes(1:i),Az_loo(1:i)); pause(1e-9); end if 0 ALLEEG(setlist(1)).lrweights(i,:)=v; ALLEEG(setlist(1)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(2)).lrweights(i,:)=v; ALLEEG(setlist(2)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(1)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(1)).data(:,:); ones(1,ALLEEG(setlist(1)).pnts.*ALLEEG(setlist(1)).trials)], ... ALLEEG(setlist(1)).pnts,ALLEEG(setlist(1)).trials),-1); ALLEEG(setlist(2)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(2)).data(:,:); ones(1,ALLEEG(setlist(2)).pnts.*ALLEEG(setlist(2)).trials)], ... ALLEEG(setlist(2)).pnts,ALLEEG(setlist(2)).trials),-1); end end; if LOO figure(102); plot(eegTimes,Az_loo); end if 0 ALLEEG(setlist(1)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(1)).lrtrainoffset=trainingwindowoffset; ALLEEG(setlist(2)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(2)).lrtrainoffset=trainingwindowoffset; end % save channel names % ------------------ %plottopo( tracing, ALLEEG(setlist(1)).chanlocs, ALLEEG(setlist(1)).pnts, [ALLEEG(setlist(1)).xmin ALLEEG(setlist(1)).xmax 0 0]*1000, plottitle, chansubset ); % recompute activations (temporal sources) and check dataset integrity eeg_options; for i=1:2, if option_computeica ALLEEG(setlist(i)).icaact = (ALLEEG(setlist(i)).icaweights*ALLEEG(setlist(i)).icasphere)*reshape(ALLEEG(setlist(i)).data, ALLEEG(setlist(i)).nbchan, ALLEEG(setlist(i)).trials*ALLEEG(setlist(i)).pnts); ALLEEG(setlist(i)).icaact = reshape( ALLEEG(setlist(i)).icaact, size(ALLEEG(setlist(i)).icaact,1), ALLEEG(setlist(i)).pnts, ALLEEG(setlist(i)).trials); end; end for i=1:2, [ALLEEG]=eeg_store(ALLEEG,ALLEEG(setlist(i)),setlist(i)); end com = sprintf('pop_logisticregression( %s, [%s], [%s], [%s], [%s]);', inputname(1), num2str(setlist), num2str(chansubset), num2str(trainingwindowlength), num2str(trainingwindowoffset)); fprintf('Done.\n'); return;
github
djangraw/FelixScripts-master
rocarea.m
.m
FelixScripts-master/MATLAB/LogReg/rocarea.m
2,126
utf_8
2be03622d12ae6f9025efde8ba6014d6
% rocarea() - computes the area under the ROC curve % If no output arguments are specified % it will display an ROC curve with the % Az and approximate fraction correct. % % Usage: % >> [Az,tp,fp,fc]=rocarea(p,label); % % Inputs: % p - classification output % label - truth labels {0,1} % % Outputs: % Az - Area under ROC curve % tp - true positive rate % fp - false positive rate % fc - fraction correct % % Authors: Lucas Parra ([email protected], 2004) % with Adam Gerson (reformatted for EEGLAB) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Lucas Parra % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [Az,tp,fp,fc]=rocarea(p,label); [tmp,indx]=sort(-p); label = label>0; Np=sum(label==1); Nn=sum(label==0); tp=0; pinc=1/Np; fp=0; finc=1/Nn; Az=0; N=Np+Nn; tp=zeros(N+1,1); fp=zeros(N+1,1); for i=1:N tp(i+1)=tp(i)+label(indx(i))/Np; fp(i+1)=fp(i)+(~label(indx(i)))/Nn; Az = Az + (~label(indx(i)))*tp(i+1)/Nn; end; [m,i]=min(fp-tp); fc = 1-mean([fp(i), 1-tp(i)]); if nargout==0 plot(fp,tp); axis([0 1 0 1]); hold on plot([0 1],[1 0],':'); hold off xlabel('false positive rate') ylabel('true positive rate') title('ROC Curve'); axis([0 1 0 1]); text(0.4,0.2,sprintf('Az = %.2f',Az)) text(0.4,0.1,sprintf('fc = %.2f',fc)) axis square end
github
djangraw/FelixScripts-master
GetLooResults.m
.m
FelixScripts-master/MATLAB/LogReg/GetLooResults.m
16,151
utf_8
9cb3acac53fa63ba05b692f2cbb1aff8
function varargout = GetLooResults(varargin) % GETLOORESULTS M-file for GetLooResults.fig % GETLOORESULTS, by itself, creates a new GETLOORESULTS or raises the existing % singleton*. % % H = GETLOORESULTS returns the handle to a new GETLOORESULTS or the handle to % the existing singleton*. % % GETLOORESULTS('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in GETLOORESULTS.M with the given input arguments. % % GETLOORESULTS('Property','Value',...) creates a new GETLOORESULTS or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before GetLooResults_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to GetLooResults_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help GetLooResults % Last Modified by GUIDE v2.5 24-Feb-2011 16:27:30 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @GetLooResults_OpeningFcn, ... 'gui_OutputFcn', @GetLooResults_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before GetLooResults is made visible. function GetLooResults_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to GetLooResults (see VARARGIN) % Choose default command line output for GetLooResults handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes GetLooResults wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = GetLooResults_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % IMPORTANT FUNCTIONS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes on button press in button_load. function button_load_Callback(hObject, eventdata, handles) % hObject handle to button_load (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.filename = get(handles.edit_filename,'String'); if ~exist(handles.filename) set(handles.text_file,'String','File Not Found!'); else load(handles.filename) set(handles.text_file,'String',sprintf('%d entries found!',length(LOO))); set(handles.popup_setname1,'String',[{'Any'}, unique({LOO(:).setname1}) ] ); set(handles.popup_setname2,'String',[{'Any'}, unique({LOO(:).setname2}) ] ); set(handles.popup_reference,'String',[{'Any'}, num2str(unique(cellfun('length',{LOO(:).reference}))') ] ); set(handles.popup_twl,'String',[{'Any'}, num2str(unique([LOO(:).trainingwindowlength])') ] ); set(handles.popup_twi,'String',[{'Any'}, num2str(unique([LOO(:).trainingwindowinterval])') ] ); % etcetera... end guidata(hObject, handles); % --- Executes on button press in button_search. function button_search_Callback(hObject, eventdata, handles) % hObject handle to button_search (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Parse input from ChooseSearchCriteria panel of GUI inputStr = ['''filename'', ''' handles.filename '''']; dateStr = get(handles.edit_date,'String'); if ~isempty(dateStr) inputStr = [inputStr, ', ''datetime'', ''' dateStr '''']; end setname1Str = get(handles.popup_setname1,'String'); setname1Str = setname1Str{get(handles.popup_setname1,'Value')}; if ~strcmp(setname1Str,'Any') inputStr = [inputStr ', ''setname1'', ''' setname1Str '''']; end setname2Str = get(handles.popup_setname2,'String'); setname2Str = setname2Str{get(handles.popup_setname2,'Value')}; if ~strcmp(setname2Str,'Any') inputStr = [inputStr ', ''setname2'', ''' setname2Str '''']; end referenceStr = get(handles.popup_reference,'String'); referenceStr = referenceStr{get(handles.popup_reference,'Value')}; if ~strcmp(referenceStr,'Any') inputStr = [inputStr ', ''reference'', ''' referenceStr '''']; end twlStr = get(handles.popup_twl,'String'); twlStr = twlStr{get(handles.popup_twl,'Value')}; if ~strcmp(twlStr,'Any') inputStr = [inputStr ', ''trainingwindowlength'', ''' twlStr '''']; end twiStr = get(handles.popup_twi,'String'); twiStr = twiStr{get(handles.popup_twi,'Value')}; if ~strcmp(twiStr,'Any') inputStr = [inputStr ', ''trainingwindowinterval'', ''' twiStr '''']; end % Get results from LOO struct eval(['handles.fits = LoadLooResults(' inputStr ');']); % Send to PlotResults panel of GUI if isempty(handles.fits) set(handles.popup_results,'String',' '); else set(handles.popup_results,'String',{handles.fits.datetime}); end set(handles.popup_results,'Value',1); set(handles.text_results,'String',sprintf('%d result(s) found: pick one above',numel(handles.fits))); guidata(hObject, handles); % --- Executes on button press in button_calendar. function button_calendar_Callback(hObject, eventdata, handles) % hObject handle to button_calendar (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) uicalendar('Weekend', [1 0 0 0 0 0 1], ... 'SelectionType', 1, ... 'DestinationUI', handles.edit_date); % --- Executes on selection change in popup_results. function popup_results_Callback(hObject, eventdata, handles) % hObject handle to popup_results (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_results contents as cell array % contents{get(hObject,'Value')} returns selected item from % popup_results if isfield(handles,'fits') && ~isempty(handles.fits) result = handles.fits(get(handles.popup_results,'Value')); fields = fieldnames(result); dispText = {''}; for i=1:numel(fields) thisField = result.(fields{i}); if isnumeric(thisField) || islogical(thisField) if length(thisField)==1 dispText = [dispText; {sprintf('%s: %g',fields{i},thisField)}]; else dispText = [dispText; {sprintf('%s: %g to %g',fields{i},thisField(1),thisField(end))}]; end else dispText = [dispText; {sprintf('%s: %s',fields{i},thisField)}]; end end set(handles.text_results,'String',dispText); guidata(hObject, handles); end % --- Executes on button press in button_plot. function button_plot_Callback(hObject, eventdata, handles) % hObject handle to button_plot (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) if isfield(handles,'fits') && ~isempty(handles.fits) result = handles.fits(get(handles.popup_results,'Value')); figure; PlotLooResults(result); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % OTHER FUNCTIONS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function edit_filename_Callback(hObject, eventdata, handles) % hObject handle to edit_filename (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_filename as text % str2double(get(hObject,'String')) returns contents of edit_filename as a double % --- Executes during object creation, after setting all properties. function edit_filename_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_filename (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_date_Callback(hObject, eventdata, handles) % hObject handle to edit_date (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_date as text % str2double(get(hObject,'String')) returns contents of edit_date as a double % --- Executes during object creation, after setting all properties. function edit_date_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_date (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popup_setname1. function popup_setname1_Callback(hObject, eventdata, handles) % hObject handle to popup_setname1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_setname1 contents as cell array % contents{get(hObject,'Value')} returns selected item from popup_setname1 % --- Executes during object creation, after setting all properties. function popup_setname1_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_setname1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popup_setname2. function popup_setname2_Callback(hObject, eventdata, handles) % hObject handle to popup_setname2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_setname2 contents as cell array % contents{get(hObject,'Value')} returns selected item from popup_setname2 % --- Executes during object creation, after setting all properties. function popup_setname2_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_setname2 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popup_reference. function popup_reference_Callback(hObject, eventdata, handles) % hObject handle to popup_reference (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_reference contents as cell array % contents{get(hObject,'Value')} returns selected item from popup_reference % --- Executes during object creation, after setting all properties. function popup_reference_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_reference (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popup_twl. function popup_twl_Callback(hObject, eventdata, handles) % hObject handle to popup_twl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_twl contents as cell array % contents{get(hObject,'Value')} returns selected item from popup_twl % --- Executes during object creation, after setting all properties. function popup_twl_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_twl (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on selection change in popup_twi. function popup_twi_Callback(hObject, eventdata, handles) % hObject handle to popup_twi (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_twi contents as cell array % contents{get(hObject,'Value')} returns selected item from popup_twi % --- Executes during object creation, after setting all properties. function popup_twi_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_twi (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes during object creation, after setting all properties. function popup_results_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_results (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
djangraw/FelixScripts-master
pop_logisticregression.m
.m
FelixScripts-master/MATLAB/LogReg/pop_logisticregression.m
13,157
utf_8
63e70f3159414b889bbb30aae887ba6d
% pop_logisticregression() - Determine linear discriminating vector between two datasets. % using logistic regression. % % Usage: % >> pop_logisticregression( ALLEEG, datasetlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show); % % Inputs: % ALLEEG - array of datasets % datasetlist - list of datasets % chansubset - vector of channel subset for dataset 1 [1:min(Dset1,Dset2)] % chansubset2 - vector of channel subset for dataset 2 [chansubset] % trainingwindowlength - Length of training window in samples [all] % trainingwindowoffset - Offset(s) of training window(s) in samples [1] % regularize - regularize [1|0] -> [yes|no] [0] % lambda - regularization constant for weight decay. [1e-6] % Makes logistic regression into a support % vector machine for large lambda % (cf. Clay Spence) % lambdasearch - [1|0] -> search for optimal regularization % constant lambda % eigvalratio - if the data does not fill D-dimensional % space, i.e. rank(x)<D, you should specify % a minimum eigenvalue ratio relative to the % largest eigenvalue of the SVD. All dimensions % with smaller eigenvalues will be eliminated % prior to the discrimination. % vinit - initialization for faster convergence [zeros(D+1,1)] % show - display discrimination boundary during training [0] % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Adam Gerson % and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5/21/2005, Fixed bug in leave one out script, Adam function [ALLEEG, com] = pop_logisticregression(ALLEEG, setlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show); showaz=1; com = ''; if nargin < 1 help pop_logisticregression; return; end; if isempty(ALLEEG) error('pop_logisticregression(): cannot process empty sets of data'); end; if nargin < 2 % which set to save % ----------------- uilist = { { 'style' 'text' 'string' 'Enter two datasets to compare (ex: 1 3):' } ... { 'style' 'edit' 'string' [ '1 2' ] } ... { 'style' 'text' 'string' 'Enter channel subset ([] = all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Enter channel subset for dataset 2 ([] = same as dataset 1):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Training Window Length (samples [] = all):' } ... { 'style' 'edit' 'string' '50' } ... { 'style' 'text' 'string' 'Training Window Offset (samples, 1 = epoch start):' } ... { 'style' 'edit' 'string' '1' } ... { 'style' 'text' 'string' 'Regularize' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Regularization constant for weight decay' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Search for optimal regularization constant' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Eigenvalue ratio for subspace reduction' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Initial discrimination vector [channels+1 x 1] for faster convergence (optional)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Display discrimination boundary' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Leave One Out' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} }; result = inputgui( { [2 .5] [2 .5] [2 .5] [2 .5] [2 .5] [3.1 .4 .15] [2 .5] [3.1 .4 .15] [2 .5] [2 .5] [3.1 .4 .15] [3.1 .4 .15] }, ... uilist, 'pophelp(''pop_logisticregression'')', ... 'Logistic Regression -- pop_logisticregression()'); if length(result) == 0 return; end; setlist = eval( [ '[' result{1} ']' ] ); chansubset = eval( [ '[' result{2} ']' ] ); if isempty( chansubset ), chansubset = 1:min(ALLEEG(setlist(1)).nbchan,ALLEEG(setlist(2)).nbchan); end; chansubset2 = eval( [ '[' result{3} ']' ] ); if isempty(chansubset2), chansubset2=chansubset; end trainingwindowlength = str2num(result{4}); if isempty(trainingwindowlength) trainingwindowlength = ALLEEG(setlist(1)).pnts; end; trainingwindowoffset = str2num(result{5}); if isempty(trainingwindowoffset) trainingwindowoffset = 1; end; regularize=result{6}; if isempty(regularize), regularize=0; end lambda=str2num(result{7}); if isempty(lambda), lambda=1e-6; end lambdasearch=result{8}; if isempty(lambdasearch), lambdasearch=0; end eigvalratio=str2num(result{9}); if isempty(eigvalratio), eigvalratio=1e-6; end vinit=eval([ '[' result{10} ']' ]); if isempty(vinit), vinit=zeros(length(chansubset)+1,1); end vinit=vinit(:); % Column vector show=result{11}; if isempty(show), show=0; end LOO=result{12}; if isempty(LOO), show=0; end end; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(1)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 1'); end if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(2)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 2'); end if (length(chansubset)~=length(chansubset2)), error('Number of channels from each dataset must be equal.'); end truth=[zeros(trainingwindowlength.*ALLEEG(setlist(1)).trials,1); ones(trainingwindowlength.*ALLEEG(setlist(2)).trials,1)]; ALLEEG(setlist(1)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan); % In case a subset of channels are used, assign unused electrodes in scalp projection to NaN ALLEEG(setlist(1)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan)'; ALLEEG(setlist(2)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan)'; ALLEEG(setlist(1)).icasphere=eye(ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icasphere=eye(ALLEEG(setlist(2)).nbchan); for i=1:length(trainingwindowoffset), x=cat(3,ALLEEG(setlist(1)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:), ... ALLEEG(setlist(2)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:)); x=x(:,:)'; % Rearrange data for logist.m [D (T x trials)]' %v=logist(x,truth)'; v = logist(x,truth,vinit,show,regularize,lambda,lambdasearch,eigvalratio); y = x*v(1:end-1) + v(end); bp = bernoull(1,y); [Az,Ry,Rx] = rocarea(bp,truth); if showaz, fprintf('Window Onset: %d; Az: %6.2f\n',trainingwindowoffset(i),Az); end a = y \ x; asetlist1=y(1:trainingwindowlength.*ALLEEG(setlist(1)).trials) \ x(1:trainingwindowlength.*ALLEEG(setlist(1)).trials,:); asetlist2=y(trainingwindowlength.*ALLEEG(setlist(1)).trials+1:end) \ x(trainingwindowlength.*ALLEEG(setlist(1)).trials+1:end,:); ALLEEG(setlist(1)).icaweights(i,chansubset)=v(1:end-1)'; ALLEEG(setlist(2)).icaweights(i,chansubset2)=v(1:end-1)'; ALLEEG(setlist(1)).icawinv(chansubset,i)=a'; % consider replacing with asetlist1 ALLEEG(setlist(2)).icawinv(chansubset2,i)=a'; % consider replacing with asetlist2 if LOO % LOO clear y; N=ALLEEG(setlist(1)).trials+ALLEEG(setlist(2)).trials; ploo=zeros(N*trainingwindowlength,1); for looi=1:length(x)./trainingwindowlength, indx=ones(N*trainingwindowlength,1); indx((looi-1)*trainingwindowlength+1:looi*trainingwindowlength)=0; tmp = x(find(indx),:); % LOO data tmpt = [truth(find(indx))]; % Target vloo(:,looi)=logist(tmp,tmpt,vinit,show,regularize,lambda,lambdasearch,eigvalratio); y(:,looi) = [x((looi-1)*trainingwindowlength+1:looi*trainingwindowlength,:) ones(trainingwindowlength,1)]*vloo(:,looi); ymean(looi)=mean(y(:,looi)); % ploo(find(1-indx)) = bernoull(1,y(:,looi)); ploo((looi-1)*trainingwindowlength+1:looi*trainingwindowlength) = bernoull(1,y(:,looi)); ploomean(looi)=bernoull(1,ymean(looi)); end truthmean=([zeros(ALLEEG(setlist(1)).trials,1); ones(ALLEEG(setlist(2)).trials,1)]); [Azloo,Ryloo,Rxloo] = rocarea(ploo,truth); [Azloomean,Ryloomean,Rxloomean] = rocarea(ploomean,truthmean); fprintf('LOO Az: %6.2f\n',Azloomean); end if 0 ALLEEG(setlist(1)).lrweights(i,:)=v; ALLEEG(setlist(1)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(2)).lrweights(i,:)=v; ALLEEG(setlist(2)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(1)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(1)).data(:,:); ones(1,ALLEEG(setlist(1)).pnts.*ALLEEG(setlist(1)).trials)], ... ALLEEG(setlist(1)).pnts,ALLEEG(setlist(1)).trials),-1); ALLEEG(setlist(2)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(2)).data(:,:); ones(1,ALLEEG(setlist(2)).pnts.*ALLEEG(setlist(2)).trials)], ... ALLEEG(setlist(2)).pnts,ALLEEG(setlist(2)).trials),-1); end end; if 0 ALLEEG(setlist(1)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(1)).lrtrainoffset=trainingwindowoffset; ALLEEG(setlist(2)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(2)).lrtrainoffset=trainingwindowoffset; end % save channel names % ------------------ %plottopo( tracing, ALLEEG(setlist(1)).chanlocs, ALLEEG(setlist(1)).pnts, [ALLEEG(setlist(1)).xmin ALLEEG(setlist(1)).xmax 0 0]*1000, plottitle, chansubset ); % recompute activations (temporal sources) and check dataset integrity eeg_options; for i=1:2, if option_computeica ALLEEG(setlist(i)).icaact = (ALLEEG(setlist(i)).icaweights*ALLEEG(setlist(i)).icasphere)*reshape(ALLEEG(setlist(i)).data, ALLEEG(setlist(i)).nbchan, ALLEEG(setlist(i)).trials*ALLEEG(setlist(i)).pnts); ALLEEG(setlist(i)).icaact = reshape( ALLEEG(setlist(i)).icaact, size(ALLEEG(setlist(i)).icaact,1), ALLEEG(setlist(i)).pnts, ALLEEG(setlist(i)).trials); end; end for i=1:2, [ALLEEG]=eeg_store(ALLEEG,ALLEEG(setlist(i)),setlist(i)); end com = sprintf('pop_logisticregression( %s, [%s], [%s], [%s], [%s]);', inputname(1), num2str(setlist), num2str(chansubset), num2str(trainingwindowlength), num2str(trainingwindowoffset)); fprintf('Done.\n'); return;
github
djangraw/FelixScripts-master
logist.m
.m
FelixScripts-master/MATLAB/LogReg/logist.m
9,656
utf_8
32dc6838e6797558e29e95e0497192ea
% logist() - Iterative recursive least squares algorithm for linear % logistic model % % Usage: % >> [v] = logist(x,y,vinit,show,regularize,lambda,lambdasearch,eigvalratio); % % Inputs: % x - N input samples [N,D] % y - N binary labels [N,1] {0,1} % % Optional parameters: % vinit - initialization for faster convergence % show - if>0 will show first two dimensions % regularize - [1|0] -> [yes|no] % lambda - regularization constant for weight decay. Makes % logistic regression into a support vector machine % for large lambda (cf. Clay Spence). Defaults to 10^-6. % lambdasearch- [1|0] -> search for optimal regularization constant lambda % eigvalratio - if the data does not fill D-dimensional space, % i.e. rank(x)<D, you should specify a minimum % eigenvalue ratio relative to the largest eigenvalue % of the SVD. All dimensions with smaller eigenvalues % will be eliminated prior to the discrimination. % % Outputs: % v - v(1:D) normal to separating hyperplane. v(D+1) slope % % Compute probability of new samples with p = bernoull(1,[x 1]*v); % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) % % CHANGED 3/25/11 by DJ and BC - to prevent convergence on first iteration % (if v is initialized to zero), we set v=v+eps. To prevent never % converging, we needed to set the convergence threshold higher, so we made % it a parameter (convergencethreshold). At the advice of matlab, we % changed from inv(...)*grad to (...)\grad. We also added a topoplot % (based on the channel locations in ALLEEG(1)) to the 'show' figure. And % we got rid of the line if regularize, lambda=1e-6; end. % UPDATED 5/23/13 by DJ - allow non-scalar lambda % UPDATED 10/31/14 by DJ - cleanup for readability %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [v] = logist(x,y,v,show,regularize,lambda,lambdasearch,eigvalratio) printoutput=0; convergencethreshold = 1e-6; % look at plot (show=1) to find a good value here [N,D]=size(x); iter=0; showcount=0; if nargin<3 || isempty(v), v=zeros(D,1); vth=0; else vth=v(D+1); v=v(1:D); end; if nargin<4 || isempty(show); show=0; end; if nargin<5 || isempty(regularize); regularize=0; end if nargin<6 || isempty(lambda); lambda=eps; end; if nargin<7 || isempty(lambdasearch), lambdasearch=0; end if nargin<8 || isempty(eigvalratio); eigvalratio=0; end; % if regularize, lambda=1e-6; end % subspace reduction if requested - electrodes might be linked if eigvalratio [~,S,V] = svd(x,0); % subspace analysis V = V(:,(diag(S)/S(1,1)>eigvalratio)); % keep significant subspace x = x*V; % map the data to that subspace v = V'*v; % reduce initialization to the subspace [N,D]=size(x); % less dimensions now end % combine threshold computation with weight vector. x = [x ones(N,1)]; v = [v; vth]+eps; % v = randn(size(v))*eps; vold=ones(size(v)); if regularize, if numel(lambda)==1 lambda = [0.5*lambda*ones(1,D) 0]'; elseif numel(lambda)==D lambda = [0.5*lambda(:); 0]; else lambda = 0.5*lambda; end end % clear warning as we will use it to catch conditioning problems lastwarn(''); % If lambda increases, the maximum number of iterations is increased from % maxiter to maxiterlambda maxiter=100; maxiterlambda=1000; singularwarning=0; lambdawarning=0; % Initialize warning flags if show, figure; end % IRLS for binary classification of experts (bernoulli distr.) while ((subspace(vold,v)>convergencethreshold) && (iter<=maxiter) && (~singularwarning) && (~lambdawarning)) || iter==0, vold=v; mu = bernoull(1,x*v); % recompute weights w = mu.*(1-mu); e = (y - mu); grad = x'*e; % - lambda .* v; if regularize, % lambda=(v'*v)./2; % grad=grad-lambda; grad=grad - lambda .* v; end %inc = inv(x'*diag(w)*x+eps*eye(D+1)) * grad; inc = (x'*(repmat(w,1,D+1).*x)+diag(lambda)*eye(D+1)) \ grad; if strncmp(lastwarn,'Matrix is close to singular or badly scaled.',44) warning('Bad conditioning. Suggest reducing subspace.') singularwarning=1; end if (norm(inc)>=1000) && regularize, if ~lambdasearch, warning('Data may be perfectly separable. Suggest increasing regularization constant lambda'); end lambdawarning=1; end; % avoid funny outliers that happen with inv if (norm(inc)>=1000) && regularize && lambdasearch, % Increase regularization constant lambda lambda=sign(lambda).*abs(lambda.^(1/1.02)); lambdawarning=0; if printoutput, fprintf('Bad conditioning. Data may be perfectly separable. Increasing lambda to: %6.2f\n',lambda(1)); end maxiter=maxiterlambda; elseif (~singularwarning) && (~lambdawarning), % update v = v + inc; if show showcount=showcount+1; subplot(1,3,1) ax=[min(x(:,1)), max(x(:,1)), min(x(:,2)), max(x(:,2))]; hold off; h(1)=plot(x(y>0,1),x(y>0,2),'bo'); hold on; h(2)=plot(x(y<1,1),x(y<1,2),'r+'); xlabel('First Dimension','FontSize',14); ylabel('Second Dimension','FontSize',14); title('Discrimination Boundary','FontSize',14); legend(h,'Dataset 1','Dataset 2'); axis square; if norm(v)>0, tmean=mean(x); tmp = tmean; tmp(1)=0; t1=tmp; t1(2)=ax(3); t2=tmp; t2(2)=ax(4); xmin=median([ax(1), -(t1*v)/v(1), -(t2*v)/v(1)]); xmax=median([ax(2), -(t1*v)/v(1), -(t2*v)/v(1)]); tmp = tmean; tmp(2)=0; t1=tmp; t1(1)=ax(1); t2=tmp; t2(1)=ax(2); ymin=median([ax(3), -(t1*v)/v(2), -(t2*v)/v(2)]); ymax=median([ax(4), -(t1*v)/v(2), -(t2*v)/v(2)]); if v(1)*v(2)>0, tmp=xmax;xmax=xmin;xmin=tmp;end; if ~(xmin<ax(1) || xmax>ax(2) || ymin<ax(3) || ymax>ax(4)), h=plot([xmin xmax],[ymin ymax],'k','LineWidth',2); end; end; subplot(1,3,2); vnorm(showcount) = subspace(vold,v); if vnorm(showcount)==0, vnorm(showcount)=nan; end plot(log(vnorm)/log(10)); title('Subspace between v(t) and v(t+1)','FontSize',14); xlabel('Iteration','FontSize',14); ylabel('Subspace','FontSize',14); axis square; subplot(1,3,3); % ALLEEG = evalin('base','ALLEEG'); % topoplot(v(1:(end-1)),ALLEEG(1).chanlocs,'electrodes','on'); title('Spatial weights for this iteration') colorbar; drawnow; end; % exit if converged if subspace(vold,v)<convergencethreshold, % CHANGED if printoutput, disp('Converged... '); disp(['Iterations: ' num2str(iter)]); disp(['Subspace: ' num2str(subspace(vold,v))]); disp(['Lambda: ' num2str(lambda(1))]); end end; end % exit if taking too long iter=iter+1; if iter>maxiter, if printoutput, disp(['Not converging after ' num2str(maxiter) ' iterations.']); disp(['Iterations: ' num2str(iter-1)]); disp(['Subspace: ' num2str(subspace(vold,v))]); disp(['Lambda: ' num2str(lambda(1))]); end end; end; if eigvalratio v = [V*v(1:D);v(D+1)]; % the result should be in the original space end function [p]=bernoull(x,eta) % bernoull() - Computes Bernoulli distribution of x for "natural parameter" eta. % % Usage: % >> [p] = bernoull(x,eta) % % The mean m of a Bernoulli distributions relates to eta as, % m = exp(eta)/(1+exp(eta)); p = exp(eta.*x - log(1+exp(eta)));
github
djangraw/FelixScripts-master
bernoull.m
.m
FelixScripts-master/MATLAB/LogReg/bernoull.m
1,630
utf_8
858cf1a152c7a6041d64ad220a523d34
% bernoull() - Computes Bernoulli distribution of x for % "natural parameter" eta. The mean m of a % Bernoulli distributions relates to eta as, % m = exp(eta)/(1+exp(eta)); % % Usage: % >> [p]=bernoull(x,eta); % % Inputs: % x - data % eta - distribution parameter % % Outputs: % p - probability % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) % % Updated 9/21/11 by DJ - make x a vector, use x(indx) instead of just x %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [p]=bernoull(x,eta) if numel(x)==1 x = repmat(x,size(eta)); end e = exp(eta); p = ones(size(e)); indx = (~isinf(e)); p(indx) = exp(eta(indx).*x(indx) - log(1+e(indx)));
github
djangraw/FelixScripts-master
JitteredLR_GUI.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/JitteredLR_GUI.m
26,769
utf_8
316a0fdded05e8b94a43677296d7978c
function varargout = JitteredLR_GUI(varargin) % JITTEREDLR_GUI M-file for JitteredLR_GUI.fig % JITTEREDLR_GUI, by itself, creates a new JITTEREDLR_GUI or raises the existing % singleton*. % % H = JITTEREDLR_GUI returns the handle to a new JITTEREDLR_GUI or the handle to % the existing singleton*. % % JITTEREDLR_GUI('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in JITTEREDLR_GUI.M with the given input arguments. % % JITTEREDLR_GUI('Property','Value',...) creates a new JITTEREDLR_GUI or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before JitteredLR_GUI_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to JitteredLR_GUI_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help JitteredLR_GUI % Last Modified by GUIDE v2.5 19-Dec-2011 13:33:45 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @JitteredLR_GUI_OpeningFcn, ... 'gui_OutputFcn', @JitteredLR_GUI_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before JitteredLR_GUI is made visible. function JitteredLR_GUI_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to JitteredLR_GUI (see VARARGIN) % Choose default command line output for JitteredLR_GUI handles.output = hObject; % Update handles structure guidata(hObject, handles); % Update copyparams allresults = dir('results*'); set(handles.popup_copyparams,'string',{'Copy Parameters From File...', allresults(:).name}); % UIWAIT makes JitteredLR_GUI wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = JitteredLR_GUI_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on selection change in popup_copyparams. function popup_copyparams_Callback(hObject, eventdata, handles) % hObject handle to popup_copyparams (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns popup_copyparams contents as cell array % contents{get(hObject,'Value')} returns selected item from popup_copyparams contents = cellstr(get(hObject,'String')); foldername = contents{get(hObject,'Value')}; paramsfile = dir([foldername '/params*']); if length(paramsfile)~=1 set(handles.text_status,'string','Error: file not found.') return; end % load parameters file load([foldername '/' paramsfile.name]); % Set Input Settings set(handles.edit_subject,'string',scope_settings.subject); set(handles.edit_saccadetype,'string',scope_settings.saccadeType); set(handles.check_weightprior,'value',pop_settings.weightprior); set(handles.edit_cvmode,'string',scope_settings.cvmode); set(handles.edit_jitterrange,'string',num2str(pop_settings.jitterrange)); % Set scope of analysis set(handles.edit_trainingwindowlength,'string',num2str(scope_settings.trainingwindowlength)); set(handles.edit_trainingwindowinterval,'string',num2str(scope_settings.trainingwindowinterval)); set(handles.edit_trainingwindowrange,'string',num2str(scope_settings.trainingwindowrange)); set(handles.check_parallel,'value',scope_settings.parallel); % Set pop settings set(handles.check_usefirstsaccade,'value',pop_settings.useFirstSaccade); set(handles.check_removebaselineyval,'value',pop_settings.removeBaselineYVal); set(handles.check_forceonewinner,'value',pop_settings.forceOneWinner); set(handles.check_usetwoposteriors,'value',pop_settings.useTwoPosteriors); set(handles.check_conditionprior,'value',pop_settings.conditionPrior); set(handles.check_denoisedata,'value',pop_settings.deNoiseData); set(handles.edit_denoiseremove,'string',num2str(pop_settings.deNoiseRemove)); set(handles.edit_convergencethreshold,'string',num2str(pop_settings.convergencethreshold)); if isfield(pop_settings,'null_sigmamultiplier') set(handles.edit_sigmamultiplier,'string',num2str(pop_settings.null_sigmamultiplier)); else set(handles.edit_sigmamultiplier,'string','1'); end % Set logist settings set(handles.edit_eigvalratio,'string',num2str(logist_settings.eigvalratio)); set(handles.edit_lambda,'string',num2str(logist_settings.lambda)); set(handles.check_lambdasearch,'value',logist_settings.lambdasearch); set(handles.check_regularize,'value',logist_settings.regularize); set(handles.text_status,'string',['Parameters last loaded from ' foldername]) % --- Executes on button press in button_run. function button_run_Callback(hObject, eventdata, handles) % hObject handle to button_run (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Input Settings subject = get(handles.edit_subject,'string'); saccadeType = get(handles.edit_saccadetype,'string'); weightprior = get(handles.check_weightprior,'value'); cvmode = get(handles.edit_cvmode,'string'); jitterrange = str2num(['[' get(handles.edit_jitterrange,'string') ']']); % Load data for given subject [ALLEEG,EEG,setlist,saccadeTimes] = loadSubjectData(subject,saccadeType); % eeg info and saccade info chansubset = 1:ALLEEG(setlist(1)).nbchan; % extract saccade times according to indicated input switch saccadeType case {'start','toObject_start','allToObject_start'} saccadeTimes1 = saccadeTimes.distractor_saccades_start; saccadeTimes2 = saccadeTimes.target_saccades_start; case {'end','toObject_end','allToObject_end'} saccadeTimes1 = saccadeTimes.distractor_saccades_end; saccadeTimes2 = saccadeTimes.target_saccades_end; end % Declare scope of analysis scope_settings.subject = subject; scope_settings.saccadeType = saccadeType; scope_settings.trainingwindowlength = str2double(get(handles.edit_trainingwindowlength,'string')); scope_settings.trainingwindowinterval = str2double(get(handles.edit_trainingwindowinterval,'string')); scope_settings.trainingwindowrange = str2num(get(handles.edit_trainingwindowrange,'string')); scope_settings.parallel = get(handles.check_parallel,'value'); scope_settings.cvmode = cvmode; % Declare parameters of pop_logisticregressions_jittered_EM pop_settings.convergencethreshold = str2double(get(handles.edit_convergencethreshold,'string')); % subspace between spatial weights at which algorithm converges pop_settings.jitterrange = jitterrange; % In samples please! pop_settings.weightprior = weightprior; % re-weight prior according to prevalence of each label pop_settings.useFirstSaccade = get(handles.check_usefirstsaccade,'value'); % 1st iteration prior is first saccade on each trial pop_settings.removeBaselineYVal = get(handles.check_removebaselineyval,'value'); % Subtract average y value before computing posteriors pop_settings.forceOneWinner = get(handles.check_forceonewinner,'value'); % make all posteriors 0 except max (i.e. find 'best saccade' in each trial) pop_settings.useTwoPosteriors = get(handles.check_usetwoposteriors,'value'); % calculate posteriors separately for truth=0,1, use both for Az calculation pop_settings.conditionPrior = get(handles.check_conditionprior,'value'); % calculate likelihood such that large values of y (in either direction) are rewarded pop_settings.deNoiseData = get(handles.check_denoisedata,'value'); % only keep approved components (see pop code for selection) in dataset pop_settings.deNoiseRemove = str2num(get(handles.edit_denoiseremove,'string')); % remove these components pop_settings.null_sigmamultiplier = str2num(get(handles.edit_sigmamultiplier,'string')); % factor to expand "null y" distribution % Declare parameters of logist_weighted logist_settings.eigvalratio = str2double(get(handles.edit_eigvalratio,'string')); logist_settings.lambda = str2double(get(handles.edit_lambda,'string')); logist_settings.lambdasearch = get(handles.check_lambdasearch,'value'); logist_settings.regularize = get(handles.check_regularize,'value'); % Define output directory that encodes info about this run outDirName = ['./results_',subject,'_',saccadeType,'Saccades']; if weightprior == 1 outDirName = [outDirName,'_weightprior']; else outDirName = [outDirName,'_noweightprior']; end outDirName = [outDirName,'_',cvmode]; outDirName = [outDirName,'_jrange_',num2str(pop_settings.jitterrange(1)),'_to_',num2str(pop_settings.jitterrange(2))]; outDirName = [outDirName,'/']; % run algorithm with given data & parameters run_logisticregression_jittered_EM_saccades(outDirName,... ALLEEG,... setlist,... chansubset,... saccadeTimes1,... saccadeTimes2,... scope_settings,... pop_settings,... logist_settings); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%% UNUSED FUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % --- Executes during object creation, after setting all properties. function popup_copyparams_CreateFcn(hObject, eventdata, handles) % hObject handle to popup_copyparams (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_trainingwindowlength_Callback(hObject, eventdata, handles) % hObject handle to edit_trainingwindowlength (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_trainingwindowlength as text % str2double(get(hObject,'String')) returns contents of edit_trainingwindowlength as a double % --- Executes during object creation, after setting all properties. function edit_trainingwindowlength_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_trainingwindowlength (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_trainingwindowinterval_Callback(hObject, eventdata, handles) % hObject handle to edit_trainingwindowinterval (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_trainingwindowinterval as text % str2double(get(hObject,'String')) returns contents of edit_trainingwindowinterval as a double % --- Executes during object creation, after setting all properties. function edit_trainingwindowinterval_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_trainingwindowinterval (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_trainingwindowrange_Callback(hObject, eventdata, handles) % hObject handle to edit_trainingwindowrange (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_trainingwindowrange as text % str2double(get(hObject,'String')) returns contents of edit_trainingwindowrange as a double % --- Executes during object creation, after setting all properties. function edit_trainingwindowrange_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_trainingwindowrange (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in check_parallel. function check_parallel_Callback(hObject, eventdata, handles) % hObject handle to check_parallel (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_parallel function edit_subject_Callback(hObject, eventdata, handles) % hObject handle to edit_subject (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_subject as text % str2double(get(hObject,'String')) returns contents of edit_subject as a double % --- Executes during object creation, after setting all properties. function edit_subject_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_subject (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_saccadetype_Callback(hObject, eventdata, handles) % hObject handle to edit_saccadetype (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_saccadetype as text % str2double(get(hObject,'String')) returns contents of edit_saccadetype as a double % --- Executes during object creation, after setting all properties. function edit_saccadetype_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_saccadetype (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in check_weightprior. function check_weightprior_Callback(hObject, eventdata, handles) % hObject handle to check_weightprior (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_weightprior function edit_cvmode_Callback(hObject, eventdata, handles) % hObject handle to edit_cvmode (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_cvmode as text % str2double(get(hObject,'String')) returns contents of edit_cvmode as a double % --- Executes during object creation, after setting all properties. function edit_cvmode_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_cvmode (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_jitterrange_Callback(hObject, eventdata, handles) % hObject handle to edit_jitterrange (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_jitterrange as text % str2double(get(hObject,'String')) returns contents of edit_jitterrange as a double % --- Executes during object creation, after setting all properties. function edit_jitterrange_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_jitterrange (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_convergencethreshold_Callback(hObject, eventdata, handles) % hObject handle to edit_convergencethreshold (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_convergencethreshold as text % str2double(get(hObject,'String')) returns contents of edit_convergencethreshold as a double % --- Executes during object creation, after setting all properties. function edit_convergencethreshold_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_convergencethreshold (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in check_usefirstsaccade. function check_usefirstsaccade_Callback(hObject, eventdata, handles) % hObject handle to check_usefirstsaccade (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_usefirstsaccade % --- Executes on button press in check_removebaselineyval. function check_removebaselineyval_Callback(hObject, eventdata, handles) % hObject handle to check_removebaselineyval (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_removebaselineyval % --- Executes on button press in check_forceonewinner. function check_forceonewinner_Callback(hObject, eventdata, handles) % hObject handle to check_forceonewinner (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_forceonewinner % --- Executes on button press in check_usetwoposteriors. function check_usetwoposteriors_Callback(hObject, eventdata, handles) % hObject handle to check_usetwoposteriors (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_usetwoposteriors % --- Executes on button press in check_denoisedata. function check_denoisedata_Callback(hObject, eventdata, handles) % hObject handle to check_denoisedata (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_denoisedata function edit_denoiseremove_Callback(hObject, eventdata, handles) % hObject handle to edit_denoiseremove (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_denoiseremove as text % str2double(get(hObject,'String')) returns contents of edit_denoiseremove as a double % --- Executes during object creation, after setting all properties. function edit_denoiseremove_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_denoiseremove (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in check_regularize. function check_regularize_Callback(hObject, eventdata, handles) % hObject handle to check_regularize (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_regularize % --- Executes on button press in check_lambdasearch. function check_lambdasearch_Callback(hObject, eventdata, handles) % hObject handle to check_lambdasearch (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_lambdasearch function edit_lambda_Callback(hObject, eventdata, handles) % hObject handle to edit_lambda (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_lambda as text % str2double(get(hObject,'String')) returns contents of edit_lambda as a double % --- Executes during object creation, after setting all properties. function edit_lambda_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_lambda (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_eigvalratio_Callback(hObject, eventdata, handles) % hObject handle to edit_eigvalratio (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_eigvalratio as text % str2double(get(hObject,'String')) returns contents of edit_eigvalratio as a double % --- Executes during object creation, after setting all properties. function edit_eigvalratio_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_eigvalratio (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in check_conditionprior. function check_conditionprior_Callback(hObject, eventdata, handles) % hObject handle to check_conditionprior (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hint: get(hObject,'Value') returns toggle state of check_conditionprior function edit_sigmamultiplier_Callback(hObject, eventdata, handles) % hObject handle to edit_sigmamultiplier (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_sigmamultiplier as text % str2double(get(hObject,'String')) returns contents of edit_sigmamultiplier as a double % --- Executes during object creation, after setting all properties. function edit_sigmamultiplier_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_sigmamultiplier (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
djangraw/FelixScripts-master
GetFinalPosteriors.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/GetFinalPosteriors.m
8,381
utf_8
df09867dec471f5f87f29d98426a6bb4
function pt = GetFinalPosteriors(subject, weightornoweight, startorend, crossval, suffix) % Put the posterior distributions of jittered logistic regression results % into a cell array. % % pt = GetFinalPosteriors(subject, resultsfile, startorend) % % INPUTS: % -subject is a string indicating the name of the folder containing the % data, up through the subject number (the data folder, the data filenames, % and the results folders must share this string in the formats described % in the code). % -weightornoweight is a string indicating whether priors should be % weighted by the number of trials in each set ('weight' or 'noweight'). % -startorend is a string indicating whether you want the results using the % saccade start time ('start') or the saccade end time ('end') as time t=0. % -crossval is a string indicating the type of cross validation used ('loo' % or 'xxfold', where xx is an integer). % -suffix is a string indicating other information included in the folder % name, such as 'jrange_0_to_500'. % % OUTPUTS: % -pt is a cell array of matrices containing the posterior distributions % over time. Indices of pt are {LOOtrial, time}, indices of pt{i,j} are % [trial, TrainingWindowOffset]. % % Created 6/15/11 by DJ - incomplete. % Updated 6/20/11 by DJ - comments. % Updated 8/31/11 by DJ - new inputs for new filenames % Updated 9/12/11 by DJ - added removeBaselineYVal option % Updated 9/14/11 by DJ - added forceOneWinner option % Updated 9/21/11 by DJ - get options from pop_settings struct in results file % Updated 10/4/11 by DJ - added useSymmetricLikelihood option % Updated 10/7/11 by DJ - debugged, disabled removeBaselineYVal option % load results load(['results_' subject '_' startorend 'Saccades_' weightornoweight 'prior_' crossval '_' suffix '/results_' crossval]); % Azloo, jitterrange, p, testsample, trainingwindowlength, trainingwindowoffset, truth, vout, pop_settings_out if strfind(startorend,'allToObject') saccadeTimes = load(['../Data/' subject '/' subject '-AllSaccadesToObject.mat']); % saccadeTimes.distractor_saccades_start/_end, target_saccades_start/_end elseif strfind(startorend,'toObject') saccadeTimes = load(['../Data/' subject '/' subject '-SaccadeToObject.mat']); % saccadeTimes.distractor_saccades_start/_end, target_saccades_start/_end else saccadeTimes = load(['../Data/' subject '/' subject '-SaccadeTimes.mat']); % saccadeTimes.distractor_saccades_start/_end, target_saccades_start/_end end % load eeglab structs ALLEEG(1) = pop_loadset('filepath',['../Data/',subject],'filename',[subject,'-distractorappear.set'],'loadmode','all'); ALLEEG(2) = pop_loadset('filepath',['../Data/',subject],'filename',[subject,'-targetappear.set'],'loadmode','all'); % convert to variables used by run_ and pop_ so that we can use our copied/pasted code truth_trials = truth; global weightprior; weightprior = strcmp(weightornoweight,'weight'); setlist = [1 2]; chansubset = 1:ALLEEG(1).nbchan; ntrials1 = ALLEEG(setlist(1)).trials; ntrials2 = ALLEEG(setlist(2)).trials; jitterrange = pop_settings_out(1).jitterrange; truth=[zeros((diff(jitterrange)+trainingwindowlength)*ntrials1,1); ... ones((diff(jitterrange)+trainingwindowlength)*ntrials2,1)]; % compute priors if strfind(startorend,'start') saccadeTimes1 = saccadeTimes.distractor_saccades_start; % or use end times saccadeTimes2 = saccadeTimes.target_saccades_start; elseif strfind(startorend,'end') saccadeTimes1 = saccadeTimes.distractor_saccades_end; % or use end times saccadeTimes2 = saccadeTimes.target_saccades_end; else error('startorend must contain ''start'' or ''end''!'); end % Ensure the saccadeTime cell arrays are row vectors if size(saccadeTimes1,1) ~= 1; saccadeTimes1 = saccadeTimes1'; end; if size(saccadeTimes2,1) ~= 1; saccadeTimes2 = saccadeTimes2'; end; saccadeTimes = [saccadeTimes1,saccadeTimes2]; % Set up JitterPrior struct jitterPrior = []; jitterPrior.fn = @computeSaccadeJitterPrior; jitterPrior.params = []; jitterPrior.params.saccadeTimes = saccadeTimes; % Calculate prior ptprior = jitterPrior.fn((1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = ptprior/sum(ptprior); ptprior = repmat(ptprior,ntrials1+ntrials2,1); else % Ensure the rows sum to 1 ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); end % Re-weight priors according to the number of trials in each class if weightprior ptprior(truth_trials==1,:) = ptprior(truth_trials==1,:) / sum(truth_trials==1); ptprior(truth_trials==0,:) = ptprior(truth_trials==0,:) / sum(truth_trials==0); end % Extract data raweeg1 = ALLEEG(setlist(1)).data(chansubset,:,:); raweeg2 = ALLEEG(setlist(2)).data(chansubset,:,:); pt = cell(length(testsample),length(trainingwindowoffset)); % initialize for i=1:length(testsample) fprintf('Sample %d of %d...\n',i,length(testsample)); for j=1:length(trainingwindowoffset) % For each training window v = vout{i}(j,:); % Put de-jittered data into [D x (N*T] matrix for input into logist x = AssembleData(raweeg1,raweeg2,trainingwindowoffset(j),trainingwindowlength,jitterrange); % Get y values y = x*v(1:end-1)' + v(end); % calculate y values given these weights % Remove baseline y-value by de-meaning if pop_settings_out(1).removeBaselineYVal y2 = y - mean(y); null_mu2 = pop_settings_out(1).null_mu-mean(y); else y2 = y; null_mu2 = pop_settings_out(1).null_mu; end % Get posterior pt{i,j} = ComputePosterior(ptprior,y2,truth,trainingwindowlength,... pop_settings_out(1).forceOneWinner,pop_settings_out(1).conditionPrior,null_mu2, pop_settings_out(1).null_sigma); end end disp('Success!') end % function GetFinalPosteriors % FUNCTION AssembleData: % Put de-jittered data into [(N*T) x D] matrix for input into logist function x = AssembleData(data1,data2,thistrainingwindowoffset,trainingwindowlength,jitterrange) % Declare constants iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength-1); x = cat(3,data1(:,iwindow,:),data2(:,iwindow,:)); x = reshape(x,[size(x,1),size(x,3)*length(iwindow)])'; end % function AssembleData % FUNCTION ComputePosterior: % Use the priors, y's and truth values to calculate the posteriors function [posterior,likelihood] = ComputePosterior(prior, y, truth, trainingwindowlength,forceOneWinner,conditionPrior,null_mu,null_sigma) % put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % calculate likelihood yavg = zeros(size(prior)); likelihood = ones(size(prior)); for i=1:size(prior,2) iwindow = (1:trainingwindowlength)+i-1; yavg(:,i) = mean(ymat(:,iwindow),2); likelihood(:,i) = bernoull(truthmat(:,i),yavg(:,i)); end if conditionPrior condprior = (1-normpdf(yavg,null_mu,null_sigma)/normpdf(0,0,null_sigma)).*prior; % prior conditioned on y (p(t|y)) condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % normalize so each trial sums to 1 else condprior = prior; end % calculate posterior posterior = likelihood.*condprior; % end % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row else % normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); end % Re-weight priors according to the number of trials in each class global weightprior; if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior
github
djangraw/FelixScripts-master
setGroupedCrossValidationStruct.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/setGroupedCrossValidationStruct.m
3,714
utf_8
1415746f28b1603cc15af6f600d5464f
% Automatically separates two eeglab datasets into multi-fold trials. % % cv = setGroupedCrossValidationStruct(cvmode,ALLEEG1,ALLEEG2) % % INPUTS: % -cvmode is a string indicating the type of cross-validation to be % performed. The options are 'nocrossval' (1 fold),'loo' (leave one out), % or '<x>fold', where x is a whole number. % -ALLEEG1 and 2 are eeglab datasets whose trials you wish to separate out % into folds. % % OUTPUTS: % -cv is a struct with fields incTrials1/2, outTrials1/2, valTrials1/2, and % numFolds. % % Created 8/27/11 (?) by BC. % Updated 2/6/13 by DJ - comments. %% ****************************************************************************************** function cv = setGroupedCrossValidationStruct(cvmode,ALLEEG1,ALLEEG2) cv = []; cv.mode = cvmode; ntrials1 = ALLEEG1.trials; ntrials2 = ALLEEG2.trials; ntrials = ntrials1 + ntrials2; if strcmp(cvmode,'nocrossval') cv.numFolds = 1; cv.incTrials1 = cell(1);cv.incTrials2 = cell(1); cv.outTrials1 = cell(1);cv.outTrials2 = cell(1); cv.valTrials1 = cell(1);cv.valTrials2 = cell(1); cv.incTrials1{1} = 1:ntrials1; cv.incTrials2{1} = 1:ntrials2; cv.outTrials1{1} = []; cv.outTrials2{1} = []; cv.valTrials1{1} = []; cv.valTrials2{1} = []; elseif strcmp(cvmode,'loo') cv.numFolds = ntrials; cv.incTrials1 = cell(1,cv.numFolds);cv.incTrials2 = cell(1,cv.numFolds); cv.outTrials1 = cell(1,cv.numFolds);cv.outTrials2 = cell(1,cv.numFolds); cv.valTrials1 = cell(1,cv.numFolds);cv.valTrials2 = cell(1,cv.numFolds); for j=1:ntrials if j <= ntrials1 cv.incTrials1{j} = setdiff(1:ntrials1,j); cv.incTrials2{j} = 1:ntrials2; cv.outTrials1{j} = j; cv.outTrials2{j} = []; cv.valTrials1{j} = j; cv.valTrials2{j} = []; else j2 = j - ntrials1; cv.incTrials1{j} = 1:ntrials1; cv.incTrials2{j} = setdiff(1:ntrials2,j2); cv.outTrials1{j} = []; cv.outTrials2{j} = j2; cv.valTrials1{j} = []; cv.valTrials2{j} = j2; end end elseif strcmp(cvmode((end-3):end),'fold') cv.numFolds = str2num(cvmode(1:(end-4))); cv.incTrials1 = cell(1,cv.numFolds);cv.incTrials2 = cell(1,cv.numFolds); cv.outTrials2 = cell(1,cv.numFolds);cv.outTrials2 = cell(1,cv.numFolds); cv.valTrials1 = cell(1,cv.numFolds);cv.valTrials2 = cell(1,cv.numFolds); % Split the data into roughly equally-sized folds foldSizes = floor(ntrials/cv.numFolds)*ones(1,cv.numFolds); foldSizes(1:(ntrials-foldSizes(1)*cv.numFolds)) = foldSizes(1)+1; % We are now going to sort the trials based on urevent id epochID1 = zeros(1,ntrials1); epochID2 = zeros(1,ntrials2); for j=1:ntrials1; epochID1(j) = ALLEEG1.epoch(j).eventurevent{1}; end; for j=1:ntrials2; epochID2(j) = ALLEEG2.epoch(j).eventurevent{2}; end; [~,epochOrdering] = sort([epochID1,epochID2],'ascend'); epochGrouping = ones(1,ntrials); locs = find(epochOrdering > ntrials1); epochGrouping(locs) = 2; epochOrdering(locs) = epochOrdering(locs) - ntrials1; eInd = 0; for j=1:cv.numFolds sInd = eInd + 1; eInd = sInd + foldSizes(j) - 1; sset = sInd:eInd; locs1 = find(epochGrouping(sset) == 1); locs2 = find(epochGrouping(sset) == 2); cv.outTrials1{j} = epochOrdering(sset(locs1));cv.valTrials1{j} = cv.outTrials1{j}; cv.outTrials2{j} = epochOrdering(sset(locs2));cv.valTrials2{j} = cv.outTrials2{j}; cv.incTrials1{j} = setdiff(1:ntrials1,cv.outTrials1{j}); cv.incTrials2{j} = setdiff(1:ntrials2,cv.outTrials2{j}); end else error('Unknown cross-validation mode'); end end %% ************************************************************************ %% ******************
github
djangraw/FelixScripts-master
run_logisticregression_jittered_EM_saccades.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/SaccadeBased/run_logisticregression_jittered_EM_saccades.m
12,766
utf_8
7b99b4b1e502dada507aeab1ae59be57
function run_logisticregression_jittered_EM_saccades(outDirName,ALLEEG,setlist, chansubset, saccadeTimes1, saccadeTimes2, scope_settings, pop_settings, logist_settings) % Perform logistic regression with trial jitter on a dataset. % % % [ALLEEG,v,Azloo,time] = run_logisticregression_jittered_EM_saccades(outDirName,ALLEEG, % setlist,chansubset,trainingwindowlength,trainingwindowinterval,jitterrange, % saccadeTimes1,saccadeTimes2,convergencethreshold,cvmode,weightprior) % % INPUTS: % -outDirName: a string specifying where results are to be saved (DEFAULT: './results/') % -ALLEEG is an array of EEGlab data structures % -setlist is a 2-element vector of the ALLEEG indices you wish to discriminate % -chansubset is a d-element array of the channel numbers you wish to use for discrimination % (DEFAULT: [] -- use all channels) % -trainingwindowlength is the number of samples that are in the training window % -trainingwindowinterval is the number of samples by which you want to slide your training window each time % -jitterrange specifies the minimum and maximum % -saccadeTimes1 and saccadeTimes2 are % -convergencethreshold % -cvmode is a string specifying what type of cross-validation to run. Can be: % 'nocrossval' - run full model (no cross-validation) % 'loo' - run leave-one-out cross-validation % 'XXfold', where XX is an integer, will run XX-fold cross-validation % (DEFAULT: '10fold') % -weightprior is a boolean % % % OUTPUTS: % -ALLEEG is the input array, but with info about the analysis stored in % the ica-related fields of the datasets in setlist. Specifically, % EEG.icawinv contains the forward model across all datasets. % EEG.icaweights contains the weight vector v (with no bias term). % -v is the weight vector from the training data (the first d are spatial % weights, and the last element is the bias.) Negative values of % y=x*v(1:end-1) + v(end) indicate that the sample is part of setlist(1)'s % class. Positive values indicate setlist(2)'s class. % -Azloo and time are vectors of the leave-one-out Az values and the center % of the time bin (in ms from setlist(1)'s time zero) at which they were % calculated. % % Created 5/12/11 by BC. % Updated 8/3/11 by BC - include x-fold cross-validation % Updated 9/14/11 by DJ - made sure fwd models are saved % Updated 9/20/11 by DJ - pass pop_settings struct to test function % Updated 9/21/11 by DJ - switched to settings structs % Updated 10/26/11 by DJ - fixed jitterprior bug % Updated 12/13/11 by DJ - made plotting optional %% ****************************************************************************************** %% Set up % if ~exist('outDirName','var') || isempty(outDirName); outDirName = './results/'; end; % if ~exist('setlist','var'); setlist = [1,2]; end; % if ~exist('chansubset','var'); chansubset = []; end; % if ~exist('trainingwindowlength','var'); trainingwindowlength = []; end; % if ~exist('trainingwindowinterval','var'); trainingwindowinterval = []; end; % if ~exist('jitterrange','var'); jitterrange = []; end; % if ~exist('convergencethreshold','var'); convergencethreshold = []; end; % if ~exist('cvmode','var'); cvmode = '10fold'; end; % if ~exist('weightprior','var'); weightprior = 1; end; UnpackStruct(scope_settings); % jitterrange, trainingwindowlength/interval/range, parallel, cvmode, convergencethreshold % There may be other loaded EEG datasets, so let's save some memory and only keep the ones we need ALLEEG = ALLEEG(setlist); setlist = [1 2]; % Start -500ms and end +500ms relative to stimulus onset loc1 = find(ALLEEG(setlist(1)).times <= trainingwindowrange(1), 1, 'last' ); loc2 = find(ALLEEG(setlist(1)).times >= trainingwindowrange(2), 1 ); loc1 = loc1 - floor(trainingwindowlength/2); loc2 = loc2 - floor(trainingwindowlength/2); trainingwindowoffset = loc1 : trainingwindowinterval : loc2; %1-jitterrange(1) : trainingwindowinterval : ALLEEG(1).pnts-trainingwindowlength-jitterrange(2); % trainingwindowoffset = 245;%190;%264; iMidTimes = trainingwindowoffset + floor(trainingwindowlength/2); % middle of time window time = ALLEEG(setlist(1)).times(iMidTimes)*0.001; % crop and convert to seconds % Ensure the saccadeTime cell arrays are row vectors if size(saccadeTimes1,1) ~= 1; saccadeTimes1 = saccadeTimes1'; end; if size(saccadeTimes2,1) ~= 1; saccadeTimes2 = saccadeTimes2'; end; saccadeTimes = [saccadeTimes1,saccadeTimes2]; % Set parameters % % regularize = 1; % % lambda = 1e-6; % % lambdasearch = false; % % eigvalratio = 1e-4; % show = 0; % parallel = 0; vinit = zeros(length(chansubset)+1,1); % Set up prior struct jitterPrior = []; jitterPrior.fn = @computeSaccadeJitterPrior; jitterPrior.params = []; jitterPrior.params.saccadeTimes = saccadeTimes; % Save parameters if ~isdir(outDirName); mkdir(outDirName); end; tic; N1 = ALLEEG(setlist(1)).trials; N2 = ALLEEG(setlist(2)).trials; N = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; cv = setGroupedCrossValidationStruct(cvmode,ALLEEG(setlist(1)),ALLEEG(setlist(2))); save([outDirName,'/params_',cvmode,'.mat'], 'ALLEEG','setlist','cv','chansubset','trainingwindowoffset','saccadeTimes1', 'saccadeTimes2', 'scope_settings','pop_settings','logist_settings'); % save([outDirName,'/params_',cvmode,'.mat'], 'ALLEEG','setlist','cv','chansubset','trainingwindowlength', 'trainingwindowinterval', 'jitterrange', 'saccadeTimes1', 'saccadeTimes2', 'convergencethreshold', 'cvmode','weightprior'); poolsize = min(15,cv.numFolds); % 15 for einstein, 4 for local if poolsize == 1; parallel = 0; end; if parallel == 1 warning('Make sure you run pctconfig(''hostname'', ''ip'')'); mls = matlabpool('size'); if mls > 0; matlabpool close; end; matlabpool('open',poolsize); % declare some variables trainingwindowlength = trainingwindowlength; end ps = cell(cv.numFolds,1); vout = cell(cv.numFolds,1); testsample = cell(cv.numFolds,1); jitterPriorLoop = cell(cv.numFolds,1); for j=1:cv.numFolds; jitterPriorLoop{j} = jitterPrior; end; jitterPriorTest = cell(cv.numFolds,1); for j=1:cv.numFolds; jitterPriorTest{j} = jitterPrior; end; fwdmodels = cell(cv.numFolds,1); foldALLEEG = cell(cv.numFolds,1); pop_settings_out = cell(cv.numFolds,1); if parallel == 1 parfor foldNum = 1:cv.numFolds % PARFOR! disp(['Running fold #',num2str(foldNum),' out of ',num2str(cv.numFolds)]);pause(1e-9); foldALLEEG{foldNum}(1) = ALLEEG(setlist(1)); foldALLEEG{foldNum}(2) = ALLEEG(setlist(2)); foldALLEEG{foldNum}(1).data = foldALLEEG{foldNum}(1).data(:,:,cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).epoch = foldALLEEG{foldNum}(1).epoch(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).trials = length(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(2).data = foldALLEEG{foldNum}(2).data(:,:,cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).epoch = foldALLEEG{foldNum}(2).epoch(cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).trials = length(cv.incTrials2{foldNum}); jitterPriorLoop{foldNum}.params.saccadeTimes = [saccadeTimes1(cv.incTrials1{foldNum}),saccadeTimes2(cv.incTrials2{foldNum})]; jitterPriorTest{foldNum}.params.saccadeTimes = [saccadeTimes1(cv.valTrials1{foldNum}),saccadeTimes2(cv.valTrials2{foldNum})]; testsample{foldNum} = cat(3,ALLEEG(setlist(1)).data(:,:,cv.valTrials1{foldNum}), ALLEEG(setlist(2)).data(:,:,cv.valTrials2{foldNum})); [ALLEEGout,~,vout{foldNum}] = pop_logisticregression_jittered_EM(foldALLEEG{foldNum},[1 2],chansubset,trainingwindowlength,trainingwindowoffset,vinit,jitterPriorLoop{foldNum},pop_settings,logist_settings); fwdmodels{foldNum} = ALLEEGout(setlist(1)).icawinv; ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); for k=1:size(testsample{foldNum},3) if k > length(cv.valTrials1{foldNum}) jitterPriorTest{foldNum}.params.saccadeTimes = saccadeTimes2(cv.valTrials2{foldNum}(k-length(cv.valTrials1{foldNum}))); else jitterPriorTest{foldNum}.params.saccadeTimes = saccadeTimes1(cv.valTrials1{foldNum}(k)); end ps{foldNum}(k,:) = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate,ALLEEGout(setlist(1)).etc.pop_settings); end pop_settings_out{foldNum} = ALLEEGout(setlist(1)).etc.pop_settings; % ps{foldNum} = runTest(testsample{foldNum},trainingwindowlength,trainingwindowoffset,jitterrange,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate); end else for foldNum = 1:cv.numFolds disp(['Running fold #',num2str(foldNum),' out of ',num2str(cv.numFolds)]);pause(1e-9); foldALLEEG{foldNum}(1) = ALLEEG(setlist(1)); foldALLEEG{foldNum}(2) = ALLEEG(setlist(2)); foldALLEEG{foldNum}(1).data = foldALLEEG{foldNum}(1).data(:,:,cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).epoch = foldALLEEG{foldNum}(1).epoch(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).trials = length(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(2).data = foldALLEEG{foldNum}(2).data(:,:,cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).epoch = foldALLEEG{foldNum}(2).epoch(cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).trials = length(cv.incTrials2{foldNum}); jitterPriorLoop{foldNum}.params.saccadeTimes = [saccadeTimes1(cv.incTrials1{foldNum}),saccadeTimes2(cv.incTrials2{foldNum})]; testsample{foldNum} = cat(3,ALLEEG(setlist(1)).data(:,:,cv.valTrials1{foldNum}), ALLEEG(setlist(2)).data(:,:,cv.valTrials2{foldNum})); [ALLEEGout,~,vout{foldNum}] = pop_logisticregression_jittered_EM(foldALLEEG{foldNum},[1 2],chansubset,trainingwindowlength,trainingwindowoffset,vinit,jitterPriorLoop{foldNum},pop_settings,logist_settings); fwdmodels{foldNum} = ALLEEGout(setlist(1)).icawinv; ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); for k=1:size(testsample{foldNum},3) if k > length(cv.valTrials1{foldNum}) jitterPriorTest{foldNum}.params.saccadeTimes = saccadeTimes2(cv.valTrials2{foldNum}(k-length(cv.valTrials1{foldNum}))); else jitterPriorTest{foldNum}.params.saccadeTimes = saccadeTimes1(cv.valTrials1{foldNum}(k)); end ps{foldNum}(k,:) = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate,ALLEEGout(setlist(1)).etc.pop_settings); end % ps{foldNum} = runTest(testsample{foldNum},trainingwindowlength,trainingwindowoffset,jitterrange,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate); pop_settings_out{foldNum} = ALLEEGout(setlist(1)).etc.pop_settings; end end pop_settings_out = [pop_settings_out{:}]'; % convert from cells to struct array p = zeros(N,length(trainingwindowoffset)); for foldNum=1:cv.numFolds p([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:) = ps{foldNum}; end truth = [zeros(ALLEEG(setlist(1)).trials,1);ones(ALLEEG(setlist(2)).trials,1)]; for wini = 1:length(trainingwindowoffset) [Azloo(wini),Ryloo,Rxloo] = rocarea(p(:,wini),truth); fprintf('Window Onset: %d; LOO Az: %6.2f\n',trainingwindowoffset(wini),Azloo(wini)); end t = toc; %fwdmodel = ALLEEG(setlist(1)).icawinv; % forward model, defined in pop_logisticregression as a=y\x. if ~isdir(outDirName); mkdir(outDirName); end; save([outDirName,'/results_',cvmode,'.mat'],'vout','testsample','trainingwindowlength','truth','trainingwindowoffset','p','Azloo','t','fwdmodels','jitterPriorTest','pop_settings_out'); %% Plot LOO Results plotAz = 0; if plotAz figure; hold on; plot(time,Azloo); plot(get(gca,'XLim'),[0.5 0.5],'k--'); plot(get(gca,'XLim'),[0.75 0.75],'k:'); ylim([0.3 1]); title('Cross-validation analysis'); xlabel('time (s)'); ylabel([cvmode ' Az']); end mls = matlabpool('size'); if mls > 0; matlabpool close; end; end %% ****************************************************************************************** %% ****************************************************************************************** function p = runTest(testsample,trainingwindowlength,trainingwindowoffset,vout,jitterPrior,srate,pop_settings) p = zeros(1,length(trainingwindowoffset)); for wini = 1:length(trainingwindowoffset) p(wini) = test_logisticregression_jittered_EM(testsample,trainingwindowlength,trainingwindowoffset(wini),vout(wini,:),jitterPrior,srate,pop_settings); % p(wini)=bernoull(1,y(wini)); end end %% ******************************************************************************************
github
djangraw/FelixScripts-master
eegplugin_lr.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/eegplugin_lr.m
1,962
utf_8
603ec4783c4b9ad94543edcd2d4c2f76
% eegplugin_lr() - Logistic Regression plugin % % Usage: % >> eegplugin_lr(fig, trystrs, catchstrs); % % Inputs: % fig - [integer] eeglab figure. % trystrs - [struct] "try" strings for menu callbacks. % catchstrs - [struct] "catch" strings for menu callbacks. % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function vers = eegplugin_lr(fig, try_strings, catch_strings); vers='lr1.2'; if nargin < 3 error('eegplugin_lr requires 3 arguments'); end; % add lr folder to path % ----------------------- if ~exist('pop_logisticregression') p = which('eegplugin_lr'); p = p(1:findstr(p,'eegplugin_lr.m')-1); addpath([ p vers ] ); end; % create menu menu = findobj(fig, 'tag', 'tools'); % menu callback commands % ---------------------- cmd = [ '[ALLEEG]=pop_logisticregression(ALLEEG); EEG=ALLEEG(CURRENTSET); eeglab(''redraw''); ' ]; % add new submenu uimenu( menu, 'label', 'Run Logistic Regression', 'callback', cmd);
github
djangraw/FelixScripts-master
pop_logisticregression_fast.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/pop_logisticregression_fast.m
12,958
utf_8
e956b7f27c65b85e6cd62272eff529df
% pop_logisticregression() - Determine linear discriminating vector between two datasets. % using logistic regression. % % Usage: % >> pop_logisticregression_fast( ALLEEG, datasetlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show, LOO, bootstrap); % % Inputs: % ALLEEG - array of datasets % datasetlist - list of datasets % chansubset - vector of channel subset for dataset 1 [1:min(Dset1,Dset2)] % chansubset2 - vector of channel subset for dataset 2 [chansubset] % trainingwindowlength - Length of training window in samples [all] % trainingwindowoffset - Offset(s) of training window(s) in samples [1] % regularize - regularize [1|0] -> [yes|no] [0] % lambda - regularization constant for weight decay. [1e-6] % Makes logistic regression into a support % vector machine for large lambda % (cf. Clay Spence) % lambdasearch - [1|0] -> search for optimal regularization % constant lambda % eigvalratio - if the data does not fill D-dimensional % space, i.e. rank(x)<D, you should specify % a minimum eigenvalue ratio relative to the % largest eigenvalue of the SVD. All dimensions % with smaller eigenvalues will be eliminated % prior to the discrimination. % vinit - initialization for faster convergence [zeros(D+1,1)] % show - display discrimination boundary during training [0] % LOO - run leave-one-out analysis [0] % bootstrap - run bootstrapping to compute significance Az levels [0] % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Adam Gerson % and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5/21/2005, Fixed bug in leave one out script, Adam function [ALLEEG, eegTimes, Az_loo, Az_perm_dist, com] = pop_logisticregression_fast(ALLEEG, setlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show,LOO,bootstrap); showaz=1; com = ''; if nargin < 1 help pop_logisticregression; return; end; if isempty(ALLEEG) error('pop_logisticregression(): cannot process empty sets of data'); end; if nargin < 2 % which set to save % ----------------- uilist = { { 'style' 'text' 'string' 'Enter two datasets to compare (ex: 1 3):' } ... { 'style' 'edit' 'string' [ '1 2' ] } ... { 'style' 'text' 'string' 'Enter channel subset ([] = all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Enter channel subset for dataset 2 ([] = same as dataset 1):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Training Window Length (samples [] = all):' } ... { 'style' 'edit' 'string' '50' } ... { 'style' 'text' 'string' 'Training Window Offset (samples, 1 = epoch start):' } ... { 'style' 'edit' 'string' '1' } ... { 'style' 'text' 'string' 'Regularize' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Regularization constant for weight decay' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Search for optimal regularization constant' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Eigenvalue ratio for subspace reduction' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Initial discrimination vector [channels+1 x 1] for faster convergence (optional)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Display discrimination boundary' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Leave One Out' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} }; result = inputgui( { [2 .5] [2 .5] [2 .5] [2 .5] [2 .5] [3.1 .4 .15] [2 .5] [3.1 .4 .15] [2 .5] [2 .5] [3.1 .4 .15] [3.1 .4 .15] }, ... uilist, 'pophelp(''pop_logisticregression'')', ... 'Logistic Regression -- pop_logisticregression()'); if length(result) == 0 return; end; setlist = eval( [ '[' result{1} ']' ] ); chansubset = eval( [ '[' result{2} ']' ] ); if isempty( chansubset ), chansubset = 1:min(ALLEEG(setlist(1)).nbchan,ALLEEG(setlist(2)).nbchan); end; chansubset2 = eval( [ '[' result{3} ']' ] ); if isempty(chansubset2), chansubset2=chansubset; end trainingwindowlength = str2num(result{4}); if isempty(trainingwindowlength) trainingwindowlength = ALLEEG(setlist(1)).pnts; end; trainingwindowoffset = str2num(result{5}); if isempty(trainingwindowoffset) trainingwindowoffset = 1; end; regularize=result{6}; if isempty(regularize), regularize=0; end lambda=str2num(result{7}); if isempty(lambda), lambda=1e-6; end lambdasearch=result{8}; if isempty(lambdasearch), lambdasearch=0; end eigvalratio=str2num(result{9}); if isempty(eigvalratio), eigvalratio=1e-6; end vinit=eval([ '[' result{10} ']' ]); if isempty(vinit), vinit=zeros(length(chansubset)+1,1); end vinit=vinit(:); % Column vector show=result{11}; if isempty(show), show=0; end LOO=result{12}; if isempty(LOO), LOO=0; end bootstrap=result{13}; if isempty(bootstrap) bootstrap=0; end end; truth=[zeros(trainingwindowlength.*ALLEEG(setlist(1)).trials,1); ones(trainingwindowlength.*ALLEEG(setlist(2)).trials,1)]; truthmean=([zeros(ALLEEG(setlist(1)).trials,1); ones(ALLEEG(setlist(2)).trials,1)]); N=ALLEEG(setlist(1)).trials+ALLEEG(setlist(2)).trials; if LOO == 0 bootstrap = 0; else if bootstrap == 1; logistMode = 'loo_and_bootstrap'; else; logistMode = 'loo'; end Az_loo = zeros(length(trainingwindowoffset),1); cv = []; cv.numFolds = N; cv.outTrials = cell(1,N); for n=1:N cv.outTrials{n} = (n-1)*trainingwindowlength+1:n*trainingwindowlength; end end try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(1)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 1'); end if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(2)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 2'); end if (length(chansubset)~=length(chansubset2)), error('Number of channels from each dataset must be equal.'); end nperms = 250; truth_perms = zeros(trainingwindowlength*N,nperms); for n=1:nperms truth_perms(:,n) = reshape(repmat(assertVec(truthmean(randperm(N)),'row'),trainingwindowlength,1),N*trainingwindowlength,1); end ALLEEG(setlist(1)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan); % In case a subset of channels are used, assign unused electrodes in scalp projection to NaN ALLEEG(setlist(1)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan)'; ALLEEG(setlist(2)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan)'; ALLEEG(setlist(1)).icasphere=eye(ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icasphere=eye(ALLEEG(setlist(2)).nbchan); timesArr = ALLEEG(setlist(1)).times; eegTimes = zeros(length(trainingwindowoffset),1); Az_perm_dist = cell(length(trainingwindowoffset),1); for i=1:length(trainingwindowoffset), x=cat(3,ALLEEG(setlist(1)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:), ... ALLEEG(setlist(2)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:)); eegTimes(i) = mean(timesArr(trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1)); x=x(:,:)'; % Rearrange data for logist.m [D x trials)]' %v=logist(x,truth)'; v = logist(x,truth,vinit,show,regularize,lambda,lambdasearch,eigvalratio); y = x*v(1:end-1) + v(end); bp = bernoull(1,y); [Az,Ry,Rx] = rocarea(bp,truth); if showaz, fprintf('Window Onset: %d; Az: %6.2f\n',trainingwindowoffset(i),Az); end a = (y-mean(y)) \ x; ALLEEG(setlist(1)).icaweights(i,chansubset)=v(1:end-1)'; ALLEEG(setlist(2)).icaweights(i,chansubset2)=v(1:end-1)'; ALLEEG(setlist(1)).icawinv(chansubset,i)=a'; % consider replacing with asetlist1 ALLEEG(setlist(2)).icawinv(chansubset2,i)=a'; % consider replacing with asetlist2 if LOO % LOO [ws_loo,ys_loo,Az_loo(i),Az_perm_dist{i}] = logist_fast(x',truth,lambda,logistMode,cv,truth_perms);%_and_bootstrap disp(['Az LOO: ',num2str(Az_loo(i))]); figure(102);plot(eegTimes(1:i),Az_loo(1:i)); pause(1e-9); end if 0 ALLEEG(setlist(1)).lrweights(i,:)=v; ALLEEG(setlist(1)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(2)).lrweights(i,:)=v; ALLEEG(setlist(2)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(1)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(1)).data(:,:); ones(1,ALLEEG(setlist(1)).pnts.*ALLEEG(setlist(1)).trials)], ... ALLEEG(setlist(1)).pnts,ALLEEG(setlist(1)).trials),-1); ALLEEG(setlist(2)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(2)).data(:,:); ones(1,ALLEEG(setlist(2)).pnts.*ALLEEG(setlist(2)).trials)], ... ALLEEG(setlist(2)).pnts,ALLEEG(setlist(2)).trials),-1); end end; if LOO figure(102); plot(eegTimes,Az_loo); end if 0 ALLEEG(setlist(1)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(1)).lrtrainoffset=trainingwindowoffset; ALLEEG(setlist(2)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(2)).lrtrainoffset=trainingwindowoffset; end % save channel names % ------------------ %plottopo( tracing, ALLEEG(setlist(1)).chanlocs, ALLEEG(setlist(1)).pnts, [ALLEEG(setlist(1)).xmin ALLEEG(setlist(1)).xmax 0 0]*1000, plottitle, chansubset ); % recompute activations (temporal sources) and check dataset integrity eeg_options; for i=1:2, if option_computeica ALLEEG(setlist(i)).icaact = (ALLEEG(setlist(i)).icaweights*ALLEEG(setlist(i)).icasphere)*reshape(ALLEEG(setlist(i)).data, ALLEEG(setlist(i)).nbchan, ALLEEG(setlist(i)).trials*ALLEEG(setlist(i)).pnts); ALLEEG(setlist(i)).icaact = reshape( ALLEEG(setlist(i)).icaact, size(ALLEEG(setlist(i)).icaact,1), ALLEEG(setlist(i)).pnts, ALLEEG(setlist(i)).trials); end; end for i=1:2, [ALLEEG]=eeg_store(ALLEEG,ALLEEG(setlist(i)),setlist(i)); end com = sprintf('pop_logisticregression( %s, [%s], [%s], [%s], [%s]);', inputname(1), num2str(setlist), num2str(chansubset), num2str(trainingwindowlength), num2str(trainingwindowoffset)); fprintf('Done.\n'); return;
github
djangraw/FelixScripts-master
rocarea.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/rocarea.m
2,126
utf_8
2be03622d12ae6f9025efde8ba6014d6
% rocarea() - computes the area under the ROC curve % If no output arguments are specified % it will display an ROC curve with the % Az and approximate fraction correct. % % Usage: % >> [Az,tp,fp,fc]=rocarea(p,label); % % Inputs: % p - classification output % label - truth labels {0,1} % % Outputs: % Az - Area under ROC curve % tp - true positive rate % fp - false positive rate % fc - fraction correct % % Authors: Lucas Parra ([email protected], 2004) % with Adam Gerson (reformatted for EEGLAB) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Lucas Parra % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [Az,tp,fp,fc]=rocarea(p,label); [tmp,indx]=sort(-p); label = label>0; Np=sum(label==1); Nn=sum(label==0); tp=0; pinc=1/Np; fp=0; finc=1/Nn; Az=0; N=Np+Nn; tp=zeros(N+1,1); fp=zeros(N+1,1); for i=1:N tp(i+1)=tp(i)+label(indx(i))/Np; fp(i+1)=fp(i)+(~label(indx(i)))/Nn; Az = Az + (~label(indx(i)))*tp(i+1)/Nn; end; [m,i]=min(fp-tp); fc = 1-mean([fp(i), 1-tp(i)]); if nargout==0 plot(fp,tp); axis([0 1 0 1]); hold on plot([0 1],[1 0],':'); hold off xlabel('false positive rate') ylabel('true positive rate') title('ROC Curve'); axis([0 1 0 1]); text(0.4,0.2,sprintf('Az = %.2f',Az)) text(0.4,0.1,sprintf('fc = %.2f',fc)) axis square end
github
djangraw/FelixScripts-master
logist_fast.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/logist_fast.m
23,146
utf_8
d816cebd3b3559f21409e7617ef050f7
function [ws_loo,ys_loo,Az_loo,Az_perm_dist] = logist_fast(X,y,l2_lambda,mode,varargin) % X is the feature data (matrix size DxN -- D = # features, N = # trials) % y are the binary truth labels (vector size Nx1) % l2_lambda is the l2 regularization value (e.g., 1e-6) % mode can be either 'loo' or 'permutation' X = double(X); y = double(y); l2_lambda = double(l2_lambda); conv_tol = 1e-11; looMode = 'average'; % Add all one's feature -- to estimate the bias [D,N] = size(X); X = [X;ones(1,N)]; D = D+1; debug = 0; chunkSize = 5000; % Can increase this number if it doesn't crash! numBatches = 1; if strcmp(mode,'loo') if isempty(varargin) cv = []; cv.numFolds = N; cv.outTrials = cell(1,cv.numFolds); for p=1:cv.numFolds cv.outTrials{p} = p; end else cv = varargin{1}; end yperms = assertVec(y,'col'); elseif strcmp(mode,'loo_and_bootstrap') cv = varargin{1}; yperms = [assertVec(y,'col'),varargin{2}]; else error('Unknown mode'); end numperms = size(yperms,2); % Make chunkSize the next closest multiple of cv.numFolds chunkSize = cv.numFolds*round(chunkSize/cv.numFolds); P = cv.numFolds*numperms; if P > chunkSize numBatches = ceil(P/chunkSize); P = chunkSize; disp(['There are too many permutations to run in one batch. This analysis will be run in ',num2str(numBatches), ' batches.']);pause(1e-9); end [y,zeroOutInds,perms] = getCurrentYAndZeroInds(1,yperms,cv,chunkSize); ws_loo = zeros(D,cv.numFolds); if strcmp(looMode,'average') ys_loo = zeros(cv.numFolds,1); else ys_loo = zeros(N,1); end Az_perm_dist = zeros(numperms-1,1); % Set the regularization matrix L % Set the last diagonal element to zero to not penalize the bias L = diag([ones(D-1,1);0]); [Q,Z] = qr(X,0); if size(Q,2) < D % Then we're better off using a low-rank representation for X % Now we need to find a basis for components y for which L*y is in the % range of U. Also the component y must be orthogonal to U (U'*y=0) [Qperp,~] = qr(L'*Q,0); Qperp = (eye(size(Q,1))-Q*Q')*Qperp; [Qtmp,~] = qr([Q,Qperp],0); Q = Qtmp(:,1:size(Q,2)); Qperp = Qtmp(:,(size(Q,2)+1):end); B = Q'*L*Qperp; D = Qperp'*L*Qperp; DinvBT = D\(B'); % DinvBT = D^(-1)*B'; additiveMatrixFactor = 2*l2_lambda*(Q'*L*Q - B*DinvBT); D = size(Q,2); finalInvertMat = Q - Qperp*DinvBT; error('Didn''t reset Z here!'); else additiveMatrixFactor = 2*l2_lambda*L; finalInvertMat = eye(D); Z = X; end XT = X'; innerLoopMode = 'singleMat';'useG'; if strcmp(innerLoopMode,'useG') G = cell(1,P); for p=1:P G{p} = zeros(D,D); end end ws = zeros(D,P); % Pre-allocate some of the big matrices ws_last = zeros(D,P); wsprev = ws; onesMat = ones(N,P); RTREP = zeros(N,P); RTMAT = sparse(N,N); RT_minus_R = zeros(N,P); yvals = zeros(N,P); mus = zeros(N,P); R = zeros(N,P); Minv_ls = zeros(D,P); % OK now let's get started with the iterations iter = 0; locsNotFullyConverged = 1:P; batchNum = 1; while 1 iter = iter + 1; disp(['Working on batch #',num2str(batchNum),' out of ',num2str(numBatches),'; Iteration #',num2str(iter),'...']);pause(1e-9); ws_last(:,:) = ws; yvals(:,locsNotFullyConverged) = XT*ws(:,locsNotFullyConverged); mus(:,locsNotFullyConverged) = 1./(1+exp(-yvals(:,locsNotFullyConverged))); R(:,locsNotFullyConverged) = mus(:,locsNotFullyConverged).*(1-mus(:,locsNotFullyConverged)); R(zeroOutInds) = 0; RT = max(R(:,locsNotFullyConverged),[],2);%%median(R(:,locsNotFullyConverged),2); if max(RT) == 0 break; end neg_ls_without_X(:,locsNotFullyConverged) = (R(:,locsNotFullyConverged).*yvals(:,locsNotFullyConverged) + y(:,locsNotFullyConverged) - mus(:,locsNotFullyConverged)); neg_ls_without_X(zeroOutInds) = 0; % neg_ls = X*neg_ls_without_X; RTMAT = spdiags(RT,0,RTMAT); M = X*(RTMAT*XT) + additiveMatrixFactor; MinvX = M\X; if strncmp(lastwarn,'Matrix is close to singular or badly scaled.',44) warning('Bad conditioning. Suggest reducing subspace.') singularwarning=1; break; end % Iteration is the following: % ws = Minv*N*wsprev + Minv*neg_ls Minv_ls(:,locsNotFullyConverged) = MinvX*neg_ls_without_X(:,locsNotFullyConverged); RTREP(:,locsNotFullyConverged) = RTMAT*onesMat(:,locsNotFullyConverged); % RTREP = repmat(RT,1,length(locsNotFullyConverged)); RT_minus_R(:,locsNotFullyConverged) = RTREP(:,locsNotFullyConverged) - R(:,locsNotFullyConverged); performLowRankUpdates = 0; ratio_thresh = 0.5; maxRank = 1;%round(0.05*D); hasLowRankCorrections = zeros(1,P); lowRankLocs = cell(1,P); lowRankCorrectionMatsLeft = cell(1,P); lowRankCorrectionMatsRight = cell(1,P); lowRankCorrectionSizes = zeros(1,P); if performLowRankUpdates == 1 RT_ratio = zeros(N,P); RT_ratio(:,locsNotFullyConverged) = abs(RT_minus_R(:,locsNotFullyConverged))./RTREP(:,locsNotFullyConverged); RT_ratio(zeroOutInds) = 0;disp('Zeroing out RT_ratio(zeroOutInds) for now. May not want to do this in the future to speed up the algorithm.');pause(1e-9); colinds = max(RT_ratio(:,locsNotFullyConverged)) > ratio_thresh; lowRankColIndsUnique = locsNotFullyConverged(colinds); avgLowRankNum = 0; if ~isempty(lowRankColIndsUnique) XTMinvX = XT*MinvX; for p=lowRankColIndsUnique lowRankLocs{p} = find(RT_ratio(:,p) > ratio_thresh); if isempty(lowRankLocs{p}); continue; end; if length(lowRankLocs{p}) > maxRank % Then make sure that we get everywhere that RT_ratio == 1 numToKeep = max(maxRank,length(find(RT_ratio(lowRankLocs{p},p) == 1))); [~,inds] = sort(RT_ratio(lowRankLocs{p},p),'descend'); lowRankLocs{p} = lowRankLocs{p}(inds(1:numToKeep)); end lowRankCorrectionSizes(p) = length(lowRankLocs{p}); avgLowRankNum = avgLowRankNum + length(lowRankCorrectionSizes(p)); hasLowRankCorrections(p) = 1; lowRankCorrectionMatsLeft{p} = MinvX(:,lowRankLocs{p}); lowRankCorrectionMatsRight{p} = (diag(1./RT_minus_R(lowRankLocs{p},p)) - XTMinvX(lowRankLocs{p},lowRankLocs{p}))\XT(lowRankLocs{p},:);%XT(lowRankLocs{p},:)*MinvX(:,lowRankLocs{p}) RT_minus_R(lowRankLocs{p},p) = 0; RT_ratio(lowRankLocs{p},p) = 0; end end else disp('Not performing low rank updates. May want to do this in the future to speed up the algorithm.');pause(1e-9); end hasLowRankCorrectionsCell = num2cell(hasLowRankCorrections); % avgLowRankNum/length(locsNotFullyConverged) if strcmp(innerLoopMode,'useG') for p=locsNotFullyConverged G{p}(:,:) = MinvX*(repmat(RT_minus_R(:,p),1,D).*XT); end Minvbc = mat2cell(Minv_ls,D,ones(1,P)); end locsNotConverged = locsNotFullyConverged; ninnerloops = 0; while 1 ninnerloops = ninnerloops + 1; %fprintf(1,['\tPerforming inner loop #',num2str(ninnerloops),'...\n']);pause(1e-9); wsprev(:,:) = ws; if strcmp(innerLoopMode,'useG') wsc = mat2cell(ws(:,locsNotConverged),D,ones(1,length(locsNotConverged))); ws(:,locsNotConverged) = cell2mat(cellfun(@iterateWithLowRankCorrection,wsc,G(locsNotConverged),Minvbc(locsNotConverged),lowRankCorrectionMatsLeft(locsNotConverged),lowRankCorrectionMatsRight(locsNotConverged),hasLowRankCorrections(locsNotConverged),'UniformOutput',false)); else %XTwsprev = XT*wsprev(:,locsNotConverged); ws(:,locsNotConverged) = MinvX*(RT_minus_R(:,locsNotConverged).*(XT*wsprev(:,locsNotConverged))) + Minv_ls(:,locsNotConverged); % Now do the low-rank corrections lowRankLocsCurr = locsNotConverged(find(hasLowRankCorrections(locsNotConverged))); if ~isempty(lowRankLocsCurr) wsc = mat2cell(ws(:,lowRankLocsCurr),D,ones(1,length(lowRankLocsCurr))); ws(:,lowRankLocsCurr) = cell2mat(cellfun(@lowRankCorrection,wsc,lowRankCorrectionMatsLeft(lowRankLocsCurr),lowRankCorrectionMatsRight(lowRankLocsCurr),hasLowRankCorrectionsCell(lowRankLocsCurr),'UniformOutput',false)); end end tol_measure = (1/D)*sum((ws(:,locsNotConverged)-wsprev(:,locsNotConverged)).^2)./sum(ws(:,locsNotConverged).^2); locsNew = find(tol_measure > conv_tol); if isempty(locsNew) break; end locsNotConverged = locsNotConverged(locsNew); if debug==1 figure(102); plot((sum((ws-wsprev).^2)./sum(wsprev.^2))); pause(0.1); end end fprintf(1,'\tNumber of inner loops: %d\n',ninnerloops);pause(1e-9); locsNotFullyConverged = find((1/D)*sum((ws_last-ws).^2)./sum(ws_last.^2) > conv_tol); if isempty(locsNotFullyConverged) % Save out the converged results eInd = 0; while 1 sInd = eInd + 1; if sInd > length(perms) break end eInd = sInd + cv.numFolds - 1; currInds = sInd:eInd; if max(abs(perms(currInds)-mean(perms(currInds)))) error('Something''s very wrong here!'); end permInd = perms(sInd); if strcmp(looMode,'average') ys_loo_perm = zeros(cv.numFolds,1); truth = zeros(cv.numFolds,1); else ys_loo_perm = zeros(N,1); truth = zeros(N,1); end for foldNum = 1:cv.numFolds if strcmp(looMode,'average') ys_loo_perm(foldNum) = mean(XT(cv.outTrials{foldNum},:)*ws(:,currInds(foldNum))); truth(foldNum) = yperms(cv.outTrials{foldNum}(1),permInd); else ys_loo_perm(cv.outTrials{foldNum}) = XT(cv.outTrials{foldNum},:)*ws(:,currInds(foldNum)); truth(cv.outTrials{foldNum}) = yperms(cv.outTrials{foldNum},permInd); end end % Now compute the roc value and store it Az_val = rocarea(ys_loo_perm,truth); if permInd == 1 % Then this is the LOO run -- save out the ws ws_loo(:,:) = ws(:,currInds); ys_loo = ys_loo_perm; Az_loo = Az_val; else Az_perm_dist(permInd-1) = Az_val; end end if batchNum < numBatches % We need to re-fill iter = 0; batchNum = batchNum + 1; ws = zeros(D,P); [y,zeroOutInds,perms,locsNotFullyConverged] = getCurrentYAndZeroInds(batchNum,yperms,cv,chunkSize); else break; end end end %toc ws = finalInvertMat*ws; %if strcmp(mode,'loo') % yv = sum(X.*ws)'; % testerr = 0.5*sum(abs((2*(y(:,1)-0.5)) - sign(yv))); % disp(['Number of test errors: ',num2str(testerr)]); %end %disp(['DONE!; ', num2str(iter)]); end function w = lowRankCorrection(w,lowRankCorrectionMatLeft,lowRankCorrectionMatRight,hasLowRankCorrection) if ~hasLowRankCorrection; return; end; w = w + lowRankCorrectionMatLeft*(lowRankCorrectionMatRight*w); end function e = lowRankCorrection2(w,lowRankCorrectionMatLeft,lowRankCorrectionMatRight,hasLowRankCorrection) e = zeros(size(w),class(w)); if ~hasLowRankCorrection; return; end; e = lowRankCorrectionMatLeft*(lowRankCorrectionMatRight*w); end function w = iterateWithLowRankCorrection(w,G,Minvb,lowRankCorrectionMatLeft,lowRankCorrectionMatRight,hasLowRankCorrection) w = G*w + Minvb; if hasLowRankCorrection w = w + lowRankCorrectionMatLeft*(lowRankCorrectionMatRight*w); end end function [y,zeroOutInds,perms,locsNotFullyConverged] = getCurrentYAndZeroInds(batchNum,yperms,cv,chunkSize) [N,numperms] = size(yperms); P = min(chunkSize,cv.numFolds*numperms); numpermsPerBatch = P/cv.numFolds; if abs(numpermsPerBatch - round(numpermsPerBatch)) > 0 error('Something''s not right'); end % Now determine the set of permutations to run based on batchNum permsStart = (batchNum-1)*numpermsPerBatch + 1; permsEnd = min(numperms, permsStart + numpermsPerBatch - 1); permsCurr = permsStart:permsEnd; numpermsCurr = length(permsCurr); perms = reshape(repmat(assertVec(permsCurr,'row'),cv.numFolds,1),numpermsCurr*cv.numFolds,1); y = zeros(N,P); eInd = 0; for n=permsCurr sInd = eInd + 1; eInd = sInd + cv.numFolds - 1; y(:,sInd:eInd) = repmat(yperms(:,n),1,cv.numFolds); end locsNotFullyConverged = 1:eInd; totalOutTrials = 0; for p=1:cv.numFolds totalOutTrials = totalOutTrials + length(cv.outTrials{p}); cv.outTrials{p} = assertVec(cv.outTrials{p},'row'); end zeroOutInds = zeros(1,totalOutTrials*numpermsCurr,'uint32'); eInd = 0; % Compute the indices to be zeroed out in the NxP gradient matrix for foldNum=1:cv.numFolds for n=1:numpermsCurr sInd = eInd + 1; eInd = sInd + length(cv.outTrials{foldNum}) - 1; zeroOutInds(sInd:eInd) = cv.outTrials{foldNum} + N*(foldNum+(n-1)*cv.numFolds - 1);%sub2ind([N,P],assertVec(cv.outTrials{foldNum},'row'),(foldNum+(n-1)*cv.numFolds)*ones(1,length(cv.outTrials{foldNum}))); end end end function doSomePermutationStuff ratio_thresh = 0.99; max_inversions = 10;%0.1*P; % We need to find extreme RT_minus_R/RT values (close to 1) % that may slow convergence QT = RT_minus_R(:,locsNotFullyConverged)./repmat(RT,1,length(locsNotFullyConverged)); [nctrialinds,ncperminds] = find(QT > ratio_thresh); ncperminds = locsNotFullyConverged(ncperminds); uncperminds = unique(ncperminds); [~,permindordering] = sort(min(R(:,uncperminds)),'ascend'); uncperminds = [];%uncperminds(permindordering); numclusts = 1; cluster_perminds = cell(1,0); cluster_perminds{1} = setdiff(locsNotFullyConverged,uncperminds); RT_minus_Rs = cell(1,0); RT_minus_Rs{1} = repmat(RT,1,length(cluster_perminds{1})) - R(:,cluster_perminds{1}); Minvs = cell(1,0); Minvs{1} = Minv; MinvXs = cell(1,0); MinvXs{1} = MinvX; Minv_lsc = cell(1,0); Minv_lsc{1} = Minv_ls(:,cluster_perminds{1}); if length(uncperminds) while length(uncperminds) uncpermind = uncperminds(1); locs = nctrialinds(find(ncperminds==uncpermind)); RTC = RT; RTC(locs) = R(locs,uncpermind)/(1-(ratio_thresh-eps)); % locsprev = []; % while 1 locs = uncperminds(find(min(repmat(RTC,1,length(uncperminds))-R(:,uncperminds))>=0)); RTC = max(R(:,locs),[],2); % locs = intersect(locs,find(min(R(:,uncperminds)/(1-(ratio_thresh-eps))-repmat(RTC,1,length(uncperminds)))>=0)); % if (length(locs) == length(locsprev)) && ~length(setdiff(locs,locsprev)) % break; % end % locsprev = locs; % end % if max(max((repmat(RTC,1,length(locs))-R(:,locs))./repmat(RTC,1,length(locs)))) > ratio_thresh % error('Something wrong here!'); % end numclusts = numclusts + 1; cluster_perminds{numclusts} = locs; ismem = ismember(uncperminds,cluster_perminds{numclusts}); uncperminds = uncperminds(~ismem); % disp([num2str(numclusts),'; ',num2str(length(uncperminds)),'; ',num2str(max(max((repmat(RTC,1,length(cluster_perminds{numclusts}))-R(:,cluster_perminds{numclusts}))./repmat(RTC,1,length(cluster_perminds{numclusts})))))]);pause(1e-9); RT_minus_Rs{numclusts} = repmat(RTC,1,length(cluster_perminds{numclusts}))-R(:,cluster_perminds{numclusts}); Minvs{numclusts} = (X*diag(RTC)*XT + additiveMatrixFactor)^(-1); MinvXs{numclusts} = Minvs{numclusts}*X; Minv_lsc{numclusts} = MinvXs{numclusts}*neg_ls_without_X(:,cluster_perminds{numclusts}); if numclusts == (max_inversions-1) numclusts = numclusts + 1; cluster_perminds{numclusts} = uncperminds; RTC = max(R(:,uncperminds),[],2); RT_minus_Rs{numclusts} = repmat(RTC,1,length(cluster_perminds{numclusts}))-R(:,cluster_perminds{numclusts}); Minvs{numclusts} = (X*diag(RTC)*XT + additiveMatrixFactor)^(-1); MinvXs{numclusts} = Minvs{numclusts}*X; Minv_lsc{numclusts} = MinvXs{numclusts}*neg_ls_without_X(:,cluster_perminds{numclusts}); break; end end else % Do nothing then... end % numclusts end % if strcmp(mode,'permutation') % % ws_norc = ws; % turnNum = 0; % numTurns = 1; % cachesize = 3; % ws_cache = zeros(D,size(ws,2)*cachesize,class(ws)); % while 1 % turnNum = turnNum + 1; % if turnNum == numTurns % conv_tol = 1e-12; % else % conv_tol = 1e-6; % end % % locsNotConverged = locsNotFullyConverged; % iterc = 0; % while 1 % iterc = iterc + 1; % wsprev = ws; % % % XTwsprev = XT*wsprev(:,locsNotConverged); % ws(:,locsNotConverged) = MinvX*(RT_minus_R(:,locsNotConverged).*(XT*wsprev(:,locsNotConverged))) + Minv_ls(:,locsNotConverged); % if turnNum == numTurns % % Now do the low-rank corrections % wsc = mat2cell(ws(:,locsNotConverged),D,ones(1,length(locsNotConverged))); % ws(:,locsNotConverged) = cell2mat(cellfun(@lowRankCorrection,wsc,lowRankCorrectionMatsLeft(locsNotConverged),lowRankCorrectionMatsRight(locsNotConverged),hasLowRankCorrections(locsNotConverged),'UniformOutput',false)); % else % for c=min(iterc,cachesize):-1:1 % inds = c:cachesize:size(ws_cache,2); % inds = inds(locsNotConverged); % if c > 1 % indsprev = (c-1):cachesize:size(ws_cache,2); % indsprev = indsprev(locsNotConverged); % ws_cache(:,inds) = ws_cache(:,indsprev); % else % ws_cache(:,inds) = ws(:,locsNotConverged); % end % end % end % % tol_measure = (1/N)*sum((ws(:,locsNotConverged)-wsprev(:,locsNotConverged)).^2)./sum(ws(:,locsNotConverged).^2); % %tol_measure = max(abs(ws(:,locsNotConverged)-wsprev(:,locsNotConverged))./abs(ws(:,locsNotConverged))); % locsNew = find(tol_measure > conv_tol); % if isempty(locsNew) % break; % end % locsNotConverged = locsNotConverged(locsNew); % % if debug==1 % h=figure(102); % plot(tol_measure); % end % end % iterc % % % wstrue = zeros(size(ws)); % % for p=1:P % % wstrue(:,p) = (X*diag(R(:,p))*XT+2*l2_lambda*L)\neg_ls(:,p); % % end % % figure(107);plot((1/N)*sum((ws-wstrue).^2)./sum(wstrue.^2)); % % disp('DONE!!!'); % % pause; % % if turnNum == numTurns % break; % end % % e = zeros(D,P); % wscc = mat2cell(ws_cache,D,cachesize*ones(1,P)); % es = zeros(D,P*cachesize); % inds = reshape(1:P*cachesize,cachesize,P); % inds = reshape(inds(:,locsNotFullyConverged),1,cachesize*length(locsNotFullyConverged)); % es(:,inds) = cell2mat(cellfun(@lowRankCorrection2,wscc(locsNotFullyConverged),lowRankCorrectionMatsLeft(locsNotFullyConverged),lowRankCorrectionMatsRight(locsNotFullyConverged),hasLowRankCorrections(locsNotFullyConverged),'UniformOutput',false)); % for cacheind = min(iterc,cachesize):-1:1 % inds = cacheind:cachesize:size(es,2); % inds = inds(locsNotFullyConverged); % e(:,locsNotFullyConverged) = e(:,locsNotFullyConverged) + es(:,inds); % if cacheind > 1 % e(:,locsNotFullyConverged) = MinvX*(RT_minus_R(:,locsNotFullyConverged).*(XT*e(:,locsNotFullyConverged))); % e(:,locsNotFullyConverged) = cell2mat(cellfun(@lowRankCorrection,mat2cell(e(:,locsNotFullyConverged),D,ones(1,length(locsNotFullyConverged))),lowRankCorrectionMatsLeft(locsNotFullyConverged),lowRankCorrectionMatsRight(locsNotFullyConverged),hasLowRankCorrections(locsNotFullyConverged),'UniformOutput',false)); % end % end % ws = ws + e; % % figure(108);plot((1/N)*sum((ws-wstrue).^2)./sum(wstrue.^2)); % % disp(num2str(cacheind)); % % pause; % % end % % end % % end
github
djangraw/FelixScripts-master
eventnum.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/eventnum.m
2,095
utf_8
19af52530257a702de592f0cbe1bb036
% eventnum() - converts voltage levels v into integer event number based % on predefined voltage levels. It also makes sure that discretized value % is consistent for at least two samples. However, this can not be tested % for first and last value and so those may not be correct. To fix that % append the previous and next values to v. Voltage values are assumed to % be calibrated with the corresponding gain. % % Usage: % >> n = eventnum(v,mark); % % Inputs: % v - voltage levels % mark - predefined voltage levels % % Outputs: % n - discrete levels % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function x=eventnum(x,mark) % make sure vectors have the right orientation x=x(:);mark=mark(:)'; % convert into integer labels (not the most efficient but uses less memory) x = repmat(x,[1 size(mark,2)]); for i=1:length(mark), x(:,i) = x(:,i)-mark(i); end; x=abs(x); x=x'; [tmp,x]=min(x); % detect state transitions transitions = find(x(1:end-2)~=x(2:end-1))+1; % transitions may take more than one sample so take the following sample x(transitions) = x(transitions+1);
github
djangraw/FelixScripts-master
pop_logisticregression.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/pop_logisticregression.m
13,162
utf_8
ec54474281f8a17f711f7e32803e0c2e
% pop_logisticregression() - Determine linear discriminating vector between two datasets. % using logistic regression. % % Usage: % >> pop_logisticregression( ALLEEG, datasetlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show); % % Inputs: % ALLEEG - array of datasets % datasetlist - list of datasets % chansubset - vector of channel subset for dataset 1 [1:min(Dset1,Dset2)] % chansubset2 - vector of channel subset for dataset 2 [chansubset] % trainingwindowlength - Length of training window in samples [all] % trainingwindowoffset - Offset(s) of training window(s) in samples [1] % regularize - regularize [1|0] -> [yes|no] [0] % lambda - regularization constant for weight decay. [1e-6] % Makes logistic regression into a support % vector machine for large lambda % (cf. Clay Spence) % lambdasearch - [1|0] -> search for optimal regularization % constant lambda % eigvalratio - if the data does not fill D-dimensional % space, i.e. rank(x)<D, you should specify % a minimum eigenvalue ratio relative to the % largest eigenvalue of the SVD. All dimensions % with smaller eigenvalues will be eliminated % prior to the discrimination. % vinit - initialization for faster convergence [zeros(D+1,1)] % show - display discrimination boundary during training [0] % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Adam Gerson % and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5/21/2005, Fixed bug in leave one out script, Adam function [ALLEEG, com] = pop_logisticregression(ALLEEG, setlist, chansubset, chansubset2, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, show, LOO); showaz=1; com = ''; if nargin < 1 help pop_logisticregression; return; end; if isempty(ALLEEG) error('pop_logisticregression(): cannot process empty sets of data'); end; if nargin < 2 % which set to save % ----------------- uilist = { { 'style' 'text' 'string' 'Enter two datasets to compare (ex: 1 3):' } ... { 'style' 'edit' 'string' [ '1 2' ] } ... { 'style' 'text' 'string' 'Enter channel subset ([] = all):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Enter channel subset for dataset 2 ([] = same as dataset 1):' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Training Window Length (samples [] = all):' } ... { 'style' 'edit' 'string' '50' } ... { 'style' 'text' 'string' 'Training Window Offset (samples, 1 = epoch start):' } ... { 'style' 'edit' 'string' '1' } ... { 'style' 'text' 'string' 'Regularize' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Regularization constant for weight decay' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Search for optimal regularization constant' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Eigenvalue ratio for subspace reduction' } ... { 'style' 'edit' 'string' '1e-6' } ... { 'style' 'text' 'string' 'Initial discrimination vector [channels+1 x 1] for faster convergence (optional)' } ... { 'style' 'edit' 'string' '' } ... { 'style' 'text' 'string' 'Display discrimination boundary' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} ... { 'style' 'text' 'string' 'Leave One Out' } ... { 'style' 'checkbox' 'string' '' 'value' 0 } {} }; result = inputgui( { [2 .5] [2 .5] [2 .5] [2 .5] [2 .5] [3.1 .4 .15] [2 .5] [3.1 .4 .15] [2 .5] [2 .5] [3.1 .4 .15] [3.1 .4 .15] }, ... uilist, 'pophelp(''pop_logisticregression'')', ... 'Logistic Regression -- pop_logisticregression()'); if length(result) == 0 return; end; setlist = eval( [ '[' result{1} ']' ] ); chansubset = eval( [ '[' result{2} ']' ] ); if isempty( chansubset ), chansubset = 1:min(ALLEEG(setlist(1)).nbchan,ALLEEG(setlist(2)).nbchan); end; chansubset2 = eval( [ '[' result{3} ']' ] ); if isempty(chansubset2), chansubset2=chansubset; end trainingwindowlength = str2num(result{4}); if isempty(trainingwindowlength) trainingwindowlength = ALLEEG(setlist(1)).pnts; end; trainingwindowoffset = str2num(result{5}); if isempty(trainingwindowoffset) trainingwindowoffset = 1; end; regularize=result{6}; if isempty(regularize), regularize=0; end lambda=str2num(result{7}); if isempty(lambda), lambda=1e-6; end lambdasearch=result{8}; if isempty(lambdasearch), lambdasearch=0; end eigvalratio=str2num(result{9}); if isempty(eigvalratio), eigvalratio=1e-6; end vinit=eval([ '[' result{10} ']' ]); if isempty(vinit), vinit=zeros(length(chansubset)+1,1); end vinit=vinit(:); % Column vector show=result{11}; if isempty(show), show=0; end LOO=result{12}; if isempty(LOO), show=0; end end; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end; if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(1)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 1'); end if max(trainingwindowlength+trainingwindowoffset-1)>ALLEEG(setlist(2)).pnts, error('pop_logisticregression(): training window exceeds length of dataset 2'); end if (length(chansubset)~=length(chansubset2)), error('Number of channels from each dataset must be equal.'); end truth=[zeros(trainingwindowlength.*ALLEEG(setlist(1)).trials,1); ones(trainingwindowlength.*ALLEEG(setlist(2)).trials,1)]; ALLEEG(setlist(1)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan); % In case a subset of channels are used, assign unused electrodes in scalp projection to NaN ALLEEG(setlist(1)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan)'; ALLEEG(setlist(2)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan)'; ALLEEG(setlist(1)).icasphere=eye(ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icasphere=eye(ALLEEG(setlist(2)).nbchan); for i=1:length(trainingwindowoffset), x=cat(3,ALLEEG(setlist(1)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:), ... ALLEEG(setlist(2)).data(chansubset,trainingwindowoffset(i):trainingwindowoffset(i)+trainingwindowlength-1,:)); x=x(:,:)'; % Rearrange data for logist.m [D (T x trials)]' %v=logist(x,truth)'; v = logist(x,truth,vinit,show,regularize,lambda,lambdasearch,eigvalratio); y = x*v(1:end-1) + v(end); bp = bernoull(1,y); [Az,Ry,Rx] = rocarea(bp,truth); if showaz, fprintf('Window Onset: %d; Az: %6.2f\n',trainingwindowoffset(i),Az); end a = y \ x; asetlist1=y(1:trainingwindowlength.*ALLEEG(setlist(1)).trials) \ x(1:trainingwindowlength.*ALLEEG(setlist(1)).trials,:); asetlist2=y(trainingwindowlength.*ALLEEG(setlist(1)).trials+1:end) \ x(trainingwindowlength.*ALLEEG(setlist(1)).trials+1:end,:); ALLEEG(setlist(1)).icaweights(i,chansubset)=v(1:end-1)'; ALLEEG(setlist(2)).icaweights(i,chansubset2)=v(1:end-1)'; ALLEEG(setlist(1)).icawinv(chansubset,i)=a'; % consider replacing with asetlist1 ALLEEG(setlist(2)).icawinv(chansubset2,i)=a'; % consider replacing with asetlist2 if LOO % LOO clear y; N=ALLEEG(setlist(1)).trials+ALLEEG(setlist(2)).trials; ploo=zeros(N*trainingwindowlength,1); for looi=1:length(x)./trainingwindowlength, indx=ones(N*trainingwindowlength,1); indx((looi-1)*trainingwindowlength+1:looi*trainingwindowlength)=0; tmp = x(find(indx),:); % LOO data tmpt = [truth(find(indx))]; % Target vloo(:,looi)=logist(tmp,tmpt,vinit,show,regularize,lambda,lambdasearch,eigvalratio); y(:,looi) = [x((looi-1)*trainingwindowlength+1:looi*trainingwindowlength,:) ones(trainingwindowlength,1)]*vloo(:,looi); ymean(looi)=mean(y(:,looi)); % ploo(find(1-indx)) = bernoull(1,y(:,looi)); ploo((looi-1)*trainingwindowlength+1:looi*trainingwindowlength) = bernoull(1,y(:,looi)); ploomean(looi)=bernoull(1,ymean(looi)); end truthmean=([zeros(ALLEEG(setlist(1)).trials,1); ones(ALLEEG(setlist(2)).trials,1)]); [Azloo,Ryloo,Rxloo] = rocarea(ploo,truth); [Azloomean,Ryloomean,Rxloomean] = rocarea(ploomean,truthmean); fprintf('LOO Az: %6.2f\n',Azloomean); end if 0 ALLEEG(setlist(1)).lrweights(i,:)=v; ALLEEG(setlist(1)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(2)).lrweights(i,:)=v; ALLEEG(setlist(2)).lrweightsinv(:,i)=pinv(v); ALLEEG(setlist(1)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(1)).data(:,:); ones(1,ALLEEG(setlist(1)).pnts.*ALLEEG(setlist(1)).trials)], ... ALLEEG(setlist(1)).pnts,ALLEEG(setlist(1)).trials),-1); ALLEEG(setlist(2)).lrsources(i,:,:)=shiftdim(reshape(v*[ALLEEG(setlist(2)).data(:,:); ones(1,ALLEEG(setlist(2)).pnts.*ALLEEG(setlist(2)).trials)], ... ALLEEG(setlist(2)).pnts,ALLEEG(setlist(2)).trials),-1); end end; if 0 ALLEEG(setlist(1)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(1)).lrtrainoffset=trainingwindowoffset; ALLEEG(setlist(2)).lrtrainlength=trainingwindowlength; ALLEEG(setlist(2)).lrtrainoffset=trainingwindowoffset; end % save channel names % ------------------ %plottopo( tracing, ALLEEG(setlist(1)).chanlocs, ALLEEG(setlist(1)).pnts, [ALLEEG(setlist(1)).xmin ALLEEG(setlist(1)).xmax 0 0]*1000, plottitle, chansubset ); % recompute activations (temporal sources) and check dataset integrity eeg_options; for i=1:2, if option_computeica ALLEEG(setlist(i)).icaact = (ALLEEG(setlist(i)).icaweights*ALLEEG(setlist(i)).icasphere)*reshape(ALLEEG(setlist(i)).data, ALLEEG(setlist(i)).nbchan, ALLEEG(setlist(i)).trials*ALLEEG(setlist(i)).pnts); ALLEEG(setlist(i)).icaact = reshape( ALLEEG(setlist(i)).icaact, size(ALLEEG(setlist(i)).icaact,1), ALLEEG(setlist(i)).pnts, ALLEEG(setlist(i)).trials); end; end for i=1:2, [ALLEEG]=eeg_store(ALLEEG,ALLEEG(setlist(i)),setlist(i)); end com = sprintf('pop_logisticregression( %s, [%s], [%s], [%s], [%s]);', inputname(1), num2str(setlist), num2str(chansubset), num2str(trainingwindowlength), num2str(trainingwindowoffset)); fprintf('Done.\n'); return;
github
djangraw/FelixScripts-master
logist.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/logist.m
9,356
utf_8
9856c6f21dcfcf687525cb7ac3391941
% logist() - Iterative recursive least squares algorithm for linear % logistic model % % Usage: % >> [v] = logist(x,y,vinit,show,regularize,lambda,lambdasearch,eigvalratio); % % Inputs: % x - N input samples [N,D] % y - N binary labels [N,1] {0,1} % % Optional parameters: % vinit - initialization for faster convergence % show - if>0 will show first two dimensions % regularize - [1|0] -> [yes|no] % lambda - regularization constant for weight decay. Makes % logistic regression into a support vector machine % for large lambda (cf. Clay Spence). Defaults to 10^-6. % lambdasearch- [1|0] -> search for optimal regularization constant lambda % eigvalratio - if the data does not fill D-dimensional space, % i.e. rank(x)<D, you should specify a minimum % eigenvalue ratio relative to the largest eigenvalue % of the SVD. All dimensions with smaller eigenvalues % will be eliminated prior to the discrimination. % % Outputs: % v - v(1:D) normal to separating hyperplane. v(D+1) slope % % Compute probability of new samples with p = bernoull(1,[x 1]*v); % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) % % CHANGED 3/25/11 by DJ and BC - to prevent convergence on first iteration % (if v is initialized to zero), we set v=v+eps. To prevent never % converging, we needed to set the convergence threshold higher, so we made % it a parameter (convergencethreshold). At the advice of matlab, we % changed from inv(...)*grad to (...)\grad. We also added a topoplot % (based on the channel locations in ALLEEG(1)) to the 'show' figure. And % we got rid of the line if regularize, lambda=1e-6; end. %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [v] = logist(x,y,v,show,regularize,lambda,lambdasearch,eigvalratio) printoutput=0; convergencethreshold = 1e-6; % look at plot (show=1) to find a good value here [N,D]=size(x); iter=0; showcount=0; if nargin<3 | isempty(v), v=zeros(D,1); vth=0; else vth=v(D+1); v=v(1:D); end; if nargin<4 | isempty(show); show=0; end; if nargin<5 | isempty(regularize); regularize=0; end if nargin<6 | isempty(lambda); lambda=eps; end; if nargin<7 | isempty(lambdasearch), lambdasearch=0; end if nargin<8 | isempty(eigvalratio); eigvalratio=0; end; % if regularize, lambda=1e-6; end % subspace reduction if requested - electrodes might be linked if eigvalratio [U,S,V] = svd(x,0); % subspace analysis V = V(:,find(diag(S)/S(1,1)>eigvalratio)); % keep significant subspace x = x*V; % map the data to that subspace v = V'*v; % reduce initialization to the subspace [N,D]=size(x); % less dimensions now end % combine threshold computation with weight vector. x = [x ones(N,1)]; v = [v; vth]+eps; % v = randn(size(v))*eps; vold=ones(size(v)); if regularize, lambda = [0.5*lambda*ones(1,D) 0]'; end % clear warning as we will use it to catch conditioning problems lastwarn(''); % If lambda increases, the maximum number of iterations is increased from % maxiter to maxiterlambda maxiter=100; maxiterlambda=1000; singularwarning=0; lambdawarning=0; % Initialize warning flags if show, figure; end % IRLS for binary classification of experts (bernoulli distr.) while ((subspace(vold,v)>convergencethreshold)&&(iter<=maxiter)&&(~singularwarning)&&(~lambdawarning))||iter==0, vold=v; mu = bernoull(1,x*v); % recompute weights w = mu.*(1-mu); e = (y - mu); grad = x'*e; % - lambda .* v; if regularize, % lambda=(v'*v)./2; % grad=grad-lambda; grad=grad - lambda .* v; end %inc = inv(x'*diag(w)*x+eps*eye(D+1)) * grad; inc = (x'*(repmat(w,1,D+1).*x)+diag(lambda)*eye(D+1)) \ grad; if strncmp(lastwarn,'Matrix is close to singular or badly scaled.',44) warning('Bad conditioning. Suggest reducing subspace.') singularwarning=1; end if (norm(inc)>=1000)&regularize, if ~lambdasearch, warning('Data may be perfectly separable. Suggest increasing regularization constant lambda'); end lambdawarning=1; end; % avoid funny outliers that happen with inv if (norm(inc)>=1000)&regularize&lambdasearch, % Increase regularization constant lambda lambda=sign(lambda).*abs(lambda.^(1/1.02)); lambdawarning=0; if printoutput, fprintf('Bad conditioning. Data may be perfectly separable. Increasing lambda to: %6.2f\n',lambda(1)); end maxiter=maxiterlambda; elseif (~singularwarning)&(~lambdawarning), % update v = v + inc; if show showcount=showcount+1; subplot(1,3,1) ax=[min(x(:,1)), max(x(:,1)), min(x(:,2)), max(x(:,2))]; hold off; h(1)=plot(x(y>0,1),x(y>0,2),'bo'); hold on; h(2)=plot(x(y<1,1),x(y<1,2),'r+'); xlabel('First Dimension','FontSize',14); ylabel('Second Dimension','FontSize',14); title('Discrimination Boundary','FontSize',14); legend(h,'Dataset 1','Dataset 2'); axis square; if norm(v)>0, tmean=mean(x); tmp = tmean; tmp(1)=0; t1=tmp; t1(2)=ax(3); t2=tmp; t2(2)=ax(4); xmin=median([ax(1), -(t1*v)/v(1), -(t2*v)/v(1)]); xmax=median([ax(2), -(t1*v)/v(1), -(t2*v)/v(1)]); tmp = tmean; tmp(2)=0; t1=tmp; t1(1)=ax(1); t2=tmp; t2(1)=ax(2); ymin=median([ax(3), -(t1*v)/v(2), -(t2*v)/v(2)]); ymax=median([ax(4), -(t1*v)/v(2), -(t2*v)/v(2)]); if v(1)*v(2)>0, tmp=xmax;xmax=xmin;xmin=tmp;end; if ~(xmin<ax(1)|xmax>ax(2)|ymin<ax(3)|ymax>ax(4)), h=plot([xmin xmax],[ymin ymax],'k','LineWidth',2); end; end; subplot(1,3,2); vnorm(showcount) = subspace(vold,v); if vnorm(showcount)==0, vnorm(showcount)=nan; end plot(log(vnorm)/log(10)); title('Subspace between v(t) and v(t+1)','FontSize',14); xlabel('Iteration','FontSize',14); ylabel('Subspace','FontSize',14); axis square; subplot(1,3,3); ALLEEG = evalin('base','ALLEEG'); topoplot(v(1:(end-1)),ALLEEG(1).chanlocs,'electrodes','on'); title('Spatial weights for this iteration') colorbar; drawnow; end; % exit if converged if subspace(vold,v)<convergencethreshold, % CHANGED if printoutput, disp(['Converged... ']); disp(['Iterations: ' num2str(iter)]); disp(['Subspace: ' num2str(subspace(vold,v))]); disp(['Lambda: ' num2str(lambda(1))]); end end; end % exit if taking too long iter=iter+1; if iter>maxiter, if printoutput, disp(['Not converging after ' num2str(maxiter) ' iterations.']); disp(['Iterations: ' num2str(iter-1)]); disp(['Subspace: ' num2str(subspace(vold,v))]); disp(['Lambda: ' num2str(lambda(1))]); end end; end; if eigvalratio v = [V*v(1:D);v(D+1)]; % the result should be in the original space end function [p]=bernoull(x,eta); % bernoull() - Computes Bernoulli distribution of x for "natural parameter" eta. % % Usage: % >> [p] = bernoull(x,eta) % % The mean m of a Bernoulli distributions relates to eta as, % m = exp(eta)/(1+exp(eta)); p = exp(eta.*x - log(1+exp(eta)));
github
djangraw/FelixScripts-master
bernoull.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/LogisticRegression/bernoull.m
1,630
utf_8
858cf1a152c7a6041d64ad220a523d34
% bernoull() - Computes Bernoulli distribution of x for % "natural parameter" eta. The mean m of a % Bernoulli distributions relates to eta as, % m = exp(eta)/(1+exp(eta)); % % Usage: % >> [p]=bernoull(x,eta); % % Inputs: % x - data % eta - distribution parameter % % Outputs: % p - probability % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) % % Updated 9/21/11 by DJ - make x a vector, use x(indx) instead of just x %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [p]=bernoull(x,eta) if numel(x)==1 x = repmat(x,size(eta)); end e = exp(eta); p = ones(size(e)); indx = (~isinf(e)); p(indx) = exp(eta(indx).*x(indx) - log(1+e(indx)));
github
djangraw/FelixScripts-master
SetUpMultiWindowJlr_v1p2.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/MultiWindow/SetUpMultiWindowJlr_v1p2.m
7,578
utf_8
f33cb93b3ae998a5ec7afa1f150dd77e
function [vOut,fmOut] = SetUpMultiWindowJlr_v1p2(ALLEEG, trainingwindowlength, trainingwindowoffset, vinit, jitterPrior, pop_settings, logist_settings) % [vOut] = SetUpMultiWindowJlr_v1p2(ALLEEG, trainingwindowlength, trainingwindowoffset, vinit, pop_settings, logist_settings) % % INPUTS: % -ALLEEG is 1x2, each with D electrodes % -trainingwindowlength is a scalar % -trainingwindowoffset is 1xP % -vinit is DxP % -pop_settings is a struct % -logist_settings is a struct % % OUTPUTS: % -vOut is DxP % % Created 12/11/12 by DJ. % Updated 12/18/12 by DJ - v1p1 (computeJitterProbabilities has corrected % posterior size, p values) % Updated 12/19/12 by DJ - v1p2 (soft EM) % Updated 12/28/12 by DJ - fmOut size correction plotdebugfigs = false; vinit(vinit==0) = vinit(vinit==0)+1e-100; % Unpack options UnpackStruct(pop_settings); % convergencethreshold,jitterrange,weightprior,forceOneWinner,conditionPrior UnpackStruct(logist_settings); % eigvalratio,lambda,lambdasearch,regularize,useOffset % Set up truth labels (one for each data sample in the window on each trial ntrials1 = ALLEEG(1).trials; ntrials2 = ALLEEG(2).trials; % Extract data raweeg1 = ALLEEG(1).data(:,:,:); raweeg2 = ALLEEG(2).data(:,:,:); % Smooth data smootheeg1 = nan(size(raweeg1,1),size(raweeg1,2)-trainingwindowlength+1, size(raweeg1,3)); smootheeg2 = nan(size(raweeg2,1),size(raweeg2,2)-trainingwindowlength+1, size(raweeg2,3)); for i=1:size(raweeg1,3) smootheeg1(:,:,i) = conv2(raweeg1(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end for i=1:size(raweeg2,3) smootheeg2(:,:,i) = conv2(raweeg2(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end % Get prior [ptprior,priortimes] = jitterPrior.fn((1000/ALLEEG(1).srate)*((jitterrange(1)+1):jitterrange(2)),jitterPrior.params); % Make prior into a matrix and normalize rows if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = repmat(ptprior,ntrials1+ntrials2,1); end ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); % Ensure the rows sum to 1 % Re-weight priors according to the number of trials in each class if weightprior ptprior(truth_trials==1,:) = ptprior(truth_trials==1,:) / sum(truth_trials==1); ptprior(truth_trials==0,:) = ptprior(truth_trials==0,:) / sum(truth_trials==0); end % Make the prior the initial condition for the posteriors pt = ptprior; if forceOneWinner % Get posteriors [~,iMax] = max(pt,[],2); pt = full(sparse(1:length(iMax),iMax,1,size(pt,1),size(pt,2))); % all zeros except at max points end % [~,iMax] = max(pt,[],2); % jitters = priortimes(iMax); % Get data and truth matrices alldata = cat(3,smootheeg1,smootheeg2); truth = [zeros(ntrials1,1); ones(ntrials2,1)]; % The truth value associated with each trial % Get data across windows & jitters iWindow = (min(trainingwindowoffset)+min(jitterrange)):(max(trainingwindowoffset)+max(jitterrange)); x = alldata(:,iWindow,:); x(end+1,:,:) = 1; % add for offset usage % Set up for loop vCrop = vinit; vCrop_prev = vCrop; % priortimes = (jitterrange(1)+1):jitterrange(2); % pt = zeros(ntrials1+ntrials2,length(priortimes)); % jitters = zeros(1,ntrials1+ntrials2); iter = 0; % draw debug figures if plotdebugfigs PlotDebugFigures(iter,vCrop,pt,jitterrange,trainingwindowoffset,ALLEEG); end %%% MAIN LOOP %%% while iter==0 || (subspace(vCrop,vCrop_prev)>convergencethreshold && iter<max_iter) iter = iter+1; fprintf('Iteration %d...\n',iter); vCrop_prev = vCrop; [v] = FindMultiWindowWeights_v1p2(alldata,truth,trainingwindowoffset,pt,priortimes,vCrop_prev,logist_settings); % [v] = FindMultiWindowWeights_v1p2(alldata,truth,trainingwindowoffset,pt,priortimes,vinit,logist_settings); % % TEMP DEBUG % [~,iMax] = max(pt,[],2); % jitters = priortimes(iMax); % [v1] = FindMultiWindowWeights_v1p1(alldata,truth,trainingwindowoffset,jitters,vCrop_prev,logist_settings); % if isequalwithequalnans(v,v1) % disp('WEIGHTS OK!'); % end [pt,pvals] = computeJitterProbabilities_v1p2(x,v,truth,ptprior,forceOneWinner); % [pt,pvals] = computeJitterProbabilities_v1p2(x,v,ones(size(truth)),ptprior,forceOneWinner); % % TEMP DEBUG % [pt1,pvals1] = computeJitterProbabilities_v1p1(x,v,truth,ptprior,forceOneWinner); % if isequal(pt1,pt) % disp('POST OK!'); % end Az = rocarea(pvals,truth); % Update vCrop and jitters isinwin = ~isnan(v(1,:)); vCrop = v(:,isinwin); % draw debug figures if plotdebugfigs PlotDebugFigures(iter,vCrop,pt,jitterrange,trainingwindowoffset,ALLEEG); end % Print text output fprintf('Az = %.3g, subspace = %.3g\n', Az, subspace(vCrop,vCrop_prev) ); end fprintf('Converged! Preparing output...\n'); vOut = vCrop; fmOut = vCrop(1:end-1,:); % TO DO: define this! fprintf('Done.\n'); end % function pop_logisticregression_jittered %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTIONS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function PlotDebugFigures(iter,vCrop,pt,priorrange,trainingwindowoffset,ALLEEG) % Set up nRows = 2; nCols = 2; iPlot = mod(iter,nRows*nCols)+1; [jitter_truth,truth_trials] = GetJitter(ALLEEG,'facecar'); n1 = ALLEEG(1).trials; n2 = ALLEEG(2).trials; % Initialize figures figures = 111:113; if iter==0 for iFig = figures figure(iFig); clf; end end % Plot v figure(figures(1)); nWindows = size(vCrop,2); for iWin=1:nWindows subplot(nRows*nCols,nWindows,nWindows*(iPlot-1)+iWin); cla; topoplot(vCrop(1:end-1,iWin),ALLEEG(2).chanlocs); title(sprintf('iter %d weight vector (raw)\n (bias = %0.2g)(t=%gs)',iter,vCrop(end,iWin),ALLEEG(1).times(trainingwindowoffset(iWin)))) colorbar; end % Plot posteriors figure(figures(2)); subplot(nRows,nCols,iPlot); cla; hold on; priortimes = (priorrange(1)+1):priorrange(2); [~,order1] = ImageSortedData(pt(1:n1,:),priorrange,1:n1,jitter_truth(1:n1)); colorbar; [~,order2] = ImageSortedData(pt(n1+1:end,:),priorrange,n1+(1:n2),jitter_truth(n1+1:end)); colorbar; [~,iMax] = max(pt([order1,n1+order2],:),[],2); jitters = priortimes(iMax); scatter(jitters,1:(n1+n2),'m.'); title(sprintf('iter %d Posteriors',iter)); axis([min(priorrange) max(priorrange) 1 n1+n2]) xlabel('Jitter (samples)'); if iter==0 title(sprintf('Priors p(t_i,c_i)')) end ylabel('Trial'); % Plot MAP jitter vs. posterior at that jitter figure(figures(3)); subplot(nRows,nCols,iPlot); cla; hold on; [~,maxinds] = max(pt,[],2); locs = find(truth_trials==0)'; scatter(priortimes(maxinds(locs)),pt(sub2ind(size(pt),locs,maxinds(locs))),50,'blue','filled'); locs = find(truth_trials==1)'; scatter(priortimes(maxinds(locs)),pt(sub2ind(size(pt),locs,maxinds(locs))),50,'red','filled'); if priorrange(2)>priorrange(1) xlim([priorrange(1),priorrange(2)]); end title(sprintf('iter %d MAP jitter',iter)); legend('MAP jitter values (l=0)','MAP jitter values (l=1)','Location','Best'); xlabel('Jitter (samples)'); ylabel('Posterior at that jitter'); drawnow; end
github
djangraw/FelixScripts-master
SetUpMultiWindowJlr_v1p3.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/MultiWindow/Unfinished_v1p3/SetUpMultiWindowJlr_v1p3.m
7,464
utf_8
1f09490f9076a27e92c77fb9f4423a80
function [vOut,fmOut] = SetUpMultiWindowJlr_v1p3(ALLEEG, trainingwindowlength, trainingwindowoffset, vinit, jitterPrior, pop_settings, logist_settings) % [vOut] = SetUpMultiWindowJlr_v1p3(ALLEEG, trainingwindowlength, trainingwindowoffset, vinit, pop_settings, logist_settings) % % INPUTS: % -ALLEEG is 1x2, each with D electrodes % -trainingwindowlength is a scalar % -trainingwindowoffset is 1xP % -vinit is DxP % -pop_settings is a struct % -logist_settings is a struct % % OUTPUTS: % -vOut is DxP % % Created 12/11/12 by DJ. % Updated 12/18/12 by DJ - v1p1 (computeJitterProbabilities has corrected % posterior size, p values) % Updated 12/19/12 by DJ - v1p2 (soft EM) % Updated 12/28/12 by DJ - fmOut size correction % Updated 1/8/13 by DJ - v1p3 (reward c'=c and penalize c'=-c) plotdebugfigs = false; vinit(vinit==0) = vinit(vinit==0)+1e-100; % Unpack options UnpackStruct(pop_settings); % convergencethreshold,jitterrange,weightprior,forceOneWinner,conditionPrior UnpackStruct(logist_settings); % eigvalratio,lambda,lambdasearch,regularize,useOffset % Set up truth labels (one for each data sample in the window on each trial ntrials1 = ALLEEG(1).trials; ntrials2 = ALLEEG(2).trials; % Extract data raweeg1 = ALLEEG(1).data(:,:,:); raweeg2 = ALLEEG(2).data(:,:,:); % Smooth data smootheeg1 = nan(size(raweeg1,1),size(raweeg1,2)-trainingwindowlength+1, size(raweeg1,3)); smootheeg2 = nan(size(raweeg2,1),size(raweeg2,2)-trainingwindowlength+1, size(raweeg2,3)); for i=1:size(raweeg1,3) smootheeg1(:,:,i) = conv2(raweeg1(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end for i=1:size(raweeg2,3) smootheeg2(:,:,i) = conv2(raweeg2(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end % Get prior [ptprior,priortimes] = jitterPrior.fn((1000/ALLEEG(1).srate)*((jitterrange(1)+1):jitterrange(2)),jitterPrior.params); % Make prior into a matrix and normalize rows if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = repmat(ptprior,ntrials1+ntrials2,1); end ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); % Ensure the rows sum to 1 % Re-weight priors according to the number of trials in each class if weightprior ptprior(truth_trials==1,:) = ptprior(truth_trials==1,:) / sum(truth_trials==1); ptprior(truth_trials==0,:) = ptprior(truth_trials==0,:) / sum(truth_trials==0); end % Make the prior the initial condition for the posteriors pt = ptprior; if forceOneWinner % Get posteriors [~,iMax] = max(pt,[],2); pt = full(sparse(1:length(iMax),iMax,1,size(pt,1),size(pt,2))); % all zeros except at max points end pt2 = pt; % [~,iMax] = max(pt,[],2); % jitters = priortimes(iMax); % Get data and truth matrices alldata = cat(3,smootheeg1,smootheeg2); truth = [zeros(ntrials1,1); ones(ntrials2,1)]; % The truth value associated with each trial % Get data across windows & jitters iWindow = (min(trainingwindowoffset)+min(jitterrange)):(max(trainingwindowoffset)+max(jitterrange)); x = alldata(:,iWindow,:); x(end+1,:,:) = 1; % add for offset usage % Set up for loop vCrop = vinit; vCrop_prev = vCrop; % priortimes = (jitterrange(1)+1):jitterrange(2); % pt = zeros(ntrials1+ntrials2,length(priortimes)); % jitters = zeros(1,ntrials1+ntrials2); iter = 0; % draw debug figures if plotdebugfigs PlotDebugFigures(iter,vCrop,pt,jitterrange,trainingwindowoffset,ALLEEG); end %%% MAIN LOOP %%% while iter==0 || (subspace(vCrop,vCrop_prev)>convergencethreshold && iter<max_iter) iter = iter+1; fprintf('Iteration %d...\n',iter); vCrop_prev = vCrop; if iter==1 [v] = FindMultiWindowWeights_v1p2(alldata,truth,trainingwindowoffset,pt,priortimes,vCrop_prev,logist_settings); else [v] = FindMultiWindowWeights_v1p2(cat(3,alldata,alldata), [truth; truth], trainingwindowoffset, cat(1,pt,pt2), priortimes, vCrop_prev, logist_settings); end [pt,pvals] = computeJitterProbabilities_v1p2(x,v,truth,ptprior,forceOneWinner); [pt2,pvals2] = computeJitterProbabilities_v1p2(x,v,1-truth,ptprior,forceOneWinner); Az = rocarea(pvals,truth); % Update vCrop and jitters isinwin = ~isnan(v(1,:)); vCrop = v(:,isinwin); % draw debug figures if plotdebugfigs PlotDebugFigures(2*iter,vCrop,pt,jitterrange,trainingwindowoffset,ALLEEG); PlotDebugFigures(2*iter+1,vCrop,pt2,jitterrange,trainingwindowoffset,ALLEEG); % PlotDebugFigures(iter,vCrop,cat(1,pt,pt2),jitterrange,trainingwindowoffset,ALLEEG); end % Print text output fprintf('Az = %.3g, subspace = %.3g\n', Az, subspace(vCrop,vCrop_prev) ); end fprintf('Converged! Preparing output...\n'); vOut = vCrop; fmOut = vCrop(1:end-1,:); % TO DO: define this! fprintf('Done.\n'); end % function pop_logisticregression_jittered %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTIONS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function PlotDebugFigures(iter,vCrop,pt,priorrange,trainingwindowoffset,ALLEEG) % Set up nRows = 2; nCols = 2; iPlot = mod(iter,nRows*nCols)+1; [jitter_truth,truth_trials] = GetJitter(ALLEEG,'facecar'); n1 = ALLEEG(1).trials; n2 = ALLEEG(2).trials; % Initialize figures figures = 111:113; if iter==0 for iFig = figures figure(iFig); clf; end end % Plot v figure(figures(1)); nWindows = size(vCrop,2); for iWin=1:nWindows subplot(nRows*nCols,nWindows,nWindows*(iPlot-1)+iWin); cla; topoplot(vCrop(1:end-1,iWin),ALLEEG(2).chanlocs); title(sprintf('iter %d weight vector (raw)\n (bias = %0.2g)(t=%gs)',iter,vCrop(end,iWin),ALLEEG(1).times(trainingwindowoffset(iWin)))) colorbar; end % Plot posteriors figure(figures(2)); subplot(nRows,nCols,iPlot); cla; hold on; priortimes = (priorrange(1)+1):priorrange(2); [~,order1] = ImageSortedData(pt(1:n1,:),priorrange,1:n1,jitter_truth(1:n1)); colorbar; [~,order2] = ImageSortedData(pt(n1+1:end,:),priorrange,n1+(1:n2),jitter_truth(n1+1:end)); colorbar; [~,iMax] = max(pt([order1,n1+order2],:),[],2); jitters = priortimes(iMax); scatter(jitters,1:(n1+n2),'m.'); title(sprintf('iter %d Posteriors',iter)); axis([min(priorrange) max(priorrange) 1 n1+n2]) xlabel('Jitter (samples)'); if iter==0 title(sprintf('Priors p(t_i,c_i)')) end ylabel('Trial'); % Plot MAP jitter vs. posterior at that jitter figure(figures(3)); subplot(nRows,nCols,iPlot); cla; hold on; [~,maxinds] = max(pt,[],2); locs = find(truth_trials==0)'; scatter(priortimes(maxinds(locs)),pt(sub2ind(size(pt),locs,maxinds(locs))),50,'blue','filled'); locs = find(truth_trials==1)'; scatter(priortimes(maxinds(locs)),pt(sub2ind(size(pt),locs,maxinds(locs))),50,'red','filled'); if priorrange(2)>priorrange(1) xlim([priorrange(1),priorrange(2)]); end title(sprintf('iter %d MAP jitter',iter)); legend('MAP jitter values (l=0)','MAP jitter values (l=1)','Location','Best'); xlabel('Jitter (samples)'); ylabel('Posterior at that jitter'); drawnow; end
github
djangraw/FelixScripts-master
run_logisticregression_jittered_EM_gaussian.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/run_logisticregression_jittered_EM_gaussian.m
13,213
utf_8
99f7596b5bc1c59e5e580eca6862e26e
function run_logisticregression_jittered_EM_gaussian(outDirName,ALLEEG,setlist, chansubset, scope_settings, pop_settings, logist_settings) % Perform logistic regression with trial jitter on a dataset. % % % [ALLEEG,v,Azloo,time] = run_logisticregression_jittered_EM_gaussian( % outDirName,ALLEEG,setlist,chansubset,scope_settings,pop_settings, % logist_settings) % % INPUTS: % -outDirName: a string specifying where results are to be saved (DEFAULT: './results/') % -ALLEEG is an array of EEGlab data structures % -setlist is a 2-element vector of the ALLEEG indices you wish to discriminate % -chansubset is a d-element array of the channel numbers you wish to use for discrimination % (DEFAULT: [] -- use all channels) % -trainingwindowlength is the number of samples that are in the training window % -trainingwindowinterval is the number of samples by which you want to slide your training window each time % -jitterrange specifies the minimum and maximum % -reactionTimes1 and reactionTimes2 are the times in ms... % -convergencethreshold % -cvmode is a string specifying what type of cross-validation to run. Can be: % 'nocrossval' - run full model (no cross-validation) % 'loo' - run leave-one-out cross-validation % 'XXfold', where XX is an integer, will run XX-fold cross-validation % (DEFAULT: '10fold') % -weightprior is a boolean % % % OUTPUTS: % -ALLEEG is the input array, but with info about the analysis stored in % the ica-related fields of the datasets in setlist. Specifically, % EEG.icawinv contains the forward model across all datasets. % EEG.icaweights contains the weight vector v (with no bias term). % -v is the weight vector from the training data (the first d are spatial % weights, and the last element is the bias.) Negative values of % y=x*v(1:end-1) + v(end) indicate that the sample is part of setlist(1)'s % class. Positive values indicate setlist(2)'s class. % -Azloo and time are vectors of the leave-one-out Az values and the center % of the time bin (in ms from setlist(1)'s time zero) at which they were % calculated. % % Created 5/12/11 by BC. % Updated 8/3/11 by BC - include x-fold cross-validation % Updated 9/14/11 by DJ - made sure fwd models are saved % Updated 9/20/11 by DJ - pass pop_settings struct to test function % Updated 9/21/11 by DJ - switched to settings structs % Updated 10/26/11 by DJ - fixed jitterprior bug % Updated 12/13/11 by DJ - made plotting optional %% ****************************************************************************************** %% Set up % if ~exist('outDirName','var') || isempty(outDirName); outDirName = './results/'; end; % if ~exist('setlist','var'); setlist = [1,2]; end; % if ~exist('chansubset','var'); chansubset = []; end; % if ~exist('trainingwindowlength','var'); trainingwindowlength = []; end; % if ~exist('trainingwindowinterval','var'); trainingwindowinterval = []; end; % if ~exist('jitterrange','var'); jitterrange = []; end; % if ~exist('convergencethreshold','var'); convergencethreshold = []; end; % if ~exist('cvmode','var'); cvmode = '10fold'; end; % if ~exist('weightprior','var'); weightprior = 1; end; UnpackStruct(scope_settings); % jitterrange, trainingwindowlength/interval/range, parallel, cvmode, convergencethreshold % There may be other loaded EEG datasets, so let's save some memory and only keep the ones we need ALLEEG = ALLEEG(setlist); setlist = [1 2]; % Start -500ms and end +500ms relative to stimulus onset loc1 = find(ALLEEG(setlist(1)).times <= trainingwindowrange(1), 1, 'last' ); loc2 = find(ALLEEG(setlist(1)).times >= trainingwindowrange(2), 1 ); loc1 = loc1 - floor(trainingwindowlength/2); loc2 = loc2 - floor(trainingwindowlength/2); trainingwindowoffset = loc1 : trainingwindowinterval : loc2; %1-jitterrange(1) : trainingwindowinterval : ALLEEG(1).pnts-trainingwindowlength-jitterrange(2); % trainingwindowoffset = 245;%190;%264; iMidTimes = trainingwindowoffset + floor(trainingwindowlength/2); % middle of time window time = ALLEEG(setlist(1)).times(iMidTimes)*0.001; % crop and convert to seconds % Set parameters vinit = zeros(length(chansubset)+1,1); % Set up prior struct jitterPrior = []; jitterPrior.fn = @computeJitterPrior_gaussian; jitterPrior.params = []; jitterPrior.params.mu = jitter_mu; jitterPrior.params.sigma = jitter_sigma; jitterPrior.params.nTrials = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; [~,priortimes] = jitterPrior.fn((1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); nPrior = numel(priortimes); % Save parameters if ~isdir(outDirName); mkdir(outDirName); end; tic; N1 = ALLEEG(setlist(1)).trials; N2 = ALLEEG(setlist(2)).trials; N = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; cv = setGroupedCrossValidationStruct(cvmode,ALLEEG(setlist(1)),ALLEEG(setlist(2))); save([outDirName,'/params_',cvmode,'.mat'], 'ALLEEG','setlist','cv','chansubset','trainingwindowoffset','scope_settings','pop_settings','logist_settings'); % save([outDirName,'/params_',cvmode,'.mat'], 'ALLEEG','setlist','cv','chansubset','trainingwindowlength', 'trainingwindowinterval', 'jitterrange', 'reactionTimes1', 'reactionTimes2', 'convergencethreshold', 'cvmode','weightprior'); poolsize = min(15,cv.numFolds); % 15 for einstein, 4 for local if poolsize == 1; parallel = 0; end; if parallel == 1 warning('Make sure you run pctconfig(''hostname'', ''ip'')'); mls = matlabpool('size'); if mls > 0; matlabpool close; end; matlabpool('open',poolsize); % declare some variables trainingwindowlength = trainingwindowlength; end ps = cell(cv.numFolds,1); posts = cell(cv.numFolds,1); posts2 = cell(cv.numFolds,1); vout = cell(cv.numFolds,1); testsample = cell(cv.numFolds,1); jitterPriorLoop = cell(cv.numFolds,1); for j=1:cv.numFolds; jitterPriorLoop{j} = jitterPrior; end; jitterPriorTest = cell(cv.numFolds,1); for j=1:cv.numFolds; jitterPriorTest{j} = jitterPrior; end; fwdmodels = cell(cv.numFolds,1); foldALLEEG = cell(cv.numFolds,1); pop_settings_out = cell(cv.numFolds,1); if parallel == 1 parfor foldNum = 1:cv.numFolds % PARFOR! disp(['Running fold #',num2str(foldNum),' out of ',num2str(cv.numFolds)]);pause(1e-9); foldALLEEG{foldNum}(1) = ALLEEG(setlist(1)); foldALLEEG{foldNum}(2) = ALLEEG(setlist(2)); foldALLEEG{foldNum}(1).data = foldALLEEG{foldNum}(1).data(:,:,cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).epoch = foldALLEEG{foldNum}(1).epoch(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).trials = length(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(2).data = foldALLEEG{foldNum}(2).data(:,:,cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).epoch = foldALLEEG{foldNum}(2).epoch(cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).trials = length(cv.incTrials2{foldNum}); jitterPriorLoop{foldNum}.params.nTrials = length(cv.incTrials1{foldNum}) + length(cv.incTrials2{foldNum}); testsample{foldNum} = cat(3,ALLEEG(setlist(1)).data(:,:,cv.valTrials1{foldNum}), ALLEEG(setlist(2)).data(:,:,cv.valTrials2{foldNum})); jitterPriorTest{foldNum}.params.nTrials = 1; % test one sample at a time [ALLEEGout,~,vout{foldNum}] = pop_logisticregression_jittered_EM(foldALLEEG{foldNum},[1 2],chansubset,trainingwindowlength,trainingwindowoffset,vinit,jitterPriorLoop{foldNum},pop_settings,logist_settings); fwdmodels{foldNum} = ALLEEGout(setlist(1)).icawinv; ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); posts{foldNum} = zeros(size(testsample{foldNum},3),nPrior,length(trainingwindowoffset)); posts2{foldNum} = zeros(size(testsample{foldNum},3),nPrior,length(trainingwindowoffset)); for k=1:size(testsample{foldNum},3) [ps{foldNum}(k,:), thisPost, thisPost2] = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate,ALLEEGout(setlist(1)).etc.pop_settings); posts{foldNum}(k,:,:) = permute(thisPost,[3 2 1]); posts2{foldNum}(k,:,:) = permute(thisPost2,[3 2 1]); end pop_settings_out{foldNum} = ALLEEGout(setlist(1)).etc.pop_settings; % ps{foldNum} = runTest(testsample{foldNum},trainingwindowlength,trainingwindowoffset,jitterrange,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate); end else for foldNum = 1:cv.numFolds disp(['Running fold #',num2str(foldNum),' out of ',num2str(cv.numFolds)]);pause(1e-9); foldALLEEG{foldNum}(1) = ALLEEG(setlist(1)); foldALLEEG{foldNum}(2) = ALLEEG(setlist(2)); foldALLEEG{foldNum}(1).data = foldALLEEG{foldNum}(1).data(:,:,cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).epoch = foldALLEEG{foldNum}(1).epoch(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).trials = length(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(2).data = foldALLEEG{foldNum}(2).data(:,:,cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).epoch = foldALLEEG{foldNum}(2).epoch(cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).trials = length(cv.incTrials2{foldNum}); jitterPriorLoop{foldNum}.params.nTrials = length(cv.incTrials1{foldNum}) + length(cv.incTrials2{foldNum}); testsample{foldNum} = cat(3,ALLEEG(setlist(1)).data(:,:,cv.valTrials1{foldNum}), ALLEEG(setlist(2)).data(:,:,cv.valTrials2{foldNum})); jitterPriorTest{foldNum}.params.nTrials = 1; % test one sample at a time [ALLEEGout,~,vout{foldNum}] = pop_logisticregression_jittered_EM(foldALLEEG{foldNum},[1 2],chansubset,trainingwindowlength,trainingwindowoffset,vinit,jitterPriorLoop{foldNum},pop_settings,logist_settings); fwdmodels{foldNum} = ALLEEGout(setlist(1)).icawinv; ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); posts{foldNum} = zeros(size(testsample{foldNum},3),nPrior,length(trainingwindowoffset)); posts2{foldNum} = zeros(size(testsample{foldNum},3),nPrior,length(trainingwindowoffset)); for k=1:size(testsample{foldNum},3) [ps{foldNum}(k,:), thisPost, thisPost2] = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate,ALLEEGout(setlist(1)).etc.pop_settings); posts{foldNum}(k,:,:) = permute(thisPost,[3 2 1]); posts2{foldNum}(k,:,:) = permute(thisPost2,[3 2 1]); end % ps{foldNum} = runTest(testsample{foldNum},trainingwindowlength,trainingwindowoffset,jitterrange,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate); pop_settings_out{foldNum} = ALLEEGout(setlist(1)).etc.pop_settings; end end pop_settings_out = [pop_settings_out{:}]'; % convert from cells to struct array p = zeros(N,length(trainingwindowoffset)); posterior = zeros(N,nPrior,length(trainingwindowoffset)); posterior2 = zeros(N,nPrior,length(trainingwindowoffset)); for foldNum=1:cv.numFolds p([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:) = ps{foldNum}; posterior([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:,:) = posts{foldNum}; posterior2([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:,:) = posts2{foldNum}; end truth = [zeros(ALLEEG(setlist(1)).trials,1);ones(ALLEEG(setlist(2)).trials,1)]; for wini = 1:length(trainingwindowoffset) [Azloo(wini),Ryloo,Rxloo] = rocarea(p(:,wini),truth); fprintf('Window Onset: %d; LOO Az: %6.2f\n',trainingwindowoffset(wini),Azloo(wini)); end t = toc; %fwdmodel = ALLEEG(setlist(1)).icawinv; % forward model, defined in pop_logisticregression as a=y\x. if ~isdir(outDirName); mkdir(outDirName); end; save([outDirName,'/results_',cvmode,'.mat'],'vout','testsample','trainingwindowlength','truth','trainingwindowoffset','p','Azloo','t','fwdmodels','jitterPriorTest','pop_settings_out','posterior','posterior2'); %% Plot LOO Results plotAz = 0; if plotAz figure; hold on; plot(time,Azloo); plot(get(gca,'XLim'),[0.5 0.5],'k--'); plot(get(gca,'XLim'),[0.75 0.75],'k:'); ylim([0.3 1]); title('Cross-validation analysis'); xlabel('time (s)'); ylabel([cvmode ' Az']); end mls = matlabpool('size'); if mls > 0; matlabpool close; end; end %% ****************************************************************************************** %% ****************************************************************************************** function [p, posterior,posterior2] = runTest(testsample,trainingwindowlength,trainingwindowoffset,vout,jitterPrior,srate,pop_settings) p = zeros(1,length(trainingwindowoffset)); post = cell(1,length(trainingwindowoffset)); post2 = cell(1,length(trainingwindowoffset)); for wini = 1:length(trainingwindowoffset) [p(wini),post{wini},~,post2{wini}] = test_logisticregression_jittered_EM(testsample,trainingwindowlength,trainingwindowoffset(wini),vout(wini,:),jitterPrior,srate,pop_settings); % p(wini)=bernoull(1,y(wini)); end posterior = cat(1,post{:}); posterior2 = cat(1,post2{:}); end %% ******************************************************************************************
github
djangraw/FelixScripts-master
run_logisticregression_jittered_EM_oddball.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/run_logisticregression_jittered_EM_oddball.m
11,802
utf_8
225039a4fe8e7f7b10dadf5d467f5b89
function run_logisticregression_jittered_EM_oddball(outDirName,ALLEEG,setlist, chansubset, scope_settings, pop_settings, logist_settings) % Perform logistic regression with trial jitter on a dataset. % % % [ALLEEG,v,Azloo,time] = run_logisticregression_jittered_EM_oddball( % outDirName,ALLEEG,setlist,chansubset,scope_settings,pop_settings, % logist_settings) % % INPUTS: % -outDirName: a string specifying where results are to be saved (DEFAULT: './results/') % -ALLEEG is an array of EEGlab data structures % -setlist is a 2-element vector of the ALLEEG indices you wish to discriminate % -chansubset is a d-element array of the channel numbers you wish to use for discrimination % (DEFAULT: [] -- use all channels) % -trainingwindowlength is the number of samples that are in the training window % -trainingwindowinterval is the number of samples by which you want to slide your training window each time % -jitterrange specifies the minimum and maximum % -reactionTimes1 and reactionTimes2 are the times in ms... % -convergencethreshold % -cvmode is a string specifying what type of cross-validation to run. Can be: % 'nocrossval' - run full model (no cross-validation) % 'loo' - run leave-one-out cross-validation % 'XXfold', where XX is an integer, will run XX-fold cross-validation % (DEFAULT: '10fold') % -weightprior is a boolean % % % OUTPUTS: % -ALLEEG is the input array, but with info about the analysis stored in % the ica-related fields of the datasets in setlist. Specifically, % EEG.icawinv contains the forward model across all datasets. % EEG.icaweights contains the weight vector v (with no bias term). % -v is the weight vector from the training data (the first d are spatial % weights, and the last element is the bias.) Negative values of % y=x*v(1:end-1) + v(end) indicate that the sample is part of setlist(1)'s % class. Positive values indicate setlist(2)'s class. % -Azloo and time are vectors of the leave-one-out Az values and the center % of the time bin (in ms from setlist(1)'s time zero) at which they were % calculated. % % Created 5/12/11 by BC. % Updated 8/3/11 by BC - include x-fold cross-validation % Updated 9/14/11 by DJ - made sure fwd models are saved % Updated 9/20/11 by DJ - pass pop_settings struct to test function % Updated 9/21/11 by DJ - switched to settings structs % Updated 10/26/11 by DJ - fixed jitterprior bug % Updated 12/13/11 by DJ - made plotting optional %% ****************************************************************************************** %% Set up % if ~exist('outDirName','var') || isempty(outDirName); outDirName = './results/'; end; % if ~exist('setlist','var'); setlist = [1,2]; end; % if ~exist('chansubset','var'); chansubset = []; end; % if ~exist('trainingwindowlength','var'); trainingwindowlength = []; end; % if ~exist('trainingwindowinterval','var'); trainingwindowinterval = []; end; % if ~exist('jitterrange','var'); jitterrange = []; end; % if ~exist('convergencethreshold','var'); convergencethreshold = []; end; % if ~exist('cvmode','var'); cvmode = '10fold'; end; % if ~exist('weightprior','var'); weightprior = 1; end; UnpackStruct(scope_settings); % jitterrange, trainingwindowlength/interval/range, parallel, cvmode, convergencethreshold % There may be other loaded EEG datasets, so let's save some memory and only keep the ones we need ALLEEG = ALLEEG(setlist); setlist = [1 2]; % Start -500ms and end +500ms relative to stimulus onset loc1 = find(ALLEEG(setlist(1)).times <= trainingwindowrange(1), 1, 'last' ); loc2 = find(ALLEEG(setlist(1)).times >= trainingwindowrange(2), 1 ); loc1 = loc1 - floor(trainingwindowlength/2); loc2 = loc2 - floor(trainingwindowlength/2); trainingwindowoffset = loc1 : trainingwindowinterval : loc2; %1-jitterrange(1) : trainingwindowinterval : ALLEEG(1).pnts-trainingwindowlength-jitterrange(2); % trainingwindowoffset = 245;%190;%264; iMidTimes = trainingwindowoffset + floor(trainingwindowlength/2); % middle of time window time = ALLEEG(setlist(1)).times(iMidTimes)*0.001; % crop and convert to seconds % Set parameters vinit = zeros(length(chansubset)+1,1); % Set up prior struct jitterPrior = []; jitterPrior.fn = @computeJitterPrior_uniform; jitterPrior.params = []; jitterPrior.params.range = jitterrange; jitterPrior.params.nTrials = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; % Save parameters if ~isdir(outDirName); mkdir(outDirName); end; tic; N1 = ALLEEG(setlist(1)).trials; N2 = ALLEEG(setlist(2)).trials; N = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; cv = setGroupedCrossValidationStruct(cvmode,ALLEEG(setlist(1)),ALLEEG(setlist(2))); save([outDirName,'/params_',cvmode,'.mat'], 'ALLEEG','setlist','cv','chansubset','trainingwindowoffset','scope_settings','pop_settings','logist_settings'); % save([outDirName,'/params_',cvmode,'.mat'], 'ALLEEG','setlist','cv','chansubset','trainingwindowlength', 'trainingwindowinterval', 'jitterrange', 'reactionTimes1', 'reactionTimes2', 'convergencethreshold', 'cvmode','weightprior'); poolsize = min(15,cv.numFolds); % 15 for einstein, 4 for local if poolsize == 1; parallel = 0; end; if parallel == 1 warning('Make sure you run pctconfig(''hostname'', ''ip'')'); mls = matlabpool('size'); if mls > 0; matlabpool close; end; matlabpool('open',poolsize); % declare some variables trainingwindowlength = trainingwindowlength; end ps = cell(cv.numFolds,1); vout = cell(cv.numFolds,1); testsample = cell(cv.numFolds,1); jitterPriorLoop = cell(cv.numFolds,1); for j=1:cv.numFolds; jitterPriorLoop{j} = jitterPrior; end; jitterPriorTest = cell(cv.numFolds,1); for j=1:cv.numFolds; jitterPriorTest{j} = jitterPrior; end; fwdmodels = cell(cv.numFolds,1); foldALLEEG = cell(cv.numFolds,1); pop_settings_out = cell(cv.numFolds,1); if parallel == 1 parfor foldNum = 1:cv.numFolds % PARFOR! disp(['Running fold #',num2str(foldNum),' out of ',num2str(cv.numFolds)]);pause(1e-9); foldALLEEG{foldNum}(1) = ALLEEG(setlist(1)); foldALLEEG{foldNum}(2) = ALLEEG(setlist(2)); foldALLEEG{foldNum}(1).data = foldALLEEG{foldNum}(1).data(:,:,cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).epoch = foldALLEEG{foldNum}(1).epoch(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).trials = length(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(2).data = foldALLEEG{foldNum}(2).data(:,:,cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).epoch = foldALLEEG{foldNum}(2).epoch(cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).trials = length(cv.incTrials2{foldNum}); jitterPriorLoop{foldNum}.params.nTrials = length(cv.incTrials1{foldNum}) + length(cv.incTrials2{foldNum}); testsample{foldNum} = cat(3,ALLEEG(setlist(1)).data(:,:,cv.valTrials1{foldNum}), ALLEEG(setlist(2)).data(:,:,cv.valTrials2{foldNum})); jitterPriorTest{foldNum}.params.nTrials = 1; % test one sample at a time [ALLEEGout,~,vout{foldNum}] = pop_logisticregression_jittered_EM(foldALLEEG{foldNum},[1 2],chansubset,trainingwindowlength,trainingwindowoffset,vinit,jitterPriorLoop{foldNum},pop_settings,logist_settings); fwdmodels{foldNum} = ALLEEGout(setlist(1)).icawinv; ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); for k=1:size(testsample{foldNum},3) ps{foldNum}(k,:) = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate,ALLEEGout(setlist(1)).etc.pop_settings); end pop_settings_out{foldNum} = ALLEEGout(setlist(1)).etc.pop_settings; % ps{foldNum} = runTest(testsample{foldNum},trainingwindowlength,trainingwindowoffset,jitterrange,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate); end else for foldNum = 1:cv.numFolds disp(['Running fold #',num2str(foldNum),' out of ',num2str(cv.numFolds)]);pause(1e-9); foldALLEEG{foldNum}(1) = ALLEEG(setlist(1)); foldALLEEG{foldNum}(2) = ALLEEG(setlist(2)); foldALLEEG{foldNum}(1).data = foldALLEEG{foldNum}(1).data(:,:,cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).epoch = foldALLEEG{foldNum}(1).epoch(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(1).trials = length(cv.incTrials1{foldNum}); foldALLEEG{foldNum}(2).data = foldALLEEG{foldNum}(2).data(:,:,cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).epoch = foldALLEEG{foldNum}(2).epoch(cv.incTrials2{foldNum}); foldALLEEG{foldNum}(2).trials = length(cv.incTrials2{foldNum}); jitterPriorLoop{foldNum}.params.nTrials = length(cv.incTrials1{foldNum}) + length(cv.incTrials2{foldNum}); testsample{foldNum} = cat(3,ALLEEG(setlist(1)).data(:,:,cv.valTrials1{foldNum}), ALLEEG(setlist(2)).data(:,:,cv.valTrials2{foldNum})); jitterPriorTest{foldNum}.params.nTrials = 1; % test one sample at a time [ALLEEGout,~,vout{foldNum}] = pop_logisticregression_jittered_EM(foldALLEEG{foldNum},[1 2],chansubset,trainingwindowlength,trainingwindowoffset,vinit,jitterPriorLoop{foldNum},pop_settings,logist_settings); fwdmodels{foldNum} = ALLEEGout(setlist(1)).icawinv; ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); for k=1:size(testsample{foldNum},3) ps{foldNum}(k,:) = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate,ALLEEGout(setlist(1)).etc.pop_settings); end % ps{foldNum} = runTest(testsample{foldNum},trainingwindowlength,trainingwindowoffset,jitterrange,vout{foldNum},jitterPriorTest{foldNum},ALLEEG(setlist(1)).srate); pop_settings_out{foldNum} = ALLEEGout(setlist(1)).etc.pop_settings; end end pop_settings_out = [pop_settings_out{:}]'; % convert from cells to struct array p = zeros(N,length(trainingwindowoffset)); for foldNum=1:cv.numFolds p([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:) = ps{foldNum}; end truth = [zeros(ALLEEG(setlist(1)).trials,1);ones(ALLEEG(setlist(2)).trials,1)]; for wini = 1:length(trainingwindowoffset) [Azloo(wini),Ryloo,Rxloo] = rocarea(p(:,wini),truth); fprintf('Window Onset: %d; LOO Az: %6.2f\n',trainingwindowoffset(wini),Azloo(wini)); end t = toc; %fwdmodel = ALLEEG(setlist(1)).icawinv; % forward model, defined in pop_logisticregression as a=y\x. if ~isdir(outDirName); mkdir(outDirName); end; save([outDirName,'/results_',cvmode,'.mat'],'vout','testsample','trainingwindowlength','truth','trainingwindowoffset','p','Azloo','t','fwdmodels','jitterPriorTest','pop_settings_out'); %% Plot LOO Results plotAz = 0; if plotAz figure; hold on; plot(time,Azloo); plot(get(gca,'XLim'),[0.5 0.5],'k--'); plot(get(gca,'XLim'),[0.75 0.75],'k:'); ylim([0.3 1]); title('Cross-validation analysis'); xlabel('time (s)'); ylabel([cvmode ' Az']); end mls = matlabpool('size'); if mls > 0; matlabpool close; end; end %% ****************************************************************************************** %% ****************************************************************************************** function [p,posterior] = runTest(testsample,trainingwindowlength,trainingwindowoffset,vout,jitterPrior,srate,pop_settings) p = zeros(1,length(trainingwindowoffset)); posterior = cell(1,length(trainingwindowoffset)); for wini = 1:length(trainingwindowoffset) [p(wini), posterior{wini}] = test_logisticregression_jittered_EM(testsample,trainingwindowlength,trainingwindowoffset(wini),vout(wini,:),jitterPrior,srate,pop_settings); % p(wini)=bernoull(1,y(wini)); end end %% ******************************************************************************************
github
djangraw/FelixScripts-master
GetFinalPosteriors_gaussian.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/GetFinalPosteriors_gaussian.m
6,840
utf_8
ff8fae23f29e568b7ae2fbdb5f5b5811
function [pt, truth_trials, times, jitter] = GetFinalPosteriors_gaussian(foldername,cvmode,subject) % Put the posterior distributions of jittered logistic regression results % into a cell array. % % pt = GetFinalPosteriors_gaussian(foldername,cvmode,subject) % % INPUTS: % -foldername is a string indicating the folder in which the JLR results % reside. % -cvmode is a string indicating the cross-validation mode you used (e.g., % '10fold','loo'). % -subject is a string indicating the subject id name/number. % % OUTPUTS: % -pt is a cell array of matrices containing the posterior distributions % over time. Indices of pt are {LOOtrial, time}, indices of pt{i,j} are % [trial, TrainingWindowOffset]. % % Created 8/16/12 by DJ based on GetFinalPosteriors.mat % Updated 8/20/12 by DJ - made specific to facecar data % load results load([foldername '/results_' cvmode '.mat']); % Azloo, jitterrange, p, testsample, trainingwindowlength, trainingwindowoffset, truth, vout, pop_settings_out % Load data for given subject % [ALLEEG,~,setlist] = loadSubjectData_oddball(subject); % eeg info and saccade info [ALLEEG,~,setlist] = loadSubjectData_facecar(subject); % eeg info and saccade info % Response-lock data RT1 = getRT(ALLEEG(setlist(1)),'RT');%,200); RT2 = getRT(ALLEEG(setlist(2)),'RT');%,150); tWindow(1) = (ALLEEG(setlist(1)).times(1) - min([RT1 RT2]))/1000; tWindow(2) = (ALLEEG(setlist(1)).times(end) - max([RT1 RT2]))/1000; ALLEEG(setlist(1)) = pop_epoch(ALLEEG(setlist(1)),{'RT'},tWindow); ALLEEG(setlist(2)) = pop_epoch(ALLEEG(setlist(2)),{'RT'},tWindow); jitter = -[RT1 RT2] + mean([RT1 RT2]); % convert to variables used by run_ and pop_ so that we can use our copied/pasted code truth_trials = truth; global weightprior; weightprior = strcmp(pop_settings_out(1).weightprior,'weight'); setlist = [1 2]; chansubset = 1:ALLEEG(1).nbchan; ntrials1 = ALLEEG(setlist(1)).trials; ntrials2 = ALLEEG(setlist(2)).trials; jitterrange = pop_settings_out(1).jitterrange; truth=[zeros((diff(jitterrange)+trainingwindowlength)*ntrials1,1); ... ones((diff(jitterrange)+trainingwindowlength)*ntrials2,1)]; times = (1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)); % Set up JitterPrior struct jitterPrior = []; jitterPrior.fn = @computeJitterPrior_gaussian; jitterPrior.params = []; jitterPrior.params.mu = 0; jitterPrior.params.sigma = std([RT1 RT2]); jitterPrior.params.nTrials = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; % Calculate prior ptprior = jitterPrior.fn((1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = ptprior/sum(ptprior); ptprior = repmat(ptprior,ntrials1+ntrials2,1); else % Ensure the rows sum to 1 ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); end % Re-weight priors according to the number of trials in each class if weightprior ptprior(truth_trials==1,:) = ptprior(truth_trials==1,:) / sum(truth_trials==1); ptprior(truth_trials==0,:) = ptprior(truth_trials==0,:) / sum(truth_trials==0); end % Extract data raweeg1 = ALLEEG(setlist(1)).data(chansubset,:,:); raweeg2 = ALLEEG(setlist(2)).data(chansubset,:,:); pt = cell(length(testsample),length(trainingwindowoffset)); % initialize for i=1:length(testsample) fprintf('Sample %d of %d...\n',i,length(testsample)); for j=1:length(trainingwindowoffset) % For each training window v = vout{i}(j,:); % v = evalin('base','v')'; % TEMP!\ % Put de-jittered data into [D x (N*T] matrix for input into logist x = AssembleData(raweeg1,raweeg2,trainingwindowoffset(j),trainingwindowlength,jitterrange); % Get y values y = x*v(1:end-1)' + v(end); % calculate y values given these weights % Remove baseline y-value by de-meaning if pop_settings_out(1).removeBaselineYVal y2 = y - mean(y); null_mu2 = pop_settings_out(1).null_mu-mean(y); else y2 = y; null_mu2 = pop_settings_out(1).null_mu; end % Get posterior pt{i,j} = ComputePosterior(ptprior,y2,truth,trainingwindowlength,... pop_settings_out(1).forceOneWinner,pop_settings_out(1).conditionPrior,null_mu2, pop_settings_out(1).null_sigma); end end disp('Success!') end % function GetFinalPosteriors % FUNCTION AssembleData: % Put de-jittered data into [(N*T) x D] matrix for input into logist function x = AssembleData(data1,data2,thistrainingwindowoffset,trainingwindowlength,jitterrange) % Declare constants iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength-1); x = cat(3,data1(:,iwindow,:),data2(:,iwindow,:)); x = reshape(x,[size(x,1),size(x,3)*length(iwindow)])'; end % function AssembleData % FUNCTION ComputePosterior: % Use the priors, y's and truth values to calculate the posteriors function [posterior,likelihood] = ComputePosterior(prior, y, truth, trainingwindowlength,forceOneWinner,conditionPrior,null_mu,null_sigma) % put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % calculate likelihood yavg = zeros(size(prior)); likelihood = ones(size(prior)); for i=1:size(prior,2) iwindow = (1:trainingwindowlength)+i-1; yavg(:,i) = mean(ymat(:,iwindow),2); likelihood(:,i) = bernoull(truthmat(:,i),yavg(:,i)); end if conditionPrior condprior = (1-normpdf(yavg,null_mu,null_sigma)/normpdf(0,0,null_sigma)).*prior; % prior conditioned on y (p(t|y)) condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % normalize so each trial sums to 1 else condprior = prior; end % calculate posterior posterior = likelihood.*condprior; % end % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row else % normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); end % Re-weight priors according to the number of trials in each class global weightprior; if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior
github
djangraw/FelixScripts-master
GetFinalPosteriors_oddball.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/GetFinalPosteriors_oddball.m
6,384
utf_8
425a4a16fa34115cd466209f11313a2f
function [pt, truth, times, jitter] = GetFinalPosteriors_oddball(foldername,cvmode,subject) % Put the posterior distributions of jittered logistic regression results % into a cell array. % % pt = GetFinalPosteriors_oddball(subject, resultsfile, startorend) % % INPUTS: % -foldername is a string indicating the folder in which the JLR results % reside. % -cvmode is a string indicating the cross-validation mode you used (e.g., % '10fold','loo'). % % OUTPUTS: % -pt is a cell array of matrices containing the posterior distributions % over time. Indices of pt are {LOOtrial, time}, indices of pt{i,j} are % [trial, TrainingWindowOffset]. % % Created 8/16/12 based on GetFinalPosteriors.mat % load results load([foldername '/results_' cvmode '.mat']); % Azloo, jitterrange, p, testsample, trainingwindowlength, trainingwindowoffset, truth, vout, pop_settings_out % Load data for given subject [ALLEEG,~,setlist] = loadSubjectData_oddball(subject); % eeg info and saccade info % Jitter data [ALLEEG(setlist(1)), jitter1] = jitterDataUniformly(ALLEEG(setlist(1)),pop_settings_out(1).jitterrange); [ALLEEG(setlist(2)), jitter2] = jitterDataUniformly(ALLEEG(setlist(2)),pop_settings_out(1).jitterrange); jitter = [jitter1, jitter2]; % convert to variables used by run_ and pop_ so that we can use our copied/pasted code truth_trials = truth; global weightprior; weightprior = strcmp(pop_settings_out(1).weightprior,'weight'); setlist = [1 2]; chansubset = 1:ALLEEG(1).nbchan; ntrials1 = ALLEEG(setlist(1)).trials; ntrials2 = ALLEEG(setlist(2)).trials; jitterrange = pop_settings_out(1).jitterrange; truth=[zeros((diff(jitterrange)+trainingwindowlength)*ntrials1,1); ... ones((diff(jitterrange)+trainingwindowlength)*ntrials2,1)]; times = (1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)); % Set up JitterPrior struct jitterPrior = []; jitterPrior.fn = @computeJitterPrior_uniform; jitterPrior.params = []; jitterPrior.params.range = jitterrange; jitterPrior.params.nTrials = ALLEEG(setlist(1)).trials + ALLEEG(setlist(2)).trials; % Calculate prior ptprior = jitterPrior.fn((1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = ptprior/sum(ptprior); ptprior = repmat(ptprior,ntrials1+ntrials2,1); else % Ensure the rows sum to 1 ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); end % Re-weight priors according to the number of trials in each class if weightprior ptprior(truth_trials==1,:) = ptprior(truth_trials==1,:) / sum(truth_trials==1); ptprior(truth_trials==0,:) = ptprior(truth_trials==0,:) / sum(truth_trials==0); end % Extract data raweeg1 = ALLEEG(setlist(1)).data(chansubset,:,:); raweeg2 = ALLEEG(setlist(2)).data(chansubset,:,:); pt = cell(length(testsample),length(trainingwindowoffset)); % initialize for i=1:length(testsample) fprintf('Sample %d of %d...\n',i,length(testsample)); for j=1:length(trainingwindowoffset) % For each training window v = vout{i}(j,:); % Put de-jittered data into [D x (N*T] matrix for input into logist x = AssembleData(raweeg1,raweeg2,trainingwindowoffset(j),trainingwindowlength,jitterrange); % Get y values y = x*v(1:end-1)' + v(end); % calculate y values given these weights % Remove baseline y-value by de-meaning if pop_settings_out(1).removeBaselineYVal y2 = y - mean(y); null_mu2 = pop_settings_out(1).null_mu-mean(y); else y2 = y; null_mu2 = pop_settings_out(1).null_mu; end % Get posterior pt{i,j} = ComputePosterior(ptprior,y2,truth,trainingwindowlength,... pop_settings_out(1).forceOneWinner,pop_settings_out(1).conditionPrior,null_mu2, pop_settings_out(1).null_sigma); end end disp('Success!') end % function GetFinalPosteriors % FUNCTION AssembleData: % Put de-jittered data into [(N*T) x D] matrix for input into logist function x = AssembleData(data1,data2,thistrainingwindowoffset,trainingwindowlength,jitterrange) % Declare constants iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength-1); x = cat(3,data1(:,iwindow,:),data2(:,iwindow,:)); x = reshape(x,[size(x,1),size(x,3)*length(iwindow)])'; end % function AssembleData % FUNCTION ComputePosterior: % Use the priors, y's and truth values to calculate the posteriors function [posterior,likelihood] = ComputePosterior(prior, y, truth, trainingwindowlength,forceOneWinner,conditionPrior,null_mu,null_sigma) % put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % calculate likelihood yavg = zeros(size(prior)); likelihood = ones(size(prior)); for i=1:size(prior,2) iwindow = (1:trainingwindowlength)+i-1; yavg(:,i) = mean(ymat(:,iwindow),2); likelihood(:,i) = bernoull(truthmat(:,i),yavg(:,i)); end if conditionPrior condprior = (1-normpdf(yavg,null_mu,null_sigma)/normpdf(0,0,null_sigma)).*prior; % prior conditioned on y (p(t|y)) condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % normalize so each trial sums to 1 else condprior = prior; end % calculate posterior posterior = likelihood.*condprior; % end % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row else % normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); end % Re-weight priors according to the number of trials in each class global weightprior; if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior
github
djangraw/FelixScripts-master
RerunJlrTesting.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/PlotResults/GetResults/RerunJlrTesting.m
3,631
utf_8
9cf1fecbead8027aba0ecfe3b1762c9f
function [Azloo,posterior,posterior2] = RerunJlrTesting(JLR,JLP,pop_settings) % Reruns just the test part of Jittered LR. % % function RerunTest_JLR(JLR,JLP) % % INPUTS: % -JLR and JLP are the outputs of LoadJlrResults % % Created 10/1/12 by DJ. if nargin<3 pop_settings = JLR.pop_settings_out; elseif numel(pop_settings) == 1 pop_settings = repmat(pop_settings,1,numel(JLR.pop_settings_out)); end % Set up srate = JLP.ALLEEG(1).srate; nFolds = numel(JLR.vout); trainingwindowlength = JLR.trainingwindowlength; trainingwindowoffset = JLR.trainingwindowoffset; testsample = JLR.testsample; jitterPriorTest = JLR.jitterPriorTest; vout = JLR.vout; nPrior = diff(JLP.pop_settings.jitterrange)+1; N = JLP.ALLEEG(1).trials + JLP.ALLEEG(2).trials; N1 = JLP.ALLEEG(1).trials; cv = JLP.cv; % Main Loop [ps posts,posts2] = deal(cell(1,nFolds)); for foldNum=1:nFolds fprintf('Testing Fold %d...\n',foldNum); ps{foldNum} = zeros(size(testsample{foldNum},3),length(trainingwindowoffset)); posts{foldNum} = zeros(size(testsample{foldNum},3),nPrior,length(trainingwindowoffset)); posts2{foldNum} = zeros(size(testsample{foldNum},3),nPrior,length(trainingwindowoffset)); % valTrials = [cv.valTrials1{foldNum}, ALLEEG(setlist(1)).trials + cv.valTrials2{foldNum}]; % TEMP 9/24/12 [ps{foldNum},posts{foldNum},~,posts2{foldNum}] = test_logisticregression_jittered_EM_v2p0(testsample{foldNum},trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},srate,pop_settings(foldNum)); % for k=1:size(testsample{foldNum},3) % % jitterPriorTest{foldNum}.params.saccadeTimes = jitterPrior.params.saccadeTimes(valTrials(k)); % TEMP 9/24/12 % [ps{foldNum}(k,:), thisPost, thisPost2] = runTest(testsample{foldNum}(:,:,k),trainingwindowlength,trainingwindowoffset,vout{foldNum},jitterPriorTest{foldNum},srate,pop_settings(foldNum)); % posts{foldNum}(k,:,:) = permute(thisPost,[3 2 1]); % posts2{foldNum}(k,:,:) = permute(thisPost2,[3 2 1]); % end end fprintf('Reshaping results...\n'); % Reshape posteriors p = zeros(N,length(trainingwindowoffset)); posterior = zeros(N,nPrior,length(trainingwindowoffset)); posterior2 = zeros(N,nPrior,length(trainingwindowoffset)); for foldNum=1:nFolds p([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:) = ps{foldNum}; posterior([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:,:) = posts{foldNum}; posterior2([cv.valTrials1{foldNum},cv.valTrials2{foldNum}+N1],:,:) = posts2{foldNum}; end % Get Az values truth = [zeros(JLP.ALLEEG(JLP.setlist(1)).trials,1);ones(JLP.ALLEEG(JLP.setlist(2)).trials,1)]; Azloo = nan(1,length(trainingwindowoffset)); for wini = 1:length(trainingwindowoffset) [Azloo(wini),~,~] = rocarea(p(:,wini),truth); fprintf('Window Onset: %d; LOO Az: %6.2f\n',trainingwindowoffset(wini),Azloo(wini)); end disp('Success!'); end % ---------------------------- % % ----- Helper Functions ----- % % ---------------------------- % function [p, posterior,posterior2] = runTest(testsample,trainingwindowlength,trainingwindowoffset,vout,jitterPrior,srate,pop_settings) p = zeros(1,length(trainingwindowoffset)); post = cell(1,length(trainingwindowoffset)); post2 = cell(1,length(trainingwindowoffset)); for wini = 1:length(trainingwindowoffset) [p(wini),post{wini},~,post2{wini}] = test_logisticregression_jittered_EM(testsample,trainingwindowlength,trainingwindowoffset(wini),vout(wini,:),jitterPrior,srate,pop_settings); % p(wini)=bernoull(1,y(wini)); end posterior = cat(1,post{:}); posterior2 = cat(1,post2{:}); end
github
djangraw/FelixScripts-master
RecalculateForwardModel_v3p1.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/PlotResults/GetResults/RecalculateForwardModel_v3p1.m
6,589
utf_8
49c9c1e9b9624ba333f536f701115ce9
function [fwdmodels,fwdmodels_v2,fwdmodels_old] = RecalculateForwardModel_v3p1(JLR,JLP) % Created 9/28/12 by DJ. nWin = numel(JLR.trainingwindowoffset); nFolds = JLP.cv.numFolds; trainingwindowlength = JLR.trainingwindowlength; trainingwindowoffset = JLR.trainingwindowoffset; UnpackStruct(JLP.pop_settings); % jitterrange,weightprior,forceOneWinner,conditionPrior srate = JLP.ALLEEG(1).srate; jitterPriorAll.fn = JLP.scope_settings.jitter_fn; jitterPriorAll.params = JLP.scope_settings.jitterparams; % Extract data raweeg1 = JLP.ALLEEG(1).data; raweeg2 = JLP.ALLEEG(2).data; % Smooth data smootheeg1 = nan(size(raweeg1,1),size(raweeg1,2)-trainingwindowlength+1, size(raweeg1,3)); smootheeg2 = nan(size(raweeg2,1),size(raweeg2,2)-trainingwindowlength+1, size(raweeg2,3)); for i=1:size(raweeg1,3) smootheeg1(:,:,i) = conv2(raweeg1(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end for i=1:size(raweeg2,3) smootheeg2(:,:,i) = conv2(raweeg2(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end N1 = size(smootheeg1,3); clear raweeg1 raweeg2 % Main loop fwdmodels = cell(nFolds,1); fwdmodels_v2 = cell(nFolds,1); fwdmodels_old = cell(nFolds,1); for i=1:nFolds % Get data, truth and prior for the trials in this fold data1 = smootheeg1(:,:,JLP.cv.incTrials1{i}); data2 = smootheeg2(:,:,JLP.cv.incTrials2{i}); ntrials1 = length(JLP.cv.incTrials1{i}); ntrials2 = length(JLP.cv.incTrials2{i}); % Define initial prior jitterPrior = jitterPriorAll; if isfield(jitterPrior.params,'data') jitterPrior.params.data = jitterPrior.params.data(:,:,[JLP.cv.incTrials1{i}, JLP.cv.incTrials2{i}+N1]); % crop data to just training trials end [ptprior,priortimes] = jitterPrior.fn((1000/srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); priorrange = round((srate/1000)*[min(priortimes),max(priortimes)]); % Make prior into a matrix and normalize rows if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = repmat(ptprior,ntrials1+ntrials2,1); end % Ensure the rows sum to 1 ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); % Get truth data truth=[zeros((diff(priorrange)+1)*ntrials1,1); ones((diff(priorrange)+1)*ntrials2,1)]; for j=1:nWin v = JLR.vout{i}(j,:)'; x = AssembleData(data1,data2,trainingwindowoffset(j),priorrange); y = x*v(1:end-1)+v(end); [nullx.mu, nullx.covar] = GetNullDistribution(data1,data2,trainingwindowoffset(j),priorrange); nully.mu = nullx.mu'*v(1:end-1)+v(end); nully.sigma = sqrt(v(1:end-1)'*nullx.covar*v(1:end-1) + v(1:end-1)'*(nullx.mu'*nullx.mu)*v(1:end-1)); nully.sigmamultiplier = null_sigmamultiplier; % widen distribution by the specified amount D = ComputePosterior(ptprior,y,truth,weightprior,forceOneWinner,conditionPrior,nully); Dvec = reshape(D',numel(D),1); Dmat = repmat(Dvec,1,size(x,2)); fwdmodels{i}(:,j) = (y\(x.*Dmat))'*size(ptprior,2); fwdmodels_v2{i}(:,j) = (y\(x.*Dmat))'; fwdmodels_old{i}(:,j) = (y\x)'; fprintf('%d, ',j); end fprintf('Done with fold %d!\n',i); end end %% HELPER FUNCTIONS FROM POP_... function [muX,covarX] = GetNullDistribution(data1,data2,thistrainingwindowoffset,jitterrange) % Crop data to null parts % inull = [1:(thistrainingwindowoffset+jitterrange(1)-1), (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength):length(data1)]; inull = [1:(thistrainingwindowoffset+jitterrange(1)-1), (thistrainingwindowoffset+jitterrange(2)+1):size(data1,2)]; X = cat(3,data1(:,inull,:),data2(:,inull,:)); X = reshape(X,[size(X,1),size(X,3)*length(inull)]); % Get mean and std muX = mean(X,2); covarX = X*X'/size(X,2); % if y=v*X, std(y,1)=sqrt(v*covarX*v'-v*muX^2); % if y=w*X+b, std(y,1) = sqrt(w*covarX*w' + w*muX*muX'*w') end % function GetNullDistribution % FUNCTION AssembleData: % Put de-jittered data into [(N*T) x D] matrix for input into logist function [x, trialnum] = AssembleData(data1,data2,thistrainingwindowoffset,jitterrange) % Declare constants iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)); % Concatenate trials from 2 datasets x = cat(3,data1(:,iwindow,:),data2(:,iwindow,:)); trialnum = repmat(reshape(1:size(x,3), 1,1,size(x,3)), 1, size(x,2)); % Reshape into 2D matrix x = reshape(x,[size(x,1),size(x,3)*length(iwindow)])'; trialnum = reshape(trialnum,[size(trialnum,1),size(trialnum,3)*length(iwindow)])'; end % function AssembleData function [posterior,likelihood,condprior] = ComputePosterior(prior, y, truth,weightprior,forceOneWinner,conditionPrior,nully) % Put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % Calculate likelihood likelihood = bernoull(truthmat,ymat); % Condition prior on y value: more extreme y values indicate more informative time points if conditionPrior % (NOTE: normalization not required, since we normalize later) % condprior = (1-normpdf(ymat,nully.mu,nully.sigma*nully.sigmamultiplier)/normpdf(0,0,nully.sigma*nully.sigmamultiplier)).*prior; % prior conditioned on y (p(t|y)) condprior = exp(abs(ymat)).*prior; else condprior = prior; end condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % Calculate posterior posterior = likelihood.*condprior; % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row end % Normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); % Re-weight priors according to the number of trials in each class if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior
github
djangraw/FelixScripts-master
RecalculateForwardModel.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/PlotResults/GetResults/RecalculateForwardModel.m
6,255
utf_8
fafbff3bee99d4fa90b9ae2267d1e59b
function [fwdmodels,fwdmodels_old] = RecalculateForwardModel(JLR,JLP) % Created 9/28/12 by DJ. nWin = numel(JLR.trainingwindowoffset); nFolds = JLP.cv.numFolds; trainingwindowlength = JLR.trainingwindowlength; trainingwindowoffset = JLR.trainingwindowoffset; UnpackStruct(JLP.pop_settings); % jitterrange,weightprior,forceOneWinner,conditionPrior jitterPrior = JLR.jitterPriorTest{1}; % Extract data raweeg1 = JLP.ALLEEG(1).data; raweeg2 = JLP.ALLEEG(2).data; % Smooth data smootheeg1 = nan(size(raweeg1,1),size(raweeg1,2)-trainingwindowlength+1, size(raweeg1,3)); smootheeg2 = nan(size(raweeg2,1),size(raweeg2,2)-trainingwindowlength+1, size(raweeg2,3)); for i=1:size(raweeg1,3) smootheeg1(:,:,i) = conv2(raweeg1(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end for i=1:size(raweeg2,3) smootheeg2(:,:,i) = conv2(raweeg2(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end clear raweeg1 raweeg2 % Compute prior [bigprior, priortimes] = jitterPrior.fn((1000/JLP.ALLEEG(1).srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); priorrange = round((JLP.ALLEEG(1).srate/1000)*[min(priortimes),max(priortimes)]); % Main loop fwdmodels = cell(nFolds,1); fwdmodels_old = cell(nFolds,1); for i=1:nFolds % Get data, truth and prior for the trials in this fold data1 = smootheeg1(:,:,JLP.cv.incTrials1{i}); data2 = smootheeg2(:,:,JLP.cv.incTrials2{i}); ntrials1 = length(JLP.cv.incTrials1{i}); ntrials2 = length(JLP.cv.incTrials2{i}); ptprior = repmat(bigprior/sum(bigprior),ntrials1+ntrials2,1); truth=[zeros((diff(priorrange)+1)*ntrials1,1); ones((diff(priorrange)+1)*ntrials2,1)]; for j=1:nWin v = JLR.vout{i}(j,:)'; x = AssembleData(data1,data2,trainingwindowoffset(j),trainingwindowlength,priorrange); y = x*v(1:end-1)+v(end); [nullx.mu, nullx.covar] = GetNullDistribution(data1,data2,trainingwindowoffset(j),trainingwindowlength,priorrange); nully.mu = nullx.mu'*v(1:end-1)+v(end); nully.sigma = sqrt(v(1:end-1)'*nullx.covar*v(1:end-1) + v(1:end-1)'*(nullx.mu'*nullx.mu)*v(1:end-1)); nully.sigmamultiplier = null_sigmamultiplier; % widen distribution by the specified amount D = ComputePosterior(ptprior,y,truth,trainingwindowlength,weightprior,forceOneWinner,conditionPrior,nully); Dvec = reshape(D',numel(D),1); Dmat = repmat(Dvec,1,size(x,2)); fwdmodels{i}(:,j) = (y\(x.*Dmat))'; fwdmodels_old{i}(:,j) = (y\x)'; fprintf('%d, ',j); end fprintf('Done with fold %d!\n',i); end end %% HELPER FUNCTIONS FROM POP_... function [muX,covarX] = GetNullDistribution(data1,data2,thistrainingwindowoffset,trainingwindowlength,jitterrange) % Crop data to null parts % inull = [1:(thistrainingwindowoffset+jitterrange(1)-1), (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength):length(data1)]; inull = [1:(thistrainingwindowoffset+jitterrange(1)-1), (thistrainingwindowoffset+jitterrange(2)+1):size(data1,2)]; X = cat(3,data1(:,inull,:),data2(:,inull,:)); X = reshape(X,[size(X,1),size(X,3)*length(inull)]); % Get mean and std muX = mean(X,2); covarX = X*X'/size(X,2); % if y=v*X, std(y,1)=sqrt(v*covarX*v'-v*muX^2); % if y=w*X+b, std(y,1) = sqrt(w*covarX*w' + w*muX*muX'*w') end % function GetNullDistribution % FUNCTION AssembleData: % Put de-jittered data into [(N*T) x D] matrix for input into logist function [x, trialnum] = AssembleData(data1,data2,thistrainingwindowoffset,trainingwindowlength,jitterrange) % Declare constants % iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength-1); iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)); x = cat(3,data1(:,iwindow,:),data2(:,iwindow,:)); trialnum = repmat(reshape(1:size(x,3), 1,1,size(x,3)), 1, size(x,2)); x = reshape(x,[size(x,1),size(x,3)*length(iwindow)])'; trialnum = reshape(trialnum,[size(trialnum,1),size(trialnum,3)*length(iwindow)])'; end % function AssembleData function [posterior,likelihood] = ComputePosterior(prior, y, truth, trainingwindowlength,weightprior,forceOneWinner,conditionPrior,nully) % put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % calculate likelihood likelihood = ones(size(prior)); for i=1:size(prior,2) likelihood(:,i) = bernoull(truthmat(:,i),ymat(:,i)); end if conditionPrior % condition prior on y value: more extreme y values indicate more informative saccades % null_y = yavg(isNull); % get y values for non-saccade timepoints % [nully.mu, nully.sigma] = normfit(null_y(:)); % gaussian fit of y values % nully.mu = -1; nully.sigma = 0.1; condprior = (1-normpdf(ymat,nully.mu,nully.sigma)/normpdf(0,0,nully.sigma)).*prior; % prior conditioned on y (p(t|y)) % condprior./repmat(sum(condprior,2),1,size(condprior,2)); % NOT NEEDED... WE NORMALIZE THE POSTERIOR LATER. else condprior = prior; end % calculate posterior posterior = likelihood.*condprior; % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row end % normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); % Re-weight priors according to the number of trials in each class if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior
github
djangraw/FelixScripts-master
TEMP_TestWithTrueWeights.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/ReactionTimeRecovery/OneTimeScripts/TEMP_TestWithTrueWeights.m
5,319
utf_8
9ad545efb03adcb6d7737719dc96ef8c
% TEMP_TestWithTrueWeights.m function TEMP_TestWithTrueWeights(x,ptprior,truth,pop_settings,ALLEEG,nully) plotbinolike = 1; convergencethreshold = 0.0100; jitterrange = [-500 500]; weightprior = 0; forceOneWinner = 0; conditionPrior = 0; null_sigmamultiplier = 1; binomialLike = 0; priortimes = jitterrange(1):jitterrange(2); UnpackStruct(pop_settings) %weightprior,forceOneWinner,conditionPrior,binomialLike if nargin<6 nully = []; end % Retrieve weights subject = ALLEEG(1).setname(1:find(ALLEEG(1).setname=='_',1)-1); [LRstim LPstim] = LoadJlrResults(subject,0,'10fold',[0 0],'_stimlocked_lambda1e+00_v2p3_condoff2'); LRavg = AverageJlrResults(LRstim,LPstim); v = LRavg.vout; tStim = LPstim.ALLEEG(1).times(LPstim.trainingwindowoffset + round(LPstim.scope_settings.trainingwindowlength/2)); % Apply weights y = x*v(1:end-1) + v(end); % calculate y values given these weights [pt,lkhd] = ComputePosterior(ptprior,y,truth,weightprior,forceOneWinner,conditionPrior,nully,binomialLike); if plotbinolike % Get the true jitter (for plotting) [jitter,fooTruth] = GetJitter(ALLEEG,'facecar'); faces = find(fooTruth==1); cars = find(fooTruth==0); ntrials = length(fooTruth); clear fooTruth % PLOT! figure(199); clf; ymat = reshape(y,length(y)/ntrials,ntrials)'; subplot(2,2,1); ImageSortedData(ymat(cars,:),priortimes,1:numel(cars),jitter(cars)); ImageSortedData(ymat(faces,:),priortimes,numel(cars)+(1:numel(faces)),jitter(faces)); title('y values') xlabel('time (ms)') ylabel('<-- cars | faces -->') axis([-500 500 0 ntrials]) colorbar; subplot(2,2,2); ImageSortedData(lkhd(cars,:),priortimes,1:numel(cars),jitter(cars)); ImageSortedData(lkhd(faces,:),priortimes,numel(cars)+(1:numel(faces)),jitter(faces)); title('likelihood') xlabel('time (ms)') ylabel('<-- cars | faces -->') axis([-500 500 0 ntrials]) colorbar; subplot(2,2,3) topoplot(v(1:end-1),ALLEEG(2).chanlocs); title(sprintf('Stim-locked weight vector (raw)\n (bias = %0.2g)(t=%gs)',v(end),tStim)) colorbar; subplot(2,2,4); ImageSortedData(pt(cars,:),priortimes,1:numel(cars),jitter(cars)); ImageSortedData(pt(faces,:),priortimes,numel(cars)+(1:numel(faces)),jitter(faces)); set(gca,'clim',[0 0.05]) title('posterior') xlabel('time (ms)') ylabel('<-- cars | faces -->') axis([-500 500 0 ntrials]) colorbar; pause(0.1); end %%%%%%%%% SUB-FUNCTIONS! %%%%%%%%%%%%%% function [posterior,likelihood] = ComputePosterior(prior, y, truth,weightprior,forceOneWinner,conditionPrior,nully,binomialLike) % Put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; truthsign = (truthmat-0.5)*2; % Calculate likelihood likelihood = bernoull(truthmat,ymat); % Binomial-based likelihod calculation % binomialLike = true; if binomialLike [L2, L3] = deal(zeros(size(likelihood))); for j=1:size(likelihood,2)% for each time point % [~,order] = sort(ymat(:,j).*truthsign(:,j),'descend'); % % [~,order] = sort(likelihood(:,j),'descend'); % L2(order,j) = 1:ntrials; % Rank of each trial within likelihood(:,j) % L3(:,j) = 1-binocdf(L2(:,j)-1,ntrials,50*prior(1,j)); L3(:,j) = 1-binocdf(ceil((1-likelihood(:,j))*ntrials-1),ntrials,50*prior(1,j)); % New Likelihood based on binomial distribution end likelihood = L3; end % Condition prior on y value: more extreme y values indicate more informative time points if conditionPrior % (NOTE: normalization not required, since we normalize later) % condprior = (1-normpdf(ymat,nully.mu,nully.sigma*nully.sigmamultiplier)/normpdf(0,0,nully.sigma*nully.sigmamultiplier)).*prior; % prior conditioned on y (p(t|y)) condprior = (1-normpdf(ymat,nully.mu,nully.sigma*nully.sigmamultiplier)/normpdf(0,0,nully.sigma*nully.sigmamultiplier)).*prior; % prior conditioned on y (p(t|y)) % additiveConst = 1.5; % condprior = additiveConst-exp(-(ymat-nully.mu).^2./(2*nully.sigma*nully.sigmamultiplier^2)); else condprior = prior; end condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % Calculate posterior posterior = likelihood.*condprior; % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row end % Normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); % Re-weight priors according to the number of trials in each class if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior end
github
djangraw/FelixScripts-master
logist_weighted_betatest_v3p0.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/New_v3/logist_weighted_betatest_v3p0.m
15,269
utf_8
874df08121f7efb64f87b0fcfa0912a9
% logist_weighted_betatest_v3p0() - Iterative recursive least squares % algorithm for linear logistic model % % Usage: % >> [v] = % logist_weighted_betatest_v3p0(x,y,vinit,d,show,regularize,lambda,lambdasearch,eigvalratio,posteriorOpts,trialnum,ptprior,useOffset) % % Inputs: % x - N input samples [N,D] % y - N binary labels [N,1] {0,1} % % Optional parameters: % vinit - initialization for faster convergence % show - if>0 will show first two dimensions % regularize - [1|0] -> [yes|no] % lambda - regularization constant for weight decay. Makes % logistic regression into a support vector machine % for large lambda (cf. Clay Spence). Defaults to 10^-6. % lambdasearch- [1|0] -> search for optimal regularization constant lambda % eigvalratio - if the data does not fill D-dimensional space, % i.e. rank(x)<D, you should specify a minimum % eigenvalue ratio relative to the largest eigenvalue % of the SVD. All dimensions with smaller eigenvalues % will be eliminated prior to the discrimination. % posteriorOpts - struct with fields mu, sigma, and sigmamultiplier. % Defines the null distribution of y values prior to this run. % trialnum - vector of the trial numbers in which each sample occurred % ptprior - prior probability of each time point. % useOffset - binary value indicating whether the weights should % include an offset (that is, y = v(1:end-1)*x + v(end) ). % % Outputs: % v - v(1:D) normal to separating hyperplane. v(D+1) slope % % Compute probability of new samples with p = bernoull(1,[x 1]*v); % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % % % Adapted from function logist.m by DJ and BC, 5/5/2011. % Updated 8/24/11 by DJ - added convergencethreshold parameter, cleanup % Updated 8/25/11 by BC to improve speed by removing examples where d==0 % Updated 10/26/11 by BC - added input for null distribution of y values % Updated 12/5/11 by BC - comments % Updated 12/6/11 by DJ - moved currtrialnumsc calculation up % Updated 12/9/11 by DJ - optimization using profiler % Updated 12/12/11 by DJ - added sigmamultiplier % Updated 9/18/12 by DJ - assume smoothed data (don't take avg here) % Updated 9/19/12 by DJ - Modified to not use offset % Updated 10/5/12 by DJ - v2p1 % Updated 11/6/12 by DJ - added conditionPrior option % Updated 11/15/12 by BC - v2p2, fixed f rounding to pass DerivativeCheck % ... % Updated 11/29/12 by DJ - added useOffset input, fixed defaults function [v] = logist_weighted_betatest_v3p0(x,y,v,d,show,regularize,lambda,lambdasearch,eigvalratio,posteriorOpts,trialnum,ptprior,useOffset) % Get data size [N,D]=size(x); % Handle defaults for optional inputs if nargin<3 || isempty(v), v=zeros(D,1); vth=0; else vth=v(D+1); v=v(1:D); end; if nargin<4 || isempty(d), d=ones(size(x)); end; if nargin<5 || isempty(show); show=0; end; if nargin<6 || isempty(regularize); regularize=0; end if nargin<7 || isempty(lambda); lambda=eps; end; if nargin<8 || isempty(lambdasearch), lambdasearch=0; end if nargin<9 || isempty(eigvalratio); eigvalratio=0; end; if nargin<10 || isempty(posteriorOpts); posteriorOpts = []; end; if nargin<11 || isempty(trialnum); trialnum = 1:numel(d); end; if nargin<12 || isempty(ptprior); ptprior = ones(size(d)); end; if nargin<13 || isempty(useOffset); useOffset=false; end; %if regularize, lambda=1e-6; end % Speed up computation by removing samples where d==0 locs = find(d<1e-8); % BC, 11/8/12 -- switched find(d==0) to find(d<1e-6) x(locs,:) = []; y(locs) = []; d(locs) = []; ptprior(locs) = []; trialnum(locs) = []; % subspace reduction if requested - electrodes might be linked if eigvalratio && 0 [U,S,V] = svd(x,0); % subspace analysis V = V(:,diag(S)/S(1,1)>eigvalratio); % keep significant subspace x = x*V; % map the data to that subspace v = V'*v; % reduce initialization to the subspace end [N,D]=size(x); % less dimensions now % combine threshold computation with weight vector. if useOffset x = [x ones(N,1)]; % To use offset else x = [x zeros(N,1)]; % To eliminate offset end v = [v; vth]+eps; if regularize lambda = [0.5*lambda*ones(1,D) 0]'; end % clear warning as we will use it to catch conditioning problems lastwarn(''); if show, figure; end %posteriorOpts.mu = 0; % Added 11/8/12 for debugging BC %posteriorOpts.sigma = 1; % Added 11/8/12 for debugging BC %posteriorOpts.sigmamultiplier = 10; % Added 11/8/12 for debugging BC if ~isempty(posteriorOpts) && isfield(posteriorOpts,'mu') && ~isnan(posteriorOpts.mu) conditionPrior = true; % Parse null distribution gaussian parameters pMu = posteriorOpts.mu; % Here, we can scale the standard deviation by a multiplicative constant if we want pStdDev = posteriorOpts.sigma * posteriorOpts.sigmamultiplier; else conditionPrior = false; end % Get trial numbers and the data points belonging to each trial trialnumunique = unique(trialnum); iThisTrialc = cell(length(trialnumunique),1); for q=1:length(trialnumunique) iThisTrialc{q} = find(trialnum==trialnumunique(q)); end xt = x'; % Added 11/8/12 BC v = double(v); % Run Optimization opts = optimset('GradObj','on',... 'Hessian','off',... 'Display','notify',... 'TolFun',1e-4,... 'TolX',1e-3,... % 11/8/12 BC 'MaxIter',1000,... 'DerivativeCheck','off'); % 'Display','iter-detailed'); % for detailed info on every iteration % 'OutputFcn',@lwf_outfcn % 'DerivativeCheck','on',... % 'FinDiffType','central',... % Set proper constraints on values of mabsx = max(sum(abs(x),2)); vlim = 100/mabsx; v = fmincon(@lwf,v,[],[],[],[],-vlim*ones(size(v)),vlim*ones(size(v)),[],opts); %v = fminunc(@lwf,v,opts); if eigvalratio && 0 v = [V*v(1:D);v(D+1)]; % the result should be in the original space end % logist-weighted function (lwf) function [f,g,H] = lwf(v) % v is the current estimate for the spatial filter weights % Returns: % f: the objective to minimize, evaluated at v % g: the gradient of the objective, evaluated at v % H: the Hessian matrix of the objective, evaluated at v % Note: the Hessian is approximated by the identity matrix here (akin to gradient descent) % % The function f(v) is given by: % f(v) = -1*sum_{i=1}^N d_i*(y_i*x_i*v - log(1+exp(x_i*v))) ... The usual weighted LR objective % + 0.5*v'*diag(lambda)*v ... The regularization (energy of the weights) % - sum_{i=1}^N d_i*log(fy_i) The log-posterior term % fy_i = p(s_i|x,v) -- the posterior probability of the saccade % The posterior probability takes the following functional form: % fy_i = fynum_i/fyden_i (numerator / denominator) % Where fynum_i = (1 - exp(-(xv_i-pMu)^2/(2*pStdDev^2))) -- (1 - gaussian) % Notice here that xv is used in fynum, to ensure that each sample from the saccade has the same posterior prob. value % Since fy_i is a probability over saccades, the sum of fy_i over all samples from a trial must equal 1 % fyden_i is the normalization constant: % fyden_i = sum_j fynum_j % Where j indexes over all samples that belong to the same trial as sample i % compute current y-values (xv) and label probabilities (pvals) xv = x*v; if conditionPrior if 1 fynum = exp(abs(xv)).*ptprior; fyden_pertrial = cellfun(@(iTT) sum(fynum(iTT)),iThisTrialc,'UniformOutput',true); fy = fynum./fyden_pertrial(trialnum); else additiveConst = 1; % compute the numerator and denominator terms of the posterior saccade probabilities fynum = (additiveConst-exp(-(xv-pMu).^2./(2*pStdDev^2))).*ptprior; fyden = zeros(size(fynum)); for j=1:length(trialnumunique) % Sum the numerator terms over all the samples from this trial % We will set this as the denominator term in order to normalize the probability fyden(iThisTrialc{j}) = sum(fynum(iThisTrialc{j})); end % Flatten any trials with small fyden values (vulnerable to round-off errors) troubleTrials = unique(trialnum(fyden<1e-10)); for jj=1:numel(troubleTrials) fynum(iThisTrialc{troubleTrials(jj)}) = 1/length(iThisTrialc{troubleTrials(jj)}); % fixed 10/5/12 fyden(iThisTrialc{troubleTrials(jj)}) = 1; % fixed 10/5/12 end % Calculate f values (see comments at top of this function) fy = fynum./fyden; end f = sum(d.*(log(1+exp(xv)) - y.*xv - log(fy))) + 0.5*sum(v.*(lambda.*v)); else f = sum(d.*(log(1+exp(xv)) - y.*xv)) + 0.5*sum(v.*(lambda.*v)); end % Produce error if any f values are infinite (???) if isinf(f) % f=1e50; warning('Infinite objective value'); % error('JLR:InfiniteFValue','objective f is infinite!') end if nargout > 1 % Then we must also compute the gradient pvals = 1./(1+exp(-xv)); if conditionPrior if 1 sgn_xv = sign(xv); g = xt*(d.*(pvals-y-sgn_xv)+fy.*sgn_xv) + lambda.*v; % for j=1:length(trialnumunique) % g = g + sum(d(iThisTrialc{j}))*(xt(:,iThisTrialc{j})*(fy_times_sgn_xv(iThisTrialc{j}))); % end else % Here we focus on computing the gradient of the log posterior probability term with respect to v % For a particular sample i, we want to compute the gradient of: % d_i log(fynum_i / fyden_i) % Where fynum_i, fyden_i depends on v % Take partial derivative (and let D(...) be a derivative operator): % d_i*(fyden_i/fynum_i)*[D(fynum_i)/fyden_i - (fynum_i/fyden_i^2)*D(fyden_i)] % = (d_i/fynum_i)*[D(fynum_i) - fy_i*D(fyden_i)] % By the chain rule, D(fynum_i) = dfy_i*x(i,:)', % where dfy_i is the derivative of fynum_i with respect to its argument % fynum(z) = % (additiveConst-exp(-(z-pMu)^2/(2*pStdDev^2))).*ptprior % d_fynum(z)/dz = -exp(-(z-pMu)^2/(2*pStdDev^2))*[-(z-pMu)/(pStdDev^2)] % = (additiveConst-fynum(z))*(z-pMu)/pStdDev^2 % So dfy_i = (additiveConst-fynum_i)*(xv(i)-pMu)/pStdDev^2 dfy = (additiveConst.*ptprior-fynum).*((xv-pMu)/pStdDev^2); % Since fyden_i = sum_j fynum_j, then: % D(fyden_i) = sum_j D(fynum_j) % = sum_j dfy_j*x(j,:)' % BC 11/8/12 edit % Old way is the (if 0) code block % New way is the (else) code block if 0 % Old way d_over_fynum = d./max(fynum,eps); dfy_times_x = spdiags(dfy,0,length(dfy),length(dfy))*x; % gf is the gradient of the log-posterior term gf = (assertVec(d_over_fynum,'row')*dfy_times_x)'; fy_times_d_over_fynum = fy.*d_over_fynum; % Gather the samples that belong to each trial for j=1:length(trialnumunique) gf = gf - sum(fy_times_d_over_fynum(iThisTrialc{j})*sum(dfy_times_x(iThisTrialc{j},:)))'; end gf2 = gf; else % New way d_over_fynum = d./max(fynum,eps); % gf is the gradient of the log-posterior term gf = xt*(d_over_fynum.*dfy); fy_times_d_over_fynum = fy.*d_over_fynum; % Gather the samples that belong to each trial for j=1:length(trialnumunique) gf = gf - sum(fy_times_d_over_fynum(iThisTrialc{j}))*(xt(:,iThisTrialc{j})*dfy(iThisTrialc{j})); end end % Now we compute the overall gradient % The first term is the gradient of the weighted LR objective % The second term is the gradient of the regularization term % The third term is the gradient of the log-posterior term g = xt*(d.*(pvals-y)) + lambda.*v - gf; % DJ, 10/8/12 % BC 11/8/12 (switched x' to xt and changed -xt*(d.*(y-pvals)) to xt*(d.*(pvals-y)) ) end else g = xt*(d.*(pvals-y)) + lambda.*v; % DJ, 11/6/12 % BC 11/8/12 (switched x' to xt and changed -xt*(d.*(y-pvals)) to xt*(d.*(pvals-y)) ) end end if nargout > 2 H = speye(size(v,1),size(v,1)); end end end
github
djangraw/FelixScripts-master
logist_weighted_betatest_v3p1.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/New_v3/logist_weighted_betatest_v3p1.m
8,564
utf_8
16ae31a125f7a66bfa78ab3de26db595
% logist_weighted_betatest_v3p0() - Iterative recursive least squares % algorithm for linear logistic model % % Usage: % >> [v] = % logist_weighted_betatest_v3p1(x,y,vinit,d,show,regularize,lambda,lambdasearch,eigvalratio,useOffset) % % Inputs: % x - N input samples [N,D] % y - N binary labels [N,1] {0,1} % % Optional parameters: % vinit - initialization for faster convergence % show - if>0 will show first two dimensions % regularize - [1|0] -> [yes|no] % lambda - regularization constant for weight decay. Makes % logistic regression into a support vector machine % for large lambda (cf. Clay Spence). Defaults to 10^-6. % lambdasearch- [1|0] -> search for optimal regularization constant lambda % eigvalratio - if the data does not fill D-dimensional space, % i.e. rank(x)<D, you should specify a minimum % eigenvalue ratio relative to the largest eigenvalue % of the SVD. All dimensions with smaller eigenvalues % will be eliminated prior to the discrimination. % useOffset - binary value indicating whether the weights should % include an offset (that is, y = v(1:end-1)*x + v(end) ). % % Outputs: % v - v(1:D) normal to separating hyperplane. v(D+1) slope % % Compute probability of new samples with p = bernoull(1,[x 1]*v); % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % % % % Adapted from function logist.m by DJ and BC, 5/5/2011. % Updated 8/24/11 by DJ - added convergencethreshold parameter, cleanup % Updated 8/25/11 by BC to improve speed by removing examples where d==0 % Updated 10/26/11 by BC - added input for null distribution of y values % Updated 12/5/11 by BC - comments % Updated 12/6/11 by DJ - moved currtrialnumsc calculation up % Updated 12/9/11 by DJ - optimization using profiler % Updated 12/12/11 by DJ - added sigmamultiplier % Updated 9/18/12 by DJ - assume smoothed data (don't take avg here) % Updated 9/19/12 by DJ - Modified to not use offset % Updated 10/5/12 by DJ - v2p1 % Updated 11/6/12 by DJ - added conditionPrior option % Updated 11/15/12 by BC - v2p2, fixed f rounding to pass DerivativeCheck % ... % Updated 11/29/12 by DJ - added useOffset input, fixed defaults % Updated 12/19/12 by DJ - no conditionPrior option, simplified inputs/code function [v] = logist_weighted_betatest_v3p1(x,y,v,d,show,regularize,lambda,lambdasearch,eigvalratio,useOffset) % Get data size [N,D]=size(x); % Handle defaults for optional inputs if nargin<3 || isempty(v), v=zeros(D,1); vth=0; else vth=v(D+1); v=v(1:D); end; if nargin<4 || isempty(d), d=ones(size(x)); end; if nargin<5 || isempty(show); show=0; end; if nargin<6 || isempty(regularize); regularize=0; end if nargin<7 || isempty(lambda); lambda=eps; end; if nargin<8 || isempty(lambdasearch), lambdasearch=0; end if nargin<9 || isempty(eigvalratio); eigvalratio=0; end; if nargin<10 || isempty(useOffset); useOffset=false; end; %if regularize, lambda=1e-6; end % Speed up computation by removing samples where d==0 locs = find(d<1e-8); % BC, 11/8/12 -- switched find(d==0) to find(d<1e-6) x(locs,:) = []; y(locs) = []; d(locs) = []; % subspace reduction if requested - electrodes might be linked if eigvalratio && 0 [U,S,V] = svd(x,0); % subspace analysis V = V(:,diag(S)/S(1,1)>eigvalratio); % keep significant subspace x = x*V; % map the data to that subspace v = V'*v; % reduce initialization to the subspace end [N,D]=size(x); % less dimensions now % combine threshold computation with weight vector. if useOffset x = [x ones(N,1)]; % To use offset else x = [x zeros(N,1)]; % To eliminate offset end v = [v; vth]+eps; if regularize lambda = [0.5*lambda*ones(1,D) 0]'; end % clear warning as we will use it to catch conditioning problems lastwarn(''); if show, figure; end xt = x'; % Added 11/8/12 BC v = double(v); % Run Optimization opts = optimset('GradObj','on',... 'Hessian','off',... 'Display','notify',... 'TolFun',1e-4,... 'TolX',1e-3,... % 11/8/12 BC 'MaxIter',1000,... 'DerivativeCheck','off'); % 'Display','iter-detailed'); % for detailed info on every iteration % 'OutputFcn',@lwf_outfcn % 'DerivativeCheck','on',... % 'FinDiffType','central',... % Set proper constraints on values of mabsx = max(sum(abs(x),2)); vlim = 100/mabsx; v = fmincon(@lwf,v,[],[],[],[],-vlim*ones(size(v)),vlim*ones(size(v)),[],opts); %v = fminunc(@lwf,v,opts); if eigvalratio && 0 v = [V*v(1:D);v(D+1)]; % the result should be in the original space end % logist-weighted function (lwf) function [f,g,H] = lwf(v) % v is the current estimate for the spatial filter weights % Returns: % f: the objective to minimize, evaluated at v % g: the gradient of the objective, evaluated at v % H: the Hessian matrix of the objective, evaluated at v % Note: the Hessian is approximated by the identity matrix here (akin to gradient descent) % % The function f(v) is given by: % f(v) = -1*sum_{i=1}^N d_i*(y_i*x_i*v - log(1+exp(x_i*v))) ... The usual weighted LR objective % + 0.5*v'*diag(lambda)*v ... The regularization (energy of the weights) % - sum_{i=1}^N d_i*log(fy_i) The log-posterior term % fy_i = p(s_i|x,v) -- the posterior probability of the saccade % The posterior probability takes the following functional form: % fy_i = fynum_i/fyden_i (numerator / denominator) % Where fynum_i = (1 - exp(-(xv_i-pMu)^2/(2*pStdDev^2))) -- (1 - gaussian) % Notice here that xv is used in fynum, to ensure that each sample from the saccade has the same posterior prob. value % Since fy_i is a probability over saccades, the sum of fy_i over all samples from a trial must equal 1 % fyden_i is the normalization constant: % fyden_i = sum_j fynum_j % Where j indexes over all samples that belong to the same trial as sample i % OBJECTIVE % compute current y-values (xv) and label probabilities (pvals) xv = x*v; % Get f value (assume conditionPrior is off) f = sum(d.*(log(1+exp(xv)) - y.*xv)) + 0.5*sum(v.*(lambda.*v)); % Produce warning/error if any f values are infinite (???) if isinf(f) % f=1e50; warning('Infinite objective value'); % error('JLR:InfiniteFValue','objective f is infinite!') end % GRADIENT if nargout > 1 % Then we must also compute the gradient pvals = 1./(1+exp(-xv)); % Bernoulli function of p values g = xt*(d.*(pvals-y)) + lambda.*v; % Assume conditionPrior is off! end % HESSIAN if nargout > 2 H = speye(size(v,1),size(v,1)); end end end
github
djangraw/FelixScripts-master
pop_logisticregression_jittered_EM_v3p0.m
.m
FelixScripts-master/MATLAB/JitteredLR/2013_02_06-DropboxCode/New_v3/pop_logisticregression_jittered_EM_v3p0.m
26,764
utf_8
78c407f8b0a751842b43752694beb57b
% pop_logisticregression_jittered_EM_v3p0() - Determine linear discriminating vector between two datasets. % using logistic regression on data where jitter of % each trial is uncertain with Expectation % Maximization % % Usage: % >> pop_logisticregression_jittered_EM_v3p0( ALLEEG, datasetlist, chansubset, trainingwindowlength, trainingwindowoffset, regularize, lambda, lambdasearch, eigvalratio, vinit, jitterrange, convergencethreshold, jitterPrior); % % Inputs: % ALLEEG - array of datasets % datasetlist - list of datasets % chansubset - vector of channel subset for dataset 1 [1:min(Dset1,Dset2)] % trainingwindowlength - Length of training window in samples [all] % trainingwindowoffset - Offset(s) of training window(s) in samples [1] % regularize - regularize [1|0] -> [yes|no] [0] % lambda - regularization constant for weight decay. [1e-6] % Makes logistic regression into a support % vector machine for large lambda % (cf. Clay Spence) % lambdasearch - [1|0] -> search for optimal regularization % constant lambda % eigvalratio - if the data does not fill D-dimensional % space, i.e. rank(x)<D, you should specify % a minimum eigenvalue ratio relative to the % largest eigenvalue of the SVD. All dimensions % with smaller eigenvalues will be eliminated % prior to the discrimination. % vinit - initialization for faster convergence [zeros(D+1,1)] % jitterrange - 2-element vector specifying the minimum and % maximum jitter values (in units of samples) % convergencethreshold - max change in Az that must be observed in order % for the iteration loop to exit. [.01] % jitterPrior - a structure containing params for the jitter % prior pdf with the following fields: % fn: a function handle that returns the prior % pdf % params: a structure of PDF parameters to pass % to the prior pdf function % The fn should be prototyped as follows: % function pdf = @fn(t,params) % Where t is a set of points to evaluate the % pdf at % % References: % % @article{gerson2005, % author = {Adam D. Gerson and Lucas C. Parra and Paul Sajda}, % title = {Cortical Origins of Response Time Variability % During Rapid Discrimination of Visual Objects}, % journal = {{NeuroImage}}, % year = {in revision}} % % @article{parra2005, % author = {Lucas C. Parra and Clay D. Spence and Adam Gerson % and Paul Sajda}, % title = {Recipes for the Linear Analysis of {EEG}}, % journal = {{NeuroImage}}, % year = {in revision}} % % Authors: Dave Jangraw ([email protected], 2011) % Bryan Conroy ([email protected],2011) % Based on program pop_logisticregression, coded by: % Adam Gerson ([email protected], 2004), % with Lucas Parra ([email protected], 2004) % and Paul Sajda (ps629@columbia,edu 2004) %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2004 Adam Gerson, Lucas Parra and Paul Sajda % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 5/21/2005, Fixed bug in leave one out script, Adam % 4/2011 - Adjusted for jittered EM algorithm, Bryan & Dave % 5/20/2011 - Added weightprior capability, Dave % 8/3/2011 - Allow flexible prior size using priorrange, Bryan % 8/24/2011 - Fixed plotting bug (jitterrange -> priorrange), Dave % 9/6/2011 - 1st iteration prior is first saccade on each trial, Dave % 9/12/2011 - added removeBaselineYVal option, Bryan & Dave % 9/14/2011 - added forceOneWinner option, fwdmodel uses y2, ellv % calculated using bp, Dave & Bryan % 9/15/2011 - added forceOneWinner to ComputePosteriorLabel, Dave % 9/16/2011 - fixed weightprior bug in ComputePosterior, added % useTwoPosteriors option, Dave % 9/19/2011 - save settings to etc fields of ALLEEG, Dave % 9/20/2011 - deNoiseData option, Dave % 10/4/2011 - useSymmetricLikelihood option, Dave - NO LONGER USED % 10/6/2011 - conditionPrior option, cleaned up pop_settings, Dave % 12/12/2011 - added sigmamultiplier option, Dave % 9/18/2012 - smooth eeg up front, added GetNullDistribution to make % conditionPrior option work without saccade-based data (everything % outside the priorrange window is considered 'null' data), Dave % 9/21/2012 - TEMP: vFirstIter output, D initialized to D from base workspace, Dave % 9/24/2012 - fixed smootheeg scaling (divided by trainingwindowlength), Dave % 9/25/2012 - added ptprior_truprior etc., Dave % 9/25/2012 - made work with conditionPrior off, Dave % 10/1/2012 - weighted forward model calculation, Dave % 10/2/2012 - include sigmamultiplier in posterior calculations, calculte % posteriors at the end for weighted fwdmodel, Dave % 10/5/2012 - v2p1, Dave % 11/14/2012 - code cleanup, consolidated condPrior options % 11/15/2012 - switched to _betatest_v2p2, removed trainingwindowlength % input to that fn, Dave % ... % 11/27-29/2012 - added useOffset setting, PlotDebugFigs function, fixed forceOneWinner py values, Dave function [ALLEEG, com, vout, vFirstIter] = pop_logisticregression_jittered_EM_v3p0(ALLEEG, setlist, chansubset, trainingwindowlength, trainingwindowoffset, vinit, jitterPrior, pop_settings, logist_settings) % Set plot settings show=0; % don't show boundary showaz=1; % display Az values as we iterate plotdebugfigs = 0; % plot posteriors, likelihoods, weight vector scalp maps as we iterate % Unpack options UnpackStruct(pop_settings); UnpackStruct(logist_settings); if ~exist('useOffset','var'), useOffset = false; end % set default here for use with old versions of wrapper code com = ''; if nargin < 1 help pop_logisticregression_jittered_EM; return; end; if isempty(ALLEEG) error('pop_logisticregression_jittered_EM(): cannot process empty sets of data'); end; if jitterrange(1) > jitterrange(2) error('jitterrange must be 2-element vector sorted in ascending order!'); end % Set up truth labels (one for each data sample in the window on each trial ALLEEG(setlist(1)).trials = size(ALLEEG(setlist(1)).data,3); ALLEEG(setlist(2)).trials = size(ALLEEG(setlist(2)).data,3); ntrials1 = ALLEEG(setlist(1)).trials; ntrials2 = ALLEEG(setlist(2)).trials; truth_trials = [zeros(ntrials1,1);ones(ntrials2,1)]; % The truth value associated with each trial % Initialize ica-related fields ALLEEG(setlist(1)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icaweights=zeros(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan); % In case a subset of channels are used, assign unused electrodes in scalp projection to NaN ALLEEG(setlist(1)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(1)).nbchan)'; ALLEEG(setlist(2)).icawinv=nan.*ones(length(trainingwindowoffset),ALLEEG(setlist(2)).nbchan)'; ALLEEG(setlist(1)).icasphere=eye(ALLEEG(setlist(1)).nbchan); ALLEEG(setlist(2)).icasphere=eye(ALLEEG(setlist(2)).nbchan); % Initialize vout vout = nan(length(trainingwindowoffset),length(chansubset)+1); % Extract data raweeg1 = ALLEEG(setlist(1)).data(chansubset,:,:); raweeg2 = ALLEEG(setlist(2)).data(chansubset,:,:); % Smooth data smootheeg1 = nan(size(raweeg1,1),size(raweeg1,2)-trainingwindowlength+1, size(raweeg1,3)); smootheeg2 = nan(size(raweeg2,1),size(raweeg2,2)-trainingwindowlength+1, size(raweeg2,3)); for i=1:size(raweeg1,3) smootheeg1(:,:,i) = conv2(raweeg1(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end for i=1:size(raweeg2,3) smootheeg2(:,:,i) = conv2(raweeg2(:,:,i),ones(1,trainingwindowlength)/trainingwindowlength,'valid'); % valid means exclude zero-padded edges without full overlap end % Define initial prior [ptprior,priortimes] = jitterPrior.fn((1000/ALLEEG(setlist(1)).srate)*(jitterrange(1):jitterrange(2)),jitterPrior.params); priorrange = round((ALLEEG(setlist(1)).srate/1000)*[min(priortimes),max(priortimes)]); truth=[zeros((diff(priorrange)+1)*ntrials1,1); ones((diff(priorrange)+1)*ntrials2,1)]; DEBUG_BRYAN = false; if DEBUG_BRYAN addpath('~/Dropbox/JitteredLogisticRegression/code/ReactionTimeRecovery/PlotResults/'); [jitter_truth,~] = GetJitter(ALLEEG,'facecar'); jitter_truth_inds = interp1(priortimes,1:numel(priortimes),jitter_truth,'nearest'); end DEBUG_BRYAN = false; % make sure training windows fit within size of data if max(trainingwindowlength+trainingwindowoffset+priorrange(2)-1)>ALLEEG(setlist(1)).pnts, error('pop_logisticregression_jitter(): training window exceeds length of dataset 1'); end if max(trainingwindowlength+trainingwindowoffset+priorrange(2)-1)>ALLEEG(setlist(2)).pnts, error('pop_logisticregression_jitter(): training window exceeds length of dataset 2'); end % Make prior into a matrix and normalize rows if size(ptprior,1) == 1 % Then the prior does not depend on the trial ptprior = repmat(ptprior,ntrials1+ntrials2,1); end % Ensure the rows sum to 1 ptprior = ptprior./repmat(sum(ptprior,2),1,size(ptprior,2)); % Re-weight priors according to the number of trials in each class if weightprior ptprior(truth_trials==1,:) = ptprior(truth_trials==1,:) / sum(truth_trials==1); ptprior(truth_trials==0,:) = ptprior(truth_trials==0,:) / sum(truth_trials==0); end if plotdebugfigs PlotDebugFigures(0,vinit,ptprior,priorrange,nan(size(ptprior)),nan(size(ptprior)),truth_trials,ntrials1+2,ALLEEG) end %%% MAIN LOOP %%% MAX_ITER = 50; % the max number of iterations allowed for i=1:length(trainingwindowoffset) % For each training window % Get mean (1xD) and covariance (DxD) for the null samples on each electrode if conditionPrior [nullx.mu, nullx.covar] = GetNullDistribution(smootheeg1,smootheeg2,trainingwindowoffset(i),priorrange); nully.sigmamultiplier = null_sigmamultiplier; % widen distribution by the specified amount else nully = []; end tllv = -inf; % true log likelihood - should increase on each iteration. % Put de-jittered data into [D x (N*T] matrix for input into logist [x, trialnum] = AssembleData(smootheeg1,smootheeg2,trainingwindowoffset(i),priorrange); % for j=1:size(x,1) % x(j,:) = x(j,:)/max(sqrt(sum(x(j,:).^2)),1e-8); % end % get D vector D = ptprior; if DEBUG_BRYAN for j=1:size(D,1) D(j,:)=0; D(j,jitter_truth_inds(j))=1; end % ptprior(:)=1/size(ptprior,2); end Dvec = reshape(D',1,numel(D)); ptpriorvec = reshape(ptprior',1,numel(ptprior)); % Calculate weights using logistic regression % v = logist_weighted_v2p1(x,truth,vinit,Dvec',show,regularize,lambda,lambdasearch,eigvalratio); % calculate logistic regression weights v = logist_weighted_betatest_v3p0(x,truth,vinit,Dvec',show,regularize,lambda,lambdasearch,eigvalratio,[],trialnum,ptpriorvec',useOffset); % calculate logistic regression weights if ~useOffset v(end) = 0; end % Update null y distribution if conditionPrior nully.mu = nullx.mu'*v(1:end-1)+v(end); nully.sigma = sqrt(v(1:end-1)'*nullx.covar*v(1:end-1) + v(1:end-1)'*(nullx.mu'*nullx.mu)*v(1:end-1)); end % Store results from first iteration vFirstIter = v; % Calculate y values given these weights y = x*v(1:end-1) + v(end); % Compute the true log-likelihood value: % sum_over_trials(log(sum_over_saccades(p(c|y,ti)*p(ti|y)))) tllv = [tllv sum(log(ComputePosteriorLabel(ptprior,y,truth,forceOneWinner,conditionPrior,nully)))-lambda/4*sum(v(1:end-1).^2)]; % adjust posterior [py, ~] = ComputePosteriorLabel(ptprior,y,ones(size(y)),forceOneWinner,conditionPrior,nully); nully.sigmamultiplier = null_sigmamultiplier; % widen distribution by the specified amount % Calculate ROC curve and Az value [Az,Ry,Rx] = rocarea(py,truth_trials); % find ROC curve % Initialize list of iteration results iterAz = [NaN Az]; % NaN included so indices will match tllv,etc. % Display results if showaz, fprintf('Window Onset: %d; iteration %d; Az: %6.3f; Average weight/sample (in LR): %.2f\n',trainingwindowoffset(i),length(iterAz)-1,Az,sum(Dvec)/length(Dvec)); end vprev = zeros(size(v)); while subspace(vprev+eps,v)>convergencethreshold vprev = v; % adjust prior [D,lkhd,cndp] = ComputePosterior(ptprior,y,truth,weightprior,forceOneWinner,conditionPrior,nully); if plotdebugfigs PlotDebugFigures(length(iterAz)-1,v,D,priorrange,lkhd,cndp,py,ntrials1+2,ALLEEG) end % Now we will update ptprior % Fit ex-gaussian to mean of D %R=fminsearch(@(params) eglike(params,data),pinit); % given the data, and starting parameters in % pinit, find the parameter values that minimize eglike % the function returns R=[mu, sig, tau] % ptprior = repmat(mean(D),size(ptprior,1),1);reshape(ptprior',1,numel(ptprior)); Dvec = reshape(D',1,numel(D)); % Calculate weights using logistic regression % Calculate weights % v = logist_weighted(x,truth,v,Dvec',show,regularize,lambda,lambdasearch,eigvalratio); % without nully distribution v = logist_weighted_betatest_v3p0(x,truth,v,Dvec',show,regularize,lambda,lambdasearch,eigvalratio,nully,trialnum,ptpriorvec',useOffset); % calculate logistic regression weights if ~useOffset v(end) = 0; end y = x*v(1:end-1) + v(end); % calculate y values given these weights % yprev = x*vprev(1:end-1) + vprev(end); % Compute the true log-likelihood value: sum_over_trials(log(sum_over_saccades(p(c|y,ti)*p(ti|y)))) tllv = [tllv sum(log(ComputePosteriorLabel(ptprior,y,truth,forceOneWinner,conditionPrior,nully)))-lambda/4*sum(v(1:end-1).^2)]; % adjust posterior [py, ~] = ComputePosteriorLabel(ptprior,y,ones(size(y)),forceOneWinner,conditionPrior,nully); % Prevent infinite loop if length(iterAz)>MAX_ITER; break; end % Calculate ROC curve and Az value Az = rocarea(py,truth_trials); % find ROC curve iterAz = [iterAz Az]; % Add to list of iteration results % Display results if showaz, fprintf('Window Onset: %d; iteration %d; Az: %6.3f; TLLVold: %.2f, TLLV: %.2f; Pct change in filter weights: %.2f; Weight subspace: %.2f; Average weight/sample (in LR): %.2f\n',... trainingwindowoffset(i),length(iterAz)-1,Az,tllv(end-1),tllv(end),100*sqrt(sum((v-vprev).^2))/sqrt(sum(vprev.^2)),subspace(vprev+eps,v),sum(Dvec)/length(Dvec)); end end % Display results if showaz, fprintf('Window Onset: %d; FINAL Az: %6.3f\n',trainingwindowoffset(i),Az); end AzAll(i) = Az; % record Az value if 0 locs0 = find(truth_trials==0); [~,ord0] = sort(jitter_truth_inds(locs0),'descend'); locs1 = find(truth_trials==1); [~,ord1] = sort(jitter_truth_inds(locs1),'descend'); A = D(locs0(ord0),:); figure; subplot(1,2,1); imagesc(A);colorbar; hold on;scatter(jitter_truth_inds(locs0(ord0)),1:numel(ord0),50,'black','filled'); subplot(1,2,2); A = D(locs1(ord1),:); imagesc(A);colorbar; hold on;scatter(jitter_truth_inds(locs1(ord1)),1:numel(ord1),50,'black','filled'); [~,q]=max(D,[],2);corr(q,jitter_truth_inds') mp1=0;mp2=0;for j=1:numel(jitter_truth_inds);mp1=mp1+D(j,jitter_truth_inds(j));mp2=mp2+ptprior(j,jitter_truth_inds(j));end;[mp1,mp2]/numel(jitter_truth_inds) end % Compute forward model [D,~] = ComputePosterior(ptprior,y,truth,weightprior,forceOneWinner,conditionPrior,nully); % Get posterior one last time Dvec = reshape(D',1,numel(D)); Dmat = repmat(Dvec',1,size(x,2)); % Make a matrix the size of x a = y \ (x.*Dmat); % weight x by Dmat before dividing % Save newly-determined weights and forward model to EEG struct ALLEEG(setlist(1)).icaweights(i,chansubset)=v(1:end-1)'; ALLEEG(setlist(2)).icaweights(i,chansubset)=v(1:end-1)'; ALLEEG(setlist(1)).icawinv(chansubset,i)=a'; % consider replacing with asetlist1 ALLEEG(setlist(2)).icawinv(chansubset,i)=a'; % consider replacing with asetlist2 % Save weights to output vout(i,:) = v'; end; % Save settings to etc field of struct if conditionPrior pop_settings.null_mu = nully.mu; pop_settings.null_sigma = nully.sigma; else pop_settings.null_mu = NaN; pop_settings.null_sigma = NaN; end ALLEEG(setlist(1)).etc.pop_settings = pop_settings; ALLEEG(setlist(2)).etc.pop_settings = pop_settings; ALLEEG(setlist(1)).etc.posteriors = D(truth_trials==0, :); ALLEEG(setlist(2)).etc.posteriors = D(truth_trials==1, :); % Declare command string for output com = sprintf('pop_logisticregression_jittered_EM( %s, [%s], [%s], [%s], [%s]);',... inputname(1), num2str(setlist), num2str(chansubset), ... num2str(trainingwindowlength), num2str(trainingwindowoffset)); fprintf('Done.\n'); return; end % function pop_logisticregression_jittered %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTIONS % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [muX,covarX] = GetNullDistribution(data1,data2,thistrainingwindowoffset,jitterrange) % Crop data to null parts % inull = [1:(thistrainingwindowoffset+jitterrange(1)-1), (thistrainingwindowoffset+jitterrange(2)+trainingwindowlength):length(data1)]; inull = [1:(thistrainingwindowoffset+jitterrange(1)-1), (thistrainingwindowoffset+jitterrange(2)+1):size(data1,2)]; X = cat(3,data1(:,inull,:),data2(:,inull,:)); X = reshape(X,[size(X,1),size(X,3)*length(inull)]); % Get mean and std muX = mean(X,2); covarX = X*X'/size(X,2); % if y=v*X, std(y,1)=sqrt(v*covarX*v'-v*muX^2); % if y=w*X+b, std(y,1) = sqrt(w*covarX*w' + w*muX*muX'*w') end % function GetNullDistribution % FUNCTION AssembleData: % Put de-jittered data into [(N*T) x D] matrix for input into logist function [x, trialnum] = AssembleData(data1,data2,thistrainingwindowoffset,jitterrange) % Declare constants iwindow = (thistrainingwindowoffset+jitterrange(1)) : (thistrainingwindowoffset+jitterrange(2)); % Concatenate trials from 2 datasets x = cat(3,data1(:,iwindow,:),data2(:,iwindow,:)); trialnum = repmat(reshape(1:size(x,3), 1,1,size(x,3)), 1, size(x,2)); % Reshape into 2D matrix x = reshape(x,[size(x,1),size(x,3)*length(iwindow)])'; trialnum = reshape(trialnum,[size(trialnum,1),size(trialnum,3)*length(iwindow)])'; end % function AssembleData function [posteriorLabel, condprior] = ComputePosteriorLabel(prior, y, truth, forceOneWinner,conditionPrior,nully) % Put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % Calculate likelihood likelihood = bernoull(truthmat,ymat); % Condition prior on y value: more extreme y values indicate more informative time points if conditionPrior condprior = exp(abs(ymat)).*prior; % condprior = (1-normpdf(ymat,nully.mu,nully.sigma*nully.sigmamultiplier)/normpdf(0,0,nully.sigma*nully.sigmamultiplier)).*prior; % prior conditioned on y (p(t|y)) condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % normalize so each trial sums to 1 else condprior = prior; end % Calculate posterior label posterior = likelihood.*condprior; if forceOneWinner posterior2 = (1-likelihood).*condprior; p = max(posterior,[],2); p2 = max(posterior2,[],2); posteriorLabel = p./(p+p2); else posteriorLabel = sum(posterior,2); end end % function ComputePosteriorLabel function [posterior,likelihood,condprior] = ComputePosterior(prior, y, truth,weightprior,forceOneWinner,conditionPrior,nully) % Put y and truth into matrix form ntrials = size(prior,1); ymat = reshape(y,length(y)/ntrials,ntrials)'; truthmat = reshape(truth,length(truth)/ntrials,ntrials)'; % Calculate likelihood likelihood = bernoull(truthmat,ymat); % Condition prior on y value: more extreme y values indicate more informative time points if conditionPrior % (NOTE: normalization not required, since we normalize later) % condprior = (1-normpdf(ymat,nully.mu,nully.sigma*nully.sigmamultiplier)/normpdf(0,0,nully.sigma*nully.sigmamultiplier)).*prior; % prior conditioned on y (p(t|y)) condprior = exp(abs(ymat)).*prior; else condprior = prior; end condprior = condprior./repmat(sum(condprior,2),1,size(condprior,2)); % Calculate posterior posterior = likelihood.*condprior; % If requested, make all posteriors 0 except max if forceOneWinner [~,iMax] = max(posterior,[],2); % finds max posterior on each trial (takes first one if there's a tie) posterior = full(sparse(1:size(posterior,1),iMax,1,size(posterior,1),size(posterior,2))); % zeros matrix with 1's at the iMax points in each row end % Normalize rows posterior = posterior./repmat(sum(posterior,2),1,size(posterior,2)); % Re-weight priors according to the number of trials in each class if weightprior posterior(truthmat(:,1)==1,:) = posterior(truthmat(:,1)==1,:) / sum(truthmat(:,1)==1); posterior(truthmat(:,1)==0,:) = posterior(truthmat(:,1)==0,:) / sum(truthmat(:,1)==0); end end % function ComputePosterior function PlotDebugFigures(iter,v,D,priorrange,lkhd,cndp,py,iTrialToPlot,ALLEEG) % Set up nRows = 2; nCols = 2; iPlot = mod(iter,nRows*nCols)+1; [jitter_truth,truth_trials] = GetJitter(ALLEEG,'facecar'); n1 = ALLEEG(1).trials; n2 = ALLEEG(2).trials; % Initialize figures if iter==0 for iFig = 111:117 figure(iFig); clf; end end % Plot v figure(111); subplot(nRows,nCols,iPlot); cla; topoplot(v(1:end-1),ALLEEG(2).chanlocs); title(sprintf('iter %d weight vector (raw)\n (bias = %0.2g)(t=%gs)',iter,v(end),NaN)) colorbar; % Plot likelihood figure(112); subplot(nRows,nCols,iPlot); cla; hold on; ImageSortedData(lkhd(1:n1,:),priorrange,1:n1,jitter_truth(1:n1)); colorbar; ImageSortedData(lkhd(n1+1:end,:),priorrange,n1+(1:n2),jitter_truth(n1+1:end)); colorbar; axis([min(priorrange) max(priorrange) 1 n1+n2]) title(sprintf('iter %d Likelihood',iter)); xlabel('Jitter (samples)'); ylabel('Trial'); % Plot conditioned prior figure(113); subplot(nRows,nCols,iPlot); cla; hold on; ImageSortedData(cndp(1:n1,:),priorrange,1:n1,jitter_truth(1:n1)); colorbar; ImageSortedData(cndp(n1+1:end,:),priorrange,n1+(1:n2),jitter_truth(n1+1:end)); colorbar; axis([min(priorrange) max(priorrange) 1 n1+n2]) title(sprintf('iter %d Conditioned Prior',iter)); xlabel('Jitter (samples)'); ylabel('Trial'); % Plot D figure(114); subplot(nRows,nCols,iPlot); cla; hold on; ImageSortedData(D(1:n1,:),priorrange,1:n1,jitter_truth(1:n1)); colorbar; ImageSortedData(D(n1+1:end,:),priorrange,n1+(1:n2),jitter_truth(n1+1:end)); colorbar; title(sprintf('iter %d Posteriors',iter)); axis([min(priorrange) max(priorrange) 1 n1+n2]) xlabel('Jitter (samples)'); if iter==0 title(sprintf('Priors p(t_i,c_i)')) end ylabel('Trial'); % Plot probability of labels figure(115); subplot(nRows,nCols,iPlot); cla; hold on; plot(py); axis([1 n1+n2 0 1]) PlotVerticalLines(n1+0.5,'r--'); title(sprintf('iter %d p(c=1)',iter)); xlabel('Trial'); ylabel('Probability'); % Plot MAP jitter vs. posterior at that jitter figure(116); subplot(nRows,nCols,iPlot); cla; hold on; [~,maxinds] = max(D,[],2); locs = find(truth_trials==0)'; jittervals = priorrange(1):priorrange(2); scatter(jittervals(maxinds(locs)),D(sub2ind(size(D),locs,maxinds(locs))),50,'blue','filled'); locs = find(truth_trials==1)'; scatter(jittervals(maxinds(locs)),D(sub2ind(size(D),locs,maxinds(locs))),50,'red','filled'); if priorrange(2)>priorrange(1) xlim([priorrange(1),priorrange(2)]); end title(sprintf('iter %d MAP jitter',iter)); legend('MAP jitter values (l=0)','MAP jitter values (l=1)','Location','Best'); xlabel('Jitter (samples)'); ylabel('Posterior at that jitter'); % Plot posterior of single trial figure(117); subplot(nRows,nCols,iPlot); cla; hold on; plot((priorrange(1):priorrange(2))*1000/ALLEEG(1).srate,D(iTrialToPlot,:)); PlotVerticalLines(jitter_truth(iTrialToPlot),'r--'); xlabel('time (ms)') ylabel('p(t_i | c_i, y_i)') title(sprintf('iter %d Posterior of trial %d',iter,iTrialToPlot)) if iter==0 ylabel('p(t_i)') title(sprintf('Prior distribution of trial i=%d',iTrialToPlot)) end pause(0.5); end
github
djangraw/FelixScripts-master
distinguishable_colors.m
.m
FelixScripts-master/MATLAB/FormatFigures/distinguishable_colors.m
5,753
utf_8
57960cf5d13cead2f1e291d1288bccb2
function colors = distinguishable_colors(n_colors,bg,func) % DISTINGUISHABLE_COLORS: pick colors that are maximally perceptually distinct % % When plotting a set of lines, you may want to distinguish them by color. % By default, Matlab chooses a small set of colors and cycles among them, % and so if you have more than a few lines there will be confusion about % which line is which. To fix this problem, one would want to be able to % pick a much larger set of distinct colors, where the number of colors % equals or exceeds the number of lines you want to plot. Because our % ability to distinguish among colors has limits, one should choose these % colors to be "maximally perceptually distinguishable." % % This function generates a set of colors which are distinguishable % by reference to the "Lab" color space, which more closely matches % human color perception than RGB. Given an initial large list of possible % colors, it iteratively chooses the entry in the list that is farthest (in % Lab space) from all previously-chosen entries. While this "greedy" % algorithm does not yield a global maximum, it is simple and efficient. % Moreover, the sequence of colors is consistent no matter how many you % request, which facilitates the users' ability to learn the color order % and avoids major changes in the appearance of plots when adding or % removing lines. % % Syntax: % colors = distinguishable_colors(n_colors) % Specify the number of colors you want as a scalar, n_colors. This will % generate an n_colors-by-3 matrix, each row representing an RGB % color triple. If you don't precisely know how many you will need in % advance, there is no harm (other than execution time) in specifying % slightly more than you think you will need. % % colors = distinguishable_colors(n_colors,bg) % This syntax allows you to specify the background color, to make sure that % your colors are also distinguishable from the background. Default value % is white. bg may be specified as an RGB triple or as one of the standard % "ColorSpec" strings. You can even specify multiple colors: % bg = {'w','k'} % or % bg = [1 1 1; 0 0 0] % will only produce colors that are distinguishable from both white and % black. % % colors = distinguishable_colors(n_colors,bg,rgb2labfunc) % By default, distinguishable_colors uses the image processing toolbox's % color conversion functions makecform and applycform. Alternatively, you % can supply your own color conversion function. % % Example: % c = distinguishable_colors(25); % figure % image(reshape(c,[1 size(c)])) % % Example using the file exchange's 'colorspace': % func = @(x) colorspace('RGB->Lab',x); % c = distinguishable_colors(25,'w',func); % Copyright 2010-2011 by Timothy E. Holy % Parse the inputs if (nargin < 2) bg = [1 1 1]; % default white background else if iscell(bg) % User specified a list of colors as a cell aray bgc = bg; for i = 1:length(bgc) bgc{i} = parsecolor(bgc{i}); end bg = cat(1,bgc{:}); else % User specified a numeric array of colors (n-by-3) bg = parsecolor(bg); end end % Generate a sizable number of RGB triples. This represents our space of % possible choices. By starting in RGB space, we ensure that all of the % colors can be generated by the monitor. n_grid = 30; % number of grid divisions along each axis in RGB space x = linspace(0,1,n_grid); [R,G,B] = ndgrid(x,x,x); rgb = [R(:) G(:) B(:)]; if (n_colors > size(rgb,1)/3) error('You can''t readily distinguish that many colors'); end % Convert to Lab color space, which more closely represents human % perception if (nargin > 2) lab = func(rgb); bglab = func(bg); else C = makecform('srgb2lab'); lab = applycform(rgb,C); bglab = applycform(bg,C); end % If the user specified multiple background colors, compute distances % from the candidate colors to the background colors mindist2 = inf(size(rgb,1),1); for i = 1:size(bglab,1)-1 dX = bsxfun(@minus,lab,bglab(i,:)); % displacement all colors from bg dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color end % Iteratively pick the color that maximizes the distance to the nearest % already-picked color colors = zeros(n_colors,3); lastlab = bglab(end,:); % initialize by making the "previous" color equal to background for i = 1:n_colors dX = bsxfun(@minus,lab,lastlab); % displacement of last from all colors on list dist2 = sum(dX.^2,2); % square distance mindist2 = min(dist2,mindist2); % dist2 to closest previously-chosen color [~,index] = max(mindist2); % find the entry farthest from all previously-chosen colors colors(i,:) = rgb(index,:); % save for output lastlab = lab(index,:); % prepare for next iteration end end function c = parsecolor(s) if ischar(s) c = colorstr2rgb(s); elseif isnumeric(s) && size(s,2) == 3 c = s; else error('MATLAB:InvalidColorSpec','Color specification cannot be parsed.'); end end function c = colorstr2rgb(c) % Convert a color string to an RGB value. % This is cribbed from Matlab's whitebg function. % Why don't they make this a stand-alone function? rgbspec = [1 0 0;0 1 0;0 0 1;1 1 1;0 1 1;1 0 1;1 1 0;0 0 0]; cspec = 'rgbwcmyk'; k = find(cspec==c(1)); if isempty(k) error('MATLAB:InvalidColorString','Unknown color string.'); end if k~=3 || length(c)==1, c = rgbspec(k,:); elseif length(c)>2, if strcmpi(c(1:3),'bla') c = [0 0 0]; elseif strcmpi(c(1:3),'blu') c = [0 0 1]; else error('MATLAB:UnknownColorString', 'Unknown color string.'); end end end
github
SoheilFeizi/Tensor-Biclustering-master
th_ind_fibers.m
.m
Tensor-Biclustering-master/th_ind_fibers.m
837
utf_8
eab514d9abaedf43e26bc3382b81f1f1
%function [J1,J2]=th_ind_fibers(T,k1,k2) % T is the input tensor of size n1 x n2 x m % |J_1|=k1 and |J_2|=k2 % J1: subspace row index set % J2: subspace column index set % Ref: Tensor Biclustering % By Soheil Feizi, Hamid Javadi and David Tse % NIPS 2017 %************************************** function [J1,J2]=th_ind_fibers(T,k1,k2) [n1,n2,m]=size(T); D=zeros(n1,n2); for i=1:n1 for j=1:n2 temp=zeros(1,m); temp(:)=T(i,j,:); D(i,j)=norm(temp); end end [~,I_x]=sort(D(:),'descend'); J12=I_x(1:k1*k2); A=zeros(n1,n2); for i=1:k1*k2 [j11,j22]=ind2sub(size(A),J12(i)); A(j11,j22)=1; end %****************** % Selecting k1 rows and k2 columns of A with the most number of 1's [~,I_c]=sort(sum(A),'descend'); J2=I_c(1:k2); [~,I_r]=sort(sum(A'),'descend'); J1=I_r(1:k1);
github
SoheilFeizi/Tensor-Biclustering-master
th_sum_fibers.m
.m
Tensor-Biclustering-master/th_sum_fibers.m
614
utf_8
1319df50e3f3281535fe04455ee20020
%function [J1,J2]=th_sum_fibers(T,k1,k2) % T is the input tensor of size n1 x n2 x m % |J_1|=k1 and |J_2|=k2 % J1: subspace row index set % J2: subspace column index set % Ref: Tensor Biclustering % By Soheil Feizi, Hamid Javadi and David Tse % NIPS 2017 %************************************** function [J1,J2]=th_sum_fibers(T,k1,k2) [n1,n2,m]=size(T); D=zeros(n1,n2); for i=1:n1 for j=1:n2 temp=zeros(1,m); temp(:)=T(i,j,:); D(i,j)=norm(temp); end end d_c=sum(D); d_r=sum(D'); [~,I_r]=sort(d_r,'descend'); J1=I_r(1:k1); [~,I_c]=sort(d_c,'descend'); J2=I_c(1:k2);
github
SoheilFeizi/Tensor-Biclustering-master
tensor_unfolding_spectral.m
.m
Tensor-Biclustering-master/tensor_unfolding_spectral.m
983
utf_8
ae4e4ae7168b61447feb4f446f0930e4
%function [J1,J2,T_uf,tt]=tensor_unfolding_spectral(T,k1,k2) % T is the input tensor of size n1 x n2 x m % |J_1|=k1 and |J_2|=k2 % T_uf: unfolded tensor % J1: subspace row index set % J2: subspace column index set % Ref: Tensor Biclustering % By Soheil Feizi, Hamid Javadi and David Tse % NIPS 2017 %************************************** function [J1,J2,T_uf]=tensor_unfolding_spectral(T,k1,k2) [n1,n2,m]=size(T); T_uf=zeros(m,n1*n2); for j1=1:n1 for j2=1:n2 T_uf(:,(j1-1)*n2+j2)=T(j1,j2,:); end end [~,~,x]=svds(T_uf,1); [~,I_x]=sort(abs(x),'descend'); J12=I_x(1:k1*k2); A=zeros(n1,n2); for i=1:k1*k2 index=J12(i); if mod(index,n2)~=0 j11=ceil(index/n2); else j11=index/n2; end j22=index-n2*(j11-1); A(j11,j22)=1; end %****************** % Selecting k1 rows and k2 columns of A with the most number of 1's [~,I_c]=sort(sum(A),'descend'); J2=I_c(1:k2); [~,I_r]=sort(sum(A'),'descend'); J1=I_r(1:k1);
github
SoheilFeizi/Tensor-Biclustering-master
tensor_folding_spectral.m
.m
Tensor-Biclustering-master/tensor_folding_spectral.m
865
utf_8
56b0207f0febeb85ebb2a68876cba8eb
%function [J1,J2,T_f1,T_f2]=tensor_folding_spectral(T,k1,k2) % T is the input tensor of size n1 x n2 x m % |J_1|=k1 and |J_2|=k2 % T_f1: folded tensor on rows % T_f2: folded tensor on columns % J1: subspace row index set % J2: subspace column index set % Ref: Tensor Biclustering % By Soheil Feizi, Hamid Javadi and David Tse % NIPS 2017 %************************************** function [J1,J2,T_f1,T_f2]=tensor_folding_spectral(T,k1,k2) [n1,n2,m]=size(T); % folding rows T_f1=zeros(n2,n2); for j=1:n1 Tj=zeros(n2,m); Tj(:,:)=T(j,:,:); Tj=Tj'; T_f1=T_f1+Tj'*Tj; end [w_1,~]=eigs(T_f1,1); [~,I_w1]=sort(abs(w_1),'descend'); J2=I_w1(1:k2); % folding columns T_f2=zeros(n1,n1); for j=1:n2 Tj=zeros(n1,m); Tj(:,:)=T(:,j,:); Tj=Tj'; T_f2=T_f2+Tj'*Tj; end [u_1,~]=eigs(T_f2,1); [~,I_u1]=sort(abs(u_1),'descend'); J1=I_u1(1:k1);
github
mjlaine/dlm-master
dlmfit.m
.m
dlm-master/dlmfit.m
9,456
utf_8
16a0acd5157835eac146e360c0434b1c
function out = dlmfit(y,s,wdiag,x0,C0, X, options) %DLMFIT Fit DLM time series model % Fits dlm time series model with local level, trend, seasonal, and proxies % out = dlmfit(y,s,wdiag,x0,C0, X, options) % Input: % y time series, n*p % s obs uncertainty, n*p or 1*1 % w sqrt of first diagonal entries of the model error matrix W % x0 initial state m*1 (optional, i.e. can be empty) % C0 initial state uncertainty covariance matrix m*m (optional) % X covariate variables n*q (optional) % options structure % order % fullseas % trig % ns % opt % mcmc % Output: % out. % Marko Laine <[email protected]> % $Revision: 0.0 $ $Date: 2013/07/12 12:00:00 $ if nargin < 6 X=[]; % covariates, aka proxies end if nargin < 7 options.trig = 0; options.opt = 0; options.mcmc = 0; end % compatibility for older version if isfield(options,'fullseas'), options.seas=options.fullseas; end if not(isfield(options,'order')), options.order=1; end if not(isfield(options,'trig')), options.trig=0; end if not(isfield(options,'seas')), options.seas=0; end if options.trig>0, options.seas=0; end if not(isfield(options,'fullseas')), options.fullseas=options.seas; end if not(isfield(options,'ns')), options.ns=12; end % number of seasons if not(isfield(options,'mcmc')), options.mcmc=0; end if not(isfield(options,'opt')), options.opt=0; end if not(isfield(options,'maxfuneval')), options.maxfuneval=400; end % fit V factor? if not(isfield(options,'fitv')), options.fitv=0; end % see also options.vcv if not(isfield(options,'winds')), options.winds=[]; end % if not(isfield(options,'logscale')), options.logscale=1; end % if not(isfield(options,'spline')), options.spline=0; end % test % These are the defaults used in the dlm acp paper if not(isfield(options,'varcv')), options.varcv=[1 1 1 1]; end if not(isfield(options,'vcv')), options.vcv=0.5; end % V factor prior CV if not(isfield(options,'nsimu')), options.nsimu=5000; end [G,F] = dlmgensys(options); % generate system matrises [p,m] = size(F); % series states n = length(y); % nobs % add covariates to system matrix G if not(isempty(X)) kk = size(X,2); G(m+1:m+kk,m+1:m+kk) = eye(kk); m = m+kk; end V = ones(n,p).*s; % V is matrix of std's W = zeros(m,m); % model error % input wdiag has diagonal std of W for i=1:length(wdiag); W(i,i) = wdiag(i).^2; end % spline if options.order==1 & options.spline W(1:2,1:2) = wdiag(2).^2 .* [1/3 1/2;1/2 1]; end % try to find sensible initial values (FIX THIS) if nargin < 4 || isempty(x0) x0 = zeros(m,1); % initial x0(1) = meannan(y(1:ceil(options.ns),:)); % how about p>1 (not yet) assume x0(1) is the level % x0(2) = (y(13)-y(1))/12; % crude estimate % if options.trig==0 % x0(3) = sumnan(-y(1:11,:)); % -,,- % end end if nargin<5||isempty(C0) C0diag = ones(1,m)*(abs(x0(1))*0.5).^2; C0diag(C0diag==0) = 1e+7; C0 = diag(C0diag); end % fit, and refit to iterate the initial values out = dlmsmo(y,F,V,x0,G,W,C0, X, 0); x0 = out.x(:,1); C0 = 100*squeeze(out.C(:,:,1)); out = dlmsmo(y,F,V,x0,G,W,C0, X); %% optimization and MCMC calculations if options.opt if isfield(options,'fitfun') % use user given fitfun that returs dlm object out = options.fitfun(out,options); else % default optimization for a V and W out = dlm_dooptim(out,options); end end if options.mcmc if isfield(options,'mcmcfun') out = options.mcmcfun(out,options); else % default MCMC for W and V out = dlm_domcmc(out,options); end end out.s = s; % save original obs std also out.options = options; out.class = 'dlmfit'; %% some helper functions function out = dlm_dooptim(dlm,options) % this optimizes some parameters defining the DLM model % the costfun is at the end if options.fitv > 0; vinds = 1; else vinds = []; end % winds = map from diag(W) to optimized parameter winds = options.winds; nw = max(winds); if isfield(options,'fitar') && options.fitar>0 ginds = findarinds(options); else ginds = []; end zfun = @(x) dlm_costfun(x,dlm,vinds,winds,ginds); W = dlm.W; V = dlm.V; G = dlm.G; if length(vinds)>0; v0 = 1; else v0 = []; end w0 = zeros(nw,1); for i=1:length(w0) ii=find(winds==i,1); w0(i)=sqrt(W(ii,ii)); end if length(ginds)>0 g0 = options.arphi(:); else g0 = []; end w00 = [log([v0;w0]);g0]; inds = [ones(size(v0));ones(size(w0))*2;ones(size(g0))*3]; oo = optimset('disp','iter','maxfuneval',options.maxfuneval); wopt = fminsearch(zfun,w00,oo); woptv = exp(wopt(inds==1)) woptw = exp(wopt(inds==2)) woptg = wopt(inds==3) if length(vinds)>0; V = V.*woptv; end for i=1:length(winds); if winds(i)>0; W(i,i) = woptw(winds(i)).^2; end; end arinds = findarinds(options); if length(ginds)>0 G(arinds,arinds(1)) = woptg; end out = dlmsmo(dlm.y,dlm.F,V,dlm.x0,G,W,dlm.C0,dlm.XX); function out = dlm_costfun(x,dlm,vinds,winds,ginds) % Helper function for dlm parameter fitting W = dlm.W; V = dlm.V; G = dlm.G; nv = length(vinds); nw = max(winds); ng = length(ginds); if nv>0; V=V.*exp(x(1)); end for i=1:length(winds) if winds(i)>0; W(i,i)=exp(x(winds(i)+nv)).^2; end end if ng>0 G(ginds,ginds(1)) = x(nv+nw+1:end); end if exist('dlmmex') == 3 % mex boosted likelihood calculations out = dlmmex(dlm.y,dlm.F,V,dlm.x0,G,W,dlm.C0,dlm.XX); else out = getfield(dlmsmo(dlm.y,dlm.F,V,dlm.x0,G,W,dlm.C0,dlm.XX,0,0),'lik'); end function out = dlm_domcmc(dlm,options) % this does MCMC for model parameters % fit a coefficient for obs error if options.fitv > 0; vinds = 1; else vinds = []; end % winds = map from diag(W) to optimized parameter winds = options.winds; nw = max(winds); if isfield(options,'fitar') && options.fitar>0 ginds = findarinds(options); else ginds = []; end % save current values W = dlm.W; V = dlm.V; G = dlm.G; % initial values if length(vinds)>0; v0 = 1; else v0 = []; end w0 = zeros(nw,1); for i=1:length(w0) ii=find(winds==i,1); w0(i)=sqrt(W(ii,ii)); end w0ini = w0; % use option for initial values, must be of length w0 if isfield(options,'varini') if length(options.varini) == length(w0) w0ini = options.varini(:); else error('options.varini length does not match') end end if length(ginds)>0 g0 = options.arphi(:); else g0 = []; end w00 = [log([v0;w0]);g0]; inds = [ones(size(v0));ones(size(w0))*2;ones(size(g0))*3]; if options.logscale ffun=@(x)log(x); bfun=@(x)exp(x); parmin = -Inf; else ffun=@(x)(x); bfun=@(x)(x); parmin = 0; end npar = length(w00); p = cell(0); i1 = 0; for i=1:length(v0) i1 = i1+1; p{i1} = {'Vfact',ffun(v0(i)),parmin,Inf,NaN,options.vcv(i)}; end for i=1:length(w0) i1 = i1+1; ii = find(winds==i,1); % p{i1} = {sprintf('w%d',ii),ffun(w0(i)),parmin,Inf,NaN,options.varcv(i)}; p{i1} = {sprintf('w%d',ii),ffun(w0ini(i)),parmin,Inf,ffun(w0(i)),options.varcv(i)}; end for i=1:length(g0) i1 = i1+1; % bound [0,1] for AR rho is fixed here for now p{i1} = {sprintf('g%d',i),g0(i),0,1,NaN,options.gcv(i)}; end m = struct; o = struct; if options.logscale m.ssfun = @(th,d) fitfun_mcmc(th,dlm,vinds,winds,ginds); m.priorfun = @(th,m,s) sum(((th-m)./s).^2); % normal prior m.priortype = 1; % else m.ssfun = @(th,d) error('not defined yet'); m.priorfun = @(th,m,s) sum((log(th./m)./s).^2); % lognormal prior m.priortype=-1; % for lognormal prior in densplot end o.qcov = eye(length(w00)); i1 = 0; for i=1:length(v0) i1 = i1+1; o.qcov(i1,i1) = 0.1; % proposal for V fact fixed here end for i=1:length(w0) i1 = i1+1; o.qcov(i1,i1) = abs(p{i1}{2})*0.002; % W diag paramrs proposal if o.qcov(i1,i1) == 0, o.qcov(i1,i1) = 1; end end for i=1:length(g0) i1 = i1+1; o.qcov(i1,i1) = 0.01; % propsal for AR rhos end o.nsimu = options.nsimu; o.method = 'am'; o.adaptint = 100; o.initqcovn = 200; o.verbosity = 1; [res,chain,~,sschain] = mcmcrun(m,[],p,o); wopt = mean(chain(fix(size(chain,1)/2):end,:)); % use the last half woptv = bfun(wopt(inds==1)) woptw = bfun(wopt(inds==2)) woptg = wopt(inds==3) if length(vinds)>0; V = V.*woptv; end for i=1:length(winds); if winds(i)>0; W(i,i) = woptw(winds(i)).^2; end; end arinds = findarinds(options); if length(ginds)>0 G(arinds,arinds(1)) = woptg; end out = dlmsmo(dlm.y,dlm.F,V,dlm.x0,G,W,dlm.C0,dlm.XX); if options.logscale % scale chain back to stds ii = (inds ==1|inds==2); chain(:,ii) = bfun(chain(:,ii)); res.prior(ii,1)=exp(res.prior(ii,1)); res.priorfun = @(th,m,s) sum((log(th./m)./s).^2); res.priortype=-1; end out.res = res; out.chain = chain; out.sschain = sschain; out.winds = winds; out.vinds = vinds; out.ginds = ginds; function out = fitfun_mcmc(x,dlm,vinds,winds,ginds) % Helper function for dlm parameter fitting W = dlm.W; V = dlm.V; G = dlm.G; nv = length(vinds); nw = max(winds); ng = length(ginds); if nv>0; V=V.*exp(x(1)); end for i=1:length(winds) if winds(i)>0; W(i,i)=exp(x(winds(i)+nv)).^2; end end if ng>0 G(ginds,ginds(1)) = x(nv+nw+1:end); end if exist('dlmmex') == 3 % mex boosted likelihood calculations out = dlmmex(dlm.y,dlm.F,V,dlm.x0,G,W,dlm.C0,dlm.XX); else out = getfield(dlmsmo(dlm.y,dlm.F,V,dlm.x0,G,W,dlm.C0,dlm.XX,0,0),'lik'); end function i = findarinds(options) % find AR indeces if not(isfield(options,'arphi')); i = []; return; end nar = length(options.arphi); i = 1; i = i + options.order + 1; if options.fullseas==1 i = i + 11; elseif options.trig>0 i = i+min(options.ns-1,options.trig*2); end i = i:i+nar-1;
github
mjlaine/dlm-master
dlmtsfit.m
.m
dlm-master/dlmtsfit.m
4,598
utf_8
7e6455cae73adee4ca81690c60f6759a
function out=dlmtsfit(t,y,s,X,options) % Fit a time series model % t time in matlab format % y n*p data matrix % s n*p std uncertainty % X n*nx proxy variables if nargin < 4 X = []; end if nargin < 5 options = []; end % remove NaN's from the begining and end i0 = isnan(s) | s<=0; y(i0) = NaN; if size(y,2)>1 i1 = find(not(all(isnan(y'))'),1,'first')-1; i2 = find(not(all(isnan(y'))'),1,'last')+1; else i1 = find(not(isnan(y)),1,'first')-1; i2 = find(not(isnan(y)),1,'last')+1; end y([1:i1,i2:end],:) = []; s([1:i1,i2:end],:) = []; t([1:i1,i2:end],:) = []; % scale y with a global scale for all columns ys = meannan(stdnan(y)); y = y./ys; s = s./ys; o = options; o.trig = getopt(o,'trig',1); o.ns = getopt(o,'ns',12); o.order = getopt(o,'order',1); o.arphi = getopt(o,'arphi',[]); o.trend = getopt(o,'trend',struct()); o.seas = getopt(o,'seas',struct()); o.ar = getopt(o,'ar',struct()); o.level = getopt(o,'level',struct()); o.level.sig = getopt(o.level,'sig',0); o.level.clen = getopt(o.level,'clen',0); o.level.tau = getopt(o.level,'tau',0); o.trend.sig = getopt(o.trend,'sig',0.001); o.trend.clen = getopt(o.trend,'clen',5); o.trend.tau = getopt(o.trend,'tau',0); o.seas.sig = getopt(o.seas,'sig',0.001); o.seas.clen = getopt(o.seas,'clen',5); o.seas.tau = getopt(o.seas,'tau',0); o.ar.sig = getopt(o.ar,'sig',0.001); o.ar.clen = getopt(o.ar,'clen',5); o.ar.tau = getopt(o.ar,'tau',0); o.solar = getopt(o,'solar',0); o.qbo = getopt(o,'qbo',0); o.refit = getopt(o,'refit',0); if o.solar X = solarfun(t,1); % fix missing solar, at the end, hopefully ii = find(isnan(X)); y(ii,:) = []; s(ii,:) = []; t(ii,:) = []; X(ii,:) = []; end if o.qbo X = [X,qbofun(t,1)]; ii = find(isnan(X(:,2))); y(ii,:) = []; s(ii,:) = []; t(ii,:) = []; X(ii,:) = []; end % not used %o.opt = 0; %o.fitv = 0; % %o.maxfuneval = 1000; %o.winds = [0, 1, 2*ones(1,o.trig*2), ones(1,length(o.arphi)>0)*3]; %o.fitar = length(o.arphi)>0; % % generate system matrices [G0,F0] = dlmgensys(o); p = size(y,2); G = kron(G0,eye(p)); F = kron(F0,eye(p)); n = size(y,1); q = size(F,2); q0 = size(F0,2); nx = size(X,2); % distance based covariance matrix needed for multicolumn data, % correlation beween columns distmat = toeplitz(0:p-1); cfun = @(d,phi) exp(-abs(d)/phi); %cfun = @(d,phi) exp(-0.5.*(d/phi).^2); cmatfun = @(sig,phi,tau) sig.^2*cfun2(distmat,phi) + eye(size(distmat))*tau.^2; % generate full matrices for all columns W1 = zeros(p,p); % level W1 = cmatfun(o.level.sig,o.level.clen,o.level.tau); % trend W2 = cmatfun(o.trend.sig,o.trend.clen,o.trend.tau); % trend W3 = cmatfun(o.seas.sig,o.seas.clen, o.seas.tau); % seas stack = @(a,b)[a,zeros(size(a,1),size(b,2));zeros(size(b,1),size(a,2)),b]; W = stack(W1,W2); for i=1:o.trig W = stack(W,W3); W = stack(W,W3); end if length(o.arphi)>0 % AR W4 = cmatfun(o.ar.sig,o.ar.clen,o.ar.tau); W = stack(W,W4); end % for the proxies for i=1:nx W = stack(W,W1); % add W G(q+1:q+p,q+1:q+p) = eye(p); % grow G, F is taken care of by dlmsmo (fix this) q = q + p; % p more states needed end % initial values x0 = zeros(q,1); x0(1:p) = y(1,:); x0(find(isnan(y(1,:)))) = 0; C0 = eye(q,q); % run dlmsmo out = dlmsmo(y,F,s,x0,G,W,C0, X, 0, 1, 0); % again, with new initial values, as in dlmfit if o.refit x0 = out.x(:,1); C0 = 1*squeeze(out.C(:,:,1)); out = dlmsmo(y,F,s,x0,G,W,C0, X, 0, 1, 0); end % save some extra elements if isfield(o,'label') out.label = o.label; end out.ys = ys; out.y = y; out.s = s; out.time = t; out.options = o; p = size(out.F,1); % find out the indexes of various state elements, level, seas, ar, X if p==1 ii = 1; out.inds.level = ii; ii = ii + o.order + 1; out.inds.seas = ii:ii+2*o.trig-1; ii = ii+2*o.trig; out.inds.ar = ones(length(o.arphi),1)+ii-1; ii = length(o.arphi) + ii; if size(X,2)>0 out.inds.X = ii:ii+size(X,2)-1; else out.inds.X = []; end else ii = 1; out.inds.level = reshape(ii:p,p,1); ii = ii*p + o.order*p + 1; out.inds.seas = ii:ii+(2*o.trig)*p-1; out.inds.seas = reshape(out.inds.seas,p,numel(out.inds.seas)/p); ii = ii+(2*o.trig)*p; % out.inds.ar = ones(1,length(o.arphi)*p)+ii-1; out.inds.ar = ii:(length(o.arphi)*p)+ii-1; out.inds.ar = reshape(out.inds.ar,p,numel(out.inds.ar)/p); ii = length(o.arphi)*p + ii; if size(X,2)>0 out.inds.X = ii:ii+size(X,2)*p-1; out.inds.X = reshape(out.inds.X,p,numel(out.inds.X)/p); else out.inds.X = []; end end function y=cfun2(d,phi) %y = exp(-abs(d)/phi); y = exp(-0.5*d.^2./phi.^2); y(isnan(y))=1;
github
mjlaine/dlm-master
dlmdisp.m
.m
dlm-master/dlmdisp.m
1,219
utf_8
c95234faa3b98756663e9c521151e59d
function out = dlmdisp(dlm) %DLMDISP print information about the DLM fit % Marko Laine <[email protected]> % $Revision: 0.0 $ $Date: 2015/06/03 12:00:00 $ if not(isstruct(dlm)) || not(strcmp(dlm.class,'dlmfit')||strcmp(dlm.class,'dlmsmo')) error('works only for dlm output structure'); end fprintf('DLM model output\n'); if strcmp(dlm.class,'dlmfit') fprintf('Model options\n') fprintf(' order: %d\n',dlm.options.order) if dlm.options.fullseas fprintf(' fullseas\n') else fprintf(' trig: %d\n',dlm.options.trig) end if not(isempty(dlm.options.arphi)) fprintf(' AR(%d): %d\n',length(dlm.options.arphi)) end if isfield(dlm,'chain') fprintf('MCMC: npar %d, nsimu: %d, rejected %0.3g%%\n', ... size(dlm.chain,2), size(dlm.chain,1),dlm.res.rejected*100); end fprintf('\n'); end %fprintf('Observations %d\n',dlm.nobs); nprint('Observations: ', '%d ',dlm.nobs); nprint('RMSE: ','%.3g ',sqrt(dlm.mse)); nprint('MAPE: ','%.3g ',dlm.mape); nprint('sigma: ', '%.4g ',sqrt(dlm.s2)); nprint('likelihood: ','%g ',dlm.lik); fprintf('\n'); if nargout>0 out=dlm; end function nprint(s,f,x) fprintf('%s',s); fprintf(f,x); fprintf('\n');
github
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week8 - K-Means Clustering, PCA/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
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week8 - K-Means Clustering, PCA/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week8 - K-Means Clustering, PCA/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week8 - K-Means Clustering, PCA/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week8 - K-Means Clustering, PCA/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week8 - K-Means Clustering, PCA/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week3 - Logistic Regression/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
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week3 - Logistic Regression/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week3 - Logistic Regression/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week3 - Logistic Regression/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week3 - Logistic Regression/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week3 - Logistic Regression/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week6 - Regularized Linear Regression and Bias or Variance/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
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week6 - Regularized Linear Regression and Bias or Variance/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week6 - Regularized Linear Regression and Bias or Variance/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week6 - Regularized Linear Regression and Bias or Variance/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week6 - Regularized Linear Regression and Bias or Variance/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week6 - Regularized Linear Regression and Bias or Variance/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week9 - Anomaly Detection and Recommender Systems/ex8/submit.m
2,135
utf_8
eebb8c0a1db5a4df20b4c858603efad6
function submit() addpath('./lib'); conf.assignmentSlug = 'anomaly-detection-and-recommender-systems'; conf.itemName = 'Anomaly Detection and Recommender Systems'; conf.partArrays = { ... { ... '1', ... { 'estimateGaussian.m' }, ... 'Estimate Gaussian Parameters', ... }, ... { ... '2', ... { 'selectThreshold.m' }, ... 'Select Threshold', ... }, ... { ... '3', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Cost', ... }, ... { ... '4', ... { 'cofiCostFunc.m' }, ... 'Collaborative Filtering Gradient', ... }, ... { ... '5', ... { 'cofiCostFunc.m' }, ... 'Regularized Cost', ... }, ... { ... '6', ... { 'cofiCostFunc.m' }, ... 'Regularized Gradient', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId, auxstring) % Random Test Cases n_u = 3; n_m = 4; n = 5; X = reshape(sin(1:n_m*n), n_m, n); Theta = reshape(cos(1:n_u*n), n_u, n); Y = reshape(sin(1:2:2*n_m*n_u), n_m, n_u); R = Y > 0.5; pval = [abs(Y(:)) ; 0.001; 1]; Y = (Y .* double(R)); % set 'Y' values to 0 for movies not reviewed yval = [R(:) ; 1; 0]; params = [X(:); Theta(:)]; if partId == '1' [mu sigma2] = estimateGaussian(X); out = sprintf('%0.5f ', [mu(:); sigma2(:)]); elseif partId == '2' [bestEpsilon bestF1] = selectThreshold(yval, pval); out = sprintf('%0.5f ', [bestEpsilon(:); bestF1(:)]); elseif partId == '3' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', J(:)); elseif partId == '4' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 0); out = sprintf('%0.5f ', grad(:)); elseif partId == '5' [J] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', J(:)); elseif partId == '6' [J, grad] = cofiCostFunc(params, Y, R, n_u, n_m, ... n, 1.5); out = sprintf('%0.5f ', grad(:)); end end
github
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week9 - Anomaly Detection and Recommender Systems/ex8/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week9 - Anomaly Detection and Recommender Systems/ex8/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week9 - Anomaly Detection and Recommender Systems/ex8/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week9 - Anomaly Detection and Recommender Systems/ex8/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week9 - Anomaly Detection and Recommender Systems/ex8/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
porterStemmer.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week7 - Support Vector Machines and Kernels/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week4 - Neural Networks Representation/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
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week4 - Neural Networks Representation/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week4 - Neural Networks Representation/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week4 - Neural Networks Representation/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week4 - Neural Networks Representation/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
github
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week4 - Neural Networks Representation/ex3/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week5 - Neural Networks Learning/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
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week5 - Neural Networks Learning/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week5 - Neural Networks Learning/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week5 - Neural Networks Learning/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week5 - Neural Networks Learning/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week5 - Neural Networks Learning/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
bodlaranjithkumar/MachineLearning-master
submit.m
.m
MachineLearning-master/Week2 - Linear Regression/ex1/submit.m
1,876
utf_8
8d1c467b830a89c187c05b121cb8fbfd
function submit() addpath('./lib'); conf.assignmentSlug = 'linear-regression'; conf.itemName = 'Linear Regression with Multiple Variables'; conf.partArrays = { ... { ... '1', ... { 'warmUpExercise.m' }, ... 'Warm-up Exercise', ... }, ... { ... '2', ... { 'computeCost.m' }, ... 'Computing Cost (for One Variable)', ... }, ... { ... '3', ... { 'gradientDescent.m' }, ... 'Gradient Descent (for One Variable)', ... }, ... { ... '4', ... { 'featureNormalize.m' }, ... 'Feature Normalization', ... }, ... { ... '5', ... { 'computeCostMulti.m' }, ... 'Computing Cost (for Multiple Variables)', ... }, ... { ... '6', ... { 'gradientDescentMulti.m' }, ... 'Gradient Descent (for Multiple Variables)', ... }, ... { ... '7', ... { 'normalEqn.m' }, ... 'Normal Equations', ... }, ... }; conf.output = @output; submitWithConfiguration(conf); end function out = output(partId) % Random Test Cases X1 = [ones(20,1) (exp(1) + exp(2) * (0.1:0.1:2))']; Y1 = X1(:,2) + sin(X1(:,1)) + cos(X1(:,2)); X2 = [X1 X1(:,2).^0.5 X1(:,2).^0.25]; Y2 = Y1.^0.5 + Y1; if partId == '1' out = sprintf('%0.5f ', warmUpExercise()); elseif partId == '2' out = sprintf('%0.5f ', computeCost(X1, Y1, [0.5 -0.5]')); elseif partId == '3' out = sprintf('%0.5f ', gradientDescent(X1, Y1, [0.5 -0.5]', 0.01, 10)); elseif partId == '4' out = sprintf('%0.5f ', featureNormalize(X2(:,2:4))); elseif partId == '5' out = sprintf('%0.5f ', computeCostMulti(X2, Y2, [0.1 0.2 0.3 0.4]')); elseif partId == '6' out = sprintf('%0.5f ', gradientDescentMulti(X2, Y2, [-0.1 -0.2 -0.3 -0.4]', 0.01, 10)); elseif partId == '7' out = sprintf('%0.5f ', normalEqn(X2, Y2)); end end
github
bodlaranjithkumar/MachineLearning-master
submitWithConfiguration.m
.m
MachineLearning-master/Week2 - Linear Regression/ex1/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
bodlaranjithkumar/MachineLearning-master
savejson.m
.m
MachineLearning-master/Week2 - Linear Regression/ex1/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
bodlaranjithkumar/MachineLearning-master
loadjson.m
.m
MachineLearning-master/Week2 - Linear Regression/ex1/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
bodlaranjithkumar/MachineLearning-master
loadubjson.m
.m
MachineLearning-master/Week2 - Linear Regression/ex1/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
bodlaranjithkumar/MachineLearning-master
saveubjson.m
.m
MachineLearning-master/Week2 - Linear Regression/ex1/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
atcemgil/VBYO-master
ex0.m
.m
VBYO-master/kodlar/YuksekBasarimliHesaplama/Matlab/ex0.m
307
utf_8
a46204430cb95f7303b507c1d434a901
function total = ex0() clear A; for i = 1:10 A(i) = i*1000000; end B = zeros(10,1); tic for i = 1:length(A) B(i) = f(A(i)); end total = sum(B); toc end function total = f(n) total = 0; for i = 1:n total = total + 1/i; end end
github
sania-irfan/Document-Layout-Analysis-MATLAB-master
DAP.m
.m
Document-Layout-Analysis-MATLAB-master/Document_layout-code/DAP.m
6,431
utf_8
539fb9c917f14560546d477433272782
function varargout = DAP(varargin) % DAP MATLAB code for DAP.fig % DAP, by itself, creates a new DAP or raises the existing % singleton*. % % H = DAP returns the handle to a new DAP or the handle to % the existing singleton*. % % DAP('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in DAP.M with the given input arguments. % % DAP('Property','Value',...) creates a new DAP or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before DAP_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to DAP_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help DAP % Last Modified by GUIDE v2.5 21-Jul-2016 21:30:28 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @DAP_OpeningFcn, ... 'gui_OutputFcn', @DAP_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before DAP is made visible. function DAP_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to DAP (see VARARGIN) % Choose default command line output for DAP handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes DAP wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = DAP_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.output = hObject; [fn pn] = uigetfile('*.jpg','select jpg file'); complete = strcat(pn,fn); set(handles.edit1,'string',complete); I = imread(complete); %axes(handles.axes1); imshow(I); guidata(hObject, handles); function edit1_Callback(hObject, eventdata, handles) % hObject handle to edit1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit1 as text % str2double(get(hObject,'String')) returns contents of edit1 as a double % --- Executes during object creation, after setting all properties. function edit1_CreateFcn(hObject, eventdata, handles) % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton2. function pushbutton2_Callback(hObject, eventdata, handles) R = get(handles.edit1, 'string') S=imread(R); H = fspecial('gaussian',100,2); gauss = imfilter(S,H,'replicate'); L=[-1 -1 -1; -1 8 -1; -1 -1 -1]; k= imfilter(gauss,L); final_img=k+gauss; imshow(final_img); imwrite(final_img,'C:\Users\sania\Downloads\Document-analysis-project\noiseremoved\NoiseRemoved.jpg'); % K = medfilt2(I); % --- Executes on button press in pushbutton3. function pushbutton3_Callback(hObject, eventdata, handles) R = get(handles.edit1, 'string') delete('C:\Users\sania\Downloads\Document-analysis-project\Output_Images\*.jpg'); img1=imread(R); [h w]=size(img1) %Ratio R=w/h; newh=h*R; img=imresize(img1,[newh 3075]); %Dilation Function [stats,Ibox,bwSub]=dilated(img); imshow(bwSub); for k=1:length(stats) c=imcrop(img,Ibox(:,k)); c=imresize(c,[480 640]); filename=sprintf('C:\\Users\\sania\\Downloads\\Document-analysis-project\\Output_Images\\%02d.jpg',k); imwrite(c,filename,'jpg'); rectangle('position',Ibox(:,k),'edgecolor','r'); end function pushbutton4_Callback(hObject, eventdata, handles) R = get(handles.edit1, 'string') delete('C:\Users\sania\Downloads\Document-analysis-project\Output_Images\*.jpg'); img1=imread(R); [h w]=size(img1); %Ratio R=w/h; newh=h*R; img=imresize(img1,[newh 3075]); %Dilation function [stats,Ibox,bwSub]=dilated(img); LabelImg=img; for k=1:length(stats) c=imcrop(LabelImg,Ibox(:,k)); c=imresize(c,[480 640]); filename=sprintf('C:\\Users\\sania\\Desktop\\Output_Images\\%02d.jpg',k); imwrite(c,filename,'jpg'); results=ocr(c); d=results.Text; thisBB = stats(k).BoundingBox ; if stats(k).BoundingBox(4) > 400 if d~=0 label = 'col'; else label='image'; end elseif stats(k).BoundingBox(4) < 400 label = 'head'; end LabelImg = insertObjectAnnotation(LabelImg,'rectangle',[thisBB(1),thisBB(2),thisBB(3),thisBB(4)]... ,label,'TextBoxOpacity',0.5,'FontSize',70); end imshow(LabelImg); % --- Executes on button press in slider. function slider_Callback(hObject, eventdata, handles) Dir=fullfile('C:\Users\sania\Downloads\Document-analysis-project\Output_Images'); paper = imageSet(Dir); for i=1:paper.Count imgCell{i} = read(paper,i); end img=cat(1,imgCell{:}); hFig = figure('Toolbar','none',... 'Menubar','none'); hIm = imshow(img); SP = imscrollpanel(hFig,hIm);