From c1fe6cc7bb58d02b96f251103ec93addf41f57c1 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 9 Aug 2018 22:37:00 +0200 Subject: [PATCH] 1.4.0 --- .gitignore | 3 + CHANGELOG.md | 19 + Core/Algos/@BreachProblem/BreachProblem.m | 28 +- Core/Algos/@BreachProblem/check_monotony.m | 24 + Core/Algos/@BreachProblem/setup_binsearch.m | 1 - Core/Algos/@BreachProblem/solve_binsearch.m | 1 + Core/Algos/FalsificationProblem.m | 31 +- Core/BreachRequirement.m | 149 ++-- Core/BreachSet.m | 59 +- Core/BreachSystem.m | 10 +- Core/BreachTraceSystem.m | 20 +- Core/ComputeTraj.m | 10 +- Core/CreateSystem.m | 2 +- Core/OutputGen/alw_monitor.m | 2 +- Core/OutputGen/get_monitors.m | 17 +- Core/OutputGen/req_monitor.m | 8 + Core/OutputGen/stl_monitor.m | 3 +- Core/SPropSensi.m | 3 - Core/m_src/isaSys.m | 2 +- Examples/+BrDemo/InitAFC.m | 1 - Examples/+BrDemo/InitAutotrans.m | 44 ++ .../Demo_move_CachingFolder_Path.m | 14 + .../Automatic_Transmission/init_autotrans.m | 2 +- .../tuto_BreachSimulinkSystem.m | 2 +- .../Automatic_Transmission/tuto_falsify.m | 6 +- .../tuto_falsify_w_disk_caching.m | 37 + Ext/Toolboxes/jsonlab/AUTHORS.txt | 56 ++ Ext/Toolboxes/jsonlab/ChangeLog.txt | 109 +++ Ext/Toolboxes/jsonlab/LICENSE_BSD.txt | 25 + Ext/Toolboxes/jsonlab/LICENSE_GPLv3.txt | 699 ++++++++++++++++++ Ext/Toolboxes/jsonlab/README.rst | 459 ++++++++++++ Ext/Toolboxes/jsonlab/README.txt | 431 +++++++++++ .../jsonlab/examples/demo_jsonlab_basic.m | 181 +++++ .../jsonlab/examples/demo_ubjson_basic.m | 180 +++++ Ext/Toolboxes/jsonlab/examples/example1.json | 21 + Ext/Toolboxes/jsonlab/examples/example2.json | 22 + Ext/Toolboxes/jsonlab/examples/example3.json | 11 + Ext/Toolboxes/jsonlab/examples/example4.json | 35 + .../jsonlab/examples/jsonlab_basictest.matlab | 671 +++++++++++++++++ .../jsonlab/examples/jsonlab_selftest.m | 27 + .../jsonlab/examples/jsonlab_selftest.matlab | 154 ++++ .../jsonlab/examples/jsonlab_speedtest.m | 21 + Ext/Toolboxes/jsonlab/jsonopt.m | 35 + Ext/Toolboxes/jsonlab/loadjson.m | 504 +++++++++++++ Ext/Toolboxes/jsonlab/loadubjson.m | 449 +++++++++++ Ext/Toolboxes/jsonlab/mergestruct.m | 33 + Ext/Toolboxes/jsonlab/package.json | 21 + Ext/Toolboxes/jsonlab/savejson.m | 593 +++++++++++++++ Ext/Toolboxes/jsonlab/saveubjson.m | 561 ++++++++++++++ Ext/Toolboxes/jsonlab/struct2jdata.m | 96 +++ .../jsonlab/varargin2struct_jsonlab.m | 40 + InitBreach.m | 1 + LICENSE | 1 + Params/Pfix_traj_ref.m | 2 +- Plots/BreachSamplesPlot.m | 288 ++++++-- Plots/BreachSignalsPlot.m | 19 +- VERSION | 2 +- 57 files changed, 6056 insertions(+), 189 deletions(-) create mode 100644 Core/Algos/@BreachProblem/check_monotony.m create mode 100644 Examples/+BrDemo/InitAutotrans.m create mode 100644 Examples/Simulink/Automatic_Transmission/Demo_move_CachingFolder_Path.m create mode 100644 Examples/Simulink/Automatic_Transmission/tuto_falsify_w_disk_caching.m create mode 100644 Ext/Toolboxes/jsonlab/AUTHORS.txt create mode 100644 Ext/Toolboxes/jsonlab/ChangeLog.txt create mode 100644 Ext/Toolboxes/jsonlab/LICENSE_BSD.txt create mode 100644 Ext/Toolboxes/jsonlab/LICENSE_GPLv3.txt create mode 100644 Ext/Toolboxes/jsonlab/README.rst create mode 100644 Ext/Toolboxes/jsonlab/README.txt create mode 100644 Ext/Toolboxes/jsonlab/examples/demo_jsonlab_basic.m create mode 100644 Ext/Toolboxes/jsonlab/examples/demo_ubjson_basic.m create mode 100644 Ext/Toolboxes/jsonlab/examples/example1.json create mode 100644 Ext/Toolboxes/jsonlab/examples/example2.json create mode 100644 Ext/Toolboxes/jsonlab/examples/example3.json create mode 100644 Ext/Toolboxes/jsonlab/examples/example4.json create mode 100644 Ext/Toolboxes/jsonlab/examples/jsonlab_basictest.matlab create mode 100644 Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.m create mode 100644 Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.matlab create mode 100644 Ext/Toolboxes/jsonlab/examples/jsonlab_speedtest.m create mode 100644 Ext/Toolboxes/jsonlab/jsonopt.m create mode 100644 Ext/Toolboxes/jsonlab/loadjson.m create mode 100644 Ext/Toolboxes/jsonlab/loadubjson.m create mode 100644 Ext/Toolboxes/jsonlab/mergestruct.m create mode 100644 Ext/Toolboxes/jsonlab/package.json create mode 100644 Ext/Toolboxes/jsonlab/savejson.m create mode 100644 Ext/Toolboxes/jsonlab/saveubjson.m create mode 100644 Ext/Toolboxes/jsonlab/struct2jdata.m create mode 100644 Ext/Toolboxes/jsonlab/varargin2struct_jsonlab.m diff --git a/.gitignore b/.gitignore index 4c426d2a..acf4a525 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,6 @@ wiki/ @STL_Formula/private/recomp.m Ext/ModelsData /Examples/docrun_backup.mat +*.mexa64 +/Ext/Toolboxes/jsonlab/examples/selftest.* +fileServerFolder diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b88246e..ec940a89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,22 @@ +# Release 1.4.0 + +## Users +- BreachSet.SetParam gets 'combine' option +- BreachSamplesPlot improvement +- Better support for req_monitors which are not stl_monitors +- Support for requirement parameters sampling at BreachRequirement level +- Updated Automatic transmission example + + +## Bugfixes +- Sim() recompute without argument now checks if traces are present before + recomputing with default time (was causing weird GetRobustSat behavior) +- log_format deactivated when using diskcaching wo parallel until figuring better solution + +## Developpers +- Added jsonlab toolbox + + # Release 1.3.3 - Fixed violation signals for alw (A => ev_[] B) types of requirements diff --git a/Core/Algos/@BreachProblem/BreachProblem.m b/Core/Algos/@BreachProblem/BreachProblem.m index f17e7221..1d9bc1f9 100644 --- a/Core/Algos/@BreachProblem/BreachProblem.m +++ b/Core/Algos/@BreachProblem/BreachProblem.m @@ -466,11 +466,7 @@ function ResetTimeSpent(this) function SaveInCache(this) if this.BrSys.UseDiskCaching FileSave = [this.BrSys.DiskCachingRoot filesep class(this) '_Runs.mat']; - if ~exist(FileSave, 'file') - evalin('base', ['save(''' FileSave ''',''' this.whoamI ''');']); - else - evalin('base', ['save(''' FileSave ''',''-append'',''', this.whoamI ''');']); - end + evalin('base', ['save(''' FileSave ''',''' this.whoamI ''');']); end end @@ -553,13 +549,14 @@ function SetupParallel(this, varargin) this.BrSys.SetupParallel(varargin{:}); % Enable DiskCaching - if this.log_traces - this.SetupDiskCaching(); - end - - % Possible need to change the optinmization optinion - this.setup_solver(); + this.SetupDiskCaching(); + % Possible need to change the optimization option + % this.setup_solver(); + % TODO: review when needed on solver-by-solver basis - maybe + % warning in order ? + + end function StopParallel(this) @@ -568,6 +565,7 @@ function StopParallel(this) end function SetupDiskCaching(this, varargin) + this.log_traces = 0; % FIXME this.BrSys.SetupDiskCaching(varargin{:}); end @@ -672,7 +670,7 @@ function LogX(this, x, fval) this.X_log = [this.X_log x]; this.obj_log = [this.obj_log fval]; - if (this.log_traces)&&~(this.use_parallel); + if (this.log_traces)&&~(this.use_parallel)&&~(this.BrSet.UseDiskCaching); % FIXME - logging flags and methods need be revised if isempty(this.BrSet_Logged) this.BrSet_Logged = this.BrSys.copy(); else @@ -744,8 +742,7 @@ function Display_Best_Results(this, best_fval, param_values) BrOut.ResetSimulations(); BrOut.SetParam(this.params, this.X_log); BrOut.Sim(); - end - + end [BrOut, Berr, BbadU] = this.ExportBrSet(BrOut); end @@ -763,7 +760,7 @@ function Display_Best_Results(this, best_fval, param_values) end function summary = SaveResults(this, varargin) - BLog = this.GetBrSet_Logged(); + BLog = this.GetLog(); summary = BLog.SaveResults(varargin{:}); end @@ -834,7 +831,6 @@ function display_status(this,fval, const_val) if ~isempty(idx_ok)&&B.hasTraj(); BrOut = this.Spec.copy(); BrOut.ResetSimulations(); - BrOut.BrSet = []; BrOut.Eval(B); end end diff --git a/Core/Algos/@BreachProblem/check_monotony.m b/Core/Algos/@BreachProblem/check_monotony.m new file mode 100644 index 00000000..3ae19f50 --- /dev/null +++ b/Core/Algos/@BreachProblem/check_monotony.m @@ -0,0 +1,24 @@ +function monotony = check_monotony(this) +% BreachProblem.check_monotony might evolve eventually into more general sensitivity +% analysis + +% check domains for non double - +for id= 1:numel(this.domains) + if ~isequal(this.domains(id).type, 'double') + warning('check_monotony not tested with non double type, such as type %s of variable %s', this.domains(id), this.params{id}); + end +end + +Sys= CreateSystem({},this.params, this.x0); +P = CreateParamSet(Sys, this.params, [this.lb, this.ub]); + +p = 4; +r = 10; +Pr = pRefine(P, p,r); +Y = this.objective(Pr.pts); +[~, ~, ~, ~, EE] = EEffects(Y, Pr.D, p); + +monotony = all(EE'>=0)-all(EE'<=0); % 1 if all positive, -1 if all negative, 0 otherwise + + + diff --git a/Core/Algos/@BreachProblem/setup_binsearch.m b/Core/Algos/@BreachProblem/setup_binsearch.m index a4a10537..a4d9d562 100644 --- a/Core/Algos/@BreachProblem/setup_binsearch.m +++ b/Core/Algos/@BreachProblem/setup_binsearch.m @@ -10,4 +10,3 @@ 'verbose', 1); this.solver_options = solver_opt; end - diff --git a/Core/Algos/@BreachProblem/solve_binsearch.m b/Core/Algos/@BreachProblem/solve_binsearch.m index 691a6e3d..dfb8464b 100644 --- a/Core/Algos/@BreachProblem/solve_binsearch.m +++ b/Core/Algos/@BreachProblem/solve_binsearch.m @@ -1,4 +1,5 @@ function res = solve_binsearch(this) +% solve_binsearch Sys = this.BrSys.Sys; phi = STL_Formula(this.Spec.req_monitors{1}.formula_id); diff --git a/Core/Algos/FalsificationProblem.m b/Core/Algos/FalsificationProblem.m index 61dcef84..132aefa5 100644 --- a/Core/Algos/FalsificationProblem.m +++ b/Core/Algos/FalsificationProblem.m @@ -21,12 +21,11 @@ end methods (Static) - function load_runs(folder, run) - if nargin==1 - evalin('base', ['load(''' folder filesep 'FalsificationProblem_Runs'');']); - elseif nargin==2 - evalin('base', ['load(''' folder filesep 'FalsificationProblem_Runs'',''' run ''');']); - end + function falsif_pb = load_runs(logFilePath) + st = load([logFilePath, filesep, 'FalsificationProblem_Runs']); + fn= fieldnames(st); + falsif_pb = st.(fn{1}); + falsif_pb.SetupDiskCaching('DiskCachingRoot', logFilePath); end end @@ -98,6 +97,14 @@ function ResetObjective(this) Xfalse = this.X_false; end + function SaveInCache(this) + if this.BrSys.UseDiskCaching + FileSave = [this.BrSys.DiskCachingRoot filesep 'FalsificationProblem_Runs.mat']; + evalin('base', ['save(''' FileSave ''',''' this.whoamI ''');']); + end + end + + % Logging function LogX(this, x, fval) % LogX log variable parameter value tested by optimizers @@ -112,7 +119,7 @@ function LogX(this, x, fval) this.obj_false = [this.obj_false fval]; if (this.log_traces)&&~this.use_parallel if isempty(this.BrSet_False) - this.BrSet_False = this.BrSys.copy(); + this.BrSet_False = this.Spec.BrSet.copy(); else this.BrSet_False.Concat(this.BrSys); end @@ -125,8 +132,8 @@ function LogX(this, x, fval) b= b||(this.StopAtFalse&&this.obj_best<0); end - function [BrFalse, BrFalse_Err, BrFalse_badU] = GetBrSet_False(this) - BrFalse = this.BrSet_False; + function [BrFalse, BrFalse_Err, BrFalse_badU] = GetFalse(this) + BrFalse = this.BrSet_False; if isempty(BrFalse) [~, i_false] = find(this.obj_log<0); if ~isempty(i_false) @@ -137,6 +144,12 @@ function LogX(this, x, fval) end [BrFalse, BrFalse_Err, BrFalse_badU] = this.ExportBrSet(BrFalse); + + end + + function [BrFalse, BrFalse_Err, BrFalse_badU] = GetBrSet_False(this) + % Use GetFalse. Keeping this for backward compatibility. + [BrFalse, BrFalse_Err, BrFalse_badU] = this.GetFalse(); end function DispResultMsg(this) diff --git a/Core/BreachRequirement.m b/Core/BreachRequirement.m index 386967e0..faea1cf2 100644 --- a/Core/BreachRequirement.m +++ b/Core/BreachRequirement.m @@ -22,7 +22,7 @@ function this = BreachRequirement(req_monitors, postprocess_signal_gens, precond_monitors) - this = this@BreachTraceSystem({}); + this = this@BreachTraceSystem({}, [], {'data_trace_idx_'}); % Adds requirement monitors, at least one this.req_monitors = {}; @@ -44,8 +44,7 @@ this.ResetSigMap(); end - - + function AddReq(this, req_monitors) [~, monitors] = get_monitors(req_monitors); @@ -141,6 +140,15 @@ function ResetSigMap(this) this.eval_precond_only = false; end + function ResetSimulations(this) + ResetSimulations@BreachSet(this); + this.traces_vals =[]; + this.val = []; + this.traces_vals_precond= []; + this.BrSet =[]; + + end + function [global_val, traces_vals, traces_vals_precond] = Eval(this, varargin) % BreachRequirement.Eval returns evaluation of the requirement - % compute it for all traces available and returns min (implicit @@ -160,13 +168,23 @@ function ResetSigMap(this) if nargin<2 idx_req_monitors = 1; end + req_mon = this.req_monitors(idx_req_monitors); if nargin<3 itraj=1; end F = BreachSignalsPlot(this, {}, itraj); % empty for ifo =1:numel(idx_req_monitors) - this.req_monitors{idx_req_monitors(ifo)}.plot_diagnosis(F); - title(this.req_monitors{idx_req_monitors(ifo)}.formula_id, 'Interpreter', 'None') + if isa(req_mon{ifo},'stl_monitor') + req_mon{ifo}.plot_diagnosis(F); + title(req_mon{ifo}.formula_id, 'Interpreter', 'None') + else + if ~isempty(req_mon{ifo}.signals_in) + F.AddSignals(req_mon{ifo}.signals_in) + end + if ~isempty(req_mon{ifo}.signals) + F.AddSignals(req_mon{ifo}.signals) + end + end end end @@ -190,9 +208,12 @@ function ResetSigMap(this) summary.num_traces_evaluated =size(this.traces_vals,1); summary.requirements.names = cell(1,numel(this.req_monitors)); for ir = 1:numel(this.req_monitors) - summary.requirements.names{ir} = this.req_monitors{ir}.formula_id; + if isa(this.req_monitors{ir}, 'stl_monitor') + summary.requirements.names{ir} = this.req_monitors{ir}.formula_id; + else + summary.requirements.names{ir} = class(this.req_monitors{ir}); + end end - if summary.num_traces_evaluated>0 summary.val = this.val; summary.requirements.rob = this.traces_vals; @@ -217,8 +238,7 @@ function ResetSigMap(this) summary.statement = [summary.statement '.']; end end - - + function values = GetParam(this, params, ip) % GetParam if not found, look into BrSet [idx, ifound] = FindParam(this.P, params); @@ -237,8 +257,13 @@ function ResetSigMap(this) idx_data = ifound==0; params_req = params(idx_req); params_data = params(idx_data); - values(idx_req,:) = this.GetParam(params_req, ip); - values(idx_data,:) = this.BrSet.GetParam(params_data, ip); + if ~isempty(params_req) + values(idx_req,:) = this.GetParam(params_req, ip); + end + for it = 1:numel(ip) + ipts = find(this.BrSet.P.traj_ref==ip(it),1); + values(idx_data,it) = this.BrSet.GetParam(params_data, ipts); + end end end @@ -288,7 +313,7 @@ function ResetSigMap(this) signals = {signals}; end [idxR, ifound, idxB, ifoundB] = this.FindSignalsIdx(signals); % finds signal indexes in this or this.BrSet, - % supports bidirectional aliases ... + % supports bidirectional aliases ... if all(ifound) X = GetSignalValues@BreachTraceSystem(this,idxR, varargin{2:end}); else @@ -303,6 +328,14 @@ function ResetSigMap(this) end if any(ifoundB) idxB = idxB(ifoundB==1); + if nargin>1 && isfield(this.BrSet.P, 'traj_ref') + iptsB = varargin{2}; + for it= 1:numel(iptsB) + itracesB(it) = this.BrSet.P.traj_ref(iptsB(it)); + end + varargin{2} = itracesB; + end + values_data = this.BrSet.GetSignalValues(idxB, varargin{2:end}); if iscell(values_data) nb_traj =numel(values_data); @@ -356,8 +389,6 @@ function PlotRobustSat(this, varargin) this.BrSet.PlotRobustSat(varargin{:}); end - - %% Display function st = disp(this) signals_in_st = cell2mat(cellfun(@(c) (['''' c ''', ']), this.signals_in, 'UniformOutput', false)); @@ -373,7 +404,7 @@ function PlotRobustSat(this, varargin) function PrintFormula(this) if ~isempty(this.precond_monitors) - fprintf(['--- PRECONDITIONS FORMULAS ---\n']); + fprintf(['--- PRECONDITIONS ---\n']); for ifo = 1:numel(this.precond_monitors) this.precond_monitors{ifo}.disp(); end @@ -768,7 +799,7 @@ function getBrSet(this, varargin) end if ~isempty(params_sys) - B.SetParam(params_sys,values(i_sys,:)); + B.SetParam(params_sys,values(i_sys,:),true); end if ~isempty(params_req) @@ -780,8 +811,24 @@ function getBrSet(this, varargin) if isa(B,'struct') % reading one struct obtained from a SaveResult command B = BreachTraceSystem(B); end % here we need to handle pre-conditions, input requirements, etc - + this.BrSet = B; + paramB = this.BrSet.GetParamList(); + idxR_paramR = this.P.DimX+2:this.P.DimP; + paramR = this.P.ParamList(idxR_paramR); + paramR_in_B = intersect(paramB, paramR); + idxB_paramR_in_B = FindParam(B.P, paramR_in_B); + idxR_paramR_in_B = FindParam(this.P, paramR_in_B); + paramR_wo_B = setdiff( paramR, paramB); % parameters in R that are not in B - need to be combined + + % if this has more than one value, needs to combine them with + % those of B + multiple_paramR_vals = size(this.P.pts,2)>1; + if multiple_paramR_vals + values_req_wo_sys = this.GetParam(paramR_wo_B); + B.SetParam(paramR_wo_B, values_req_wo_sys, 'combine'); % now B contains all params for requirement + idxB_paramR = FindParam(B.P, paramR); + end if this.eval_precond_only % find what needs to be computed sigs_need = {}; @@ -830,51 +877,53 @@ function getBrSet(this, varargin) this.BrSet = B; % initialize or reset traces - num_traj = numel(B.P.traj); - - param_sys = intersect(this.BrSet.GetParamList(), this.P.ParamList(this.P.DimX+1:end)); - idx_param_sys_B = FindParam(this.BrSet.P, param_sys); - idx_param_sys_R = FindParam(this.P, param_sys); + num_pts = size(B.P.pts,2); % Eval reset and recompute - not so much as Sim() if this.hasTraj() this.ResetParamSet(); end - for it =1:num_traj + this.P = Sselect(this.P,1); + + if isfield(this.BrSet.P,'traj_ref') + itrajs = B.P.traj_ref; + else + itrajs = 1:num_pts; + end + + for it =1:num_pts trajR = struct(); - trajR.param = this.P.pts(:,1)'; - paramB= B.P.traj{it}.param; - if ~isempty(idx_param_sys_R) - if idx_param_sys_B <= B.P.DimP - trajR.param(1,idx_param_sys_R) = paramB(1, idx_param_sys_B); - else - trajR.param(1,idx_param_sys_R) = B.P.pts(idx_param_sys_B,it)'; % Spec parameter for B, have to look into pts, risky wrt traj_ref - end + trajR.param = zeros(1,this.Sys.DimX); + trajR.param(this.Sys.DimX+1) = itrajs(it); + if ~multiple_paramR_vals % parameters of R were combined previously, + trajR.param = [trajR.param this.P.pts(idxR_paramR,1)']; % simple case: only one pts in R otherwise... + trajR.param(1,idxR_paramR_in_B) = B.P.pts(idxB_paramR_in_B,it)'; + else + trajR.param = [trajR.param B.P.pts(idxB_paramR,it)']; end - - trajR.time = B.P.traj{it}.time; + trajR.time = B.P.traj{itrajs(it)}.time; trajR.X = NaN(this.Sys.DimX, numel(trajR.time)); this.AddTrace(trajR); end end - function [traces_vals, traces_vals_precond] =evalAllTraces(this,varargin) + function [traces_vals, traces_vals_precond] =evalAllTraces(this,varargin) % BreachRequirement.evalAllTraces collect traces and apply % evalTrace this.getBrSet(varargin{:}); - - num_traj = numel(this.BrSet.P.traj); + num_traj = numel(this.P.traj); traces_vals = nan(num_traj, numel(this.req_monitors)); traces_vals_precond = nan(num_traj, numel(this.precond_monitors)); + % eval pre conditions if ~isempty(this.precond_monitors) for it = 1:num_traj - time = this.P.traj{it}.time; - for ipre = 1:numel(this.precond_monitors) - req = this.precond_monitors{ipre}; - traces_vals_precond(it, ipre) = eval_req(); - end + time = this.P.traj{it}.time; + for ipre = 1:numel(this.precond_monitors) + req = this.precond_monitors{ipre}; + traces_vals_precond(it, ipre) = eval_req(); + end end end @@ -920,8 +969,7 @@ function getBrSet(this, varargin) if ~isempty(idx_sig_req) [val , this.P.traj{it}.time, Xout] ... = this.evalRequirement(req, time, Xin, p_in); - this.P.traj{it}.X( idx_sig_req,:) = Xout; - + this.P.traj{it}.X( idx_sig_req,:) = Xout; else val = this.evalRequirement(req, time, Xin, p_in); end @@ -980,9 +1028,11 @@ function setTraces(this, trajs_req) function b = is_a_requirement(this, sig) b = false; for ifo = 1:numel(this.req_monitors) - if strcmp(sig, [this.req_monitors{ifo}.formula_id '_quant_sat' ])||... - strcmp(sig, [get_id(this.req_monitors{ifo}.formula) ]) - b = true; + if isa(this.req_monitors{ifo}, 'stl_monitor') + if strcmp(sig, [this.req_monitors{ifo}.formula_id '_quant_sat' ])||... + strcmp(sig, [get_id(this.req_monitors{ifo}.formula) ]) + b = true; + end end end end @@ -990,8 +1040,11 @@ function setTraces(this, trajs_req) function b = is_a_violation_signal(this, sig) b = false; for ifo = 1:numel(this.req_monitors) - if strcmp(sig, [this.req_monitors{ifo}.formula_id '_violation' ]) - b = true; + if isa(this.req_monitors{ifo}, 'stl_monitor') + + if strcmp(sig, [this.req_monitors{ifo}.formula_id '_violation' ]) + b = true; + end end end end diff --git a/Core/BreachSet.m b/Core/BreachSet.m index 51af68d1..5099fb4b 100644 --- a/Core/BreachSet.m +++ b/Core/BreachSet.m @@ -230,6 +230,10 @@ function SetParam(this, params, values, is_spec_param) % several samples and there is only one value, set this value to % all samples. Otherwise, returns an error. + if (~exist('is_spec_param', 'var')) + is_spec_param = false; + end + ip = FindParam(this.P, params); i_not_sys = find(ip>this.P.DimP); if ~isempty(i_not_sys) @@ -238,7 +242,7 @@ function SetParam(this, params, values, is_spec_param) else nparam = params; end - if ~exist('is_spec_param','var')||isequal(is_spec_param,false) + if isequal(is_spec_param,false) warning('SetParam:param_not_in_list',['Parameter ' nparam ' was set but is not a system parameter.' ... ' If this is intended to be a spec. parameter, consider using SetParamSpec instead.']); end @@ -259,18 +263,39 @@ function SetParam(this, params, values, is_spec_param) num_pts = size(this.P.pts,2); num_values = size(values, 2); + saved_traj = false; - if num_values==1 || num_values == num_pts - this.P = SetParam(this.P, params, values); - elseif num_pts==1 % note in this case, we have to remove traces ( or see if maybe not, ) + if ischar(is_spec_param)&&strcmp(is_spec_param, 'combine') + if this.hasTraj() + P0 = this.P; + saved_traj = true; + end + idx = N2Nn(2, [num_pts num_values]); + old_pts = this.P.pts; this.P = Sselect(SPurge(this.P),1); - this.P.pts = repmat(this.P.pts,1, size(values, 2)); - this.P.epsi= repmat(this.P.epsi,1, size(values, 2)); - this.P.selected = zeros(1, size(values, 2)); - this.P = SetParam(this.P, ip, values); - else - error('SetParam:wrong_arguments_size', 'Dimension mismatch between values and parameters.'); + this.P.pts = old_pts(:, idx(1,:)); + this.P.epsi= repmat(this.P.epsi,1, size(idx, 2)); + this.P.selected = zeros(1, size(idx, 2)); + this.P = SetParam(this.P, params, values(:, idx(2,:))); + else % legacy, i.e., not combine version + if num_values==1 || num_values == num_pts + this.P = SetParam(this.P, params, values); + elseif num_pts==1 % note in this case, we have to remove traces ( or see if maybe not, ) + this.P = Sselect(SPurge(this.P),1); + this.P.pts = repmat(this.P.pts,1, size(values, 2)); + this.P.epsi= repmat(this.P.epsi,1, size(values, 2)); + this.P.selected = zeros(1, size(values, 2)); + this.P = SetParam(this.P, params, values); + else + error('SetParam:wrong_arguments_size', 'Dimension mismatch between values and parameters.'); + end + end + + % restore traj if needed + if saved_traj + this.P = Pfix_traj_ref(this.P, P0); end + end function SetParamSpec(this, params, values, ignore_sys_param) @@ -510,9 +535,10 @@ function PrintSigMap(this) traj_status = zeros(1, nb_pts); for it = 1:nb_pts - traj_status(it) = this.P.traj{this.P.traj_ref(it)}.status; + if this.P.traj_ref(it) + traj_status(it) = this.P.traj{this.P.traj_ref(it)}.status; + end end - idx_ok = find(traj_status == 0); idx_sim_error = find(traj_status == -1); idx_invalid_input = find(traj_status == -2); @@ -1557,7 +1583,7 @@ function SortbySat(this) if isfield(this.P,'props_names') spec_names = this.P.props_names; end - + summary.signature= this.GetSignature(); summary.date = datestr(now); summary.num_traces = num_traces; summary.params.names = param_names; @@ -1576,10 +1602,13 @@ function SortbySat(this) function b = is_variable(this, par) b = false ; - [~, f] = FindParam(this.P, par); + [i, f] = FindParam(this.P, par); if f - dom = this.GetDomain(par); + dom = this.Domains(i); b = ~isempty(dom.domain); + if ~b + b = any(diff(this.P.pts(i,:))); + end end end diff --git a/Core/BreachSystem.m b/Core/BreachSystem.m index 7aa2f3e4..0b48fe7c 100644 --- a/Core/BreachSystem.m +++ b/Core/BreachSystem.m @@ -200,7 +200,11 @@ function Sim(this,tspan) evalin('base', this.InitFn); this.CheckinDomainParam(); if nargin==1 - tspan = this.Sys.tspan; + if this.hasTraj() + tspan = [0 this.P.traj{1}.time(end)]; + else + tspan = this.Sys.tspan; + end end this.P = ComputeTraj(this.Sys, this.P, tspan); this.CheckinDomainTraj(); @@ -353,11 +357,15 @@ function SetSpec(this,varargin) % FIXME: this is going to break with multiple trajectories with % some of them containing NaN - + if any(isnan(this.P.traj{1}.X)) tau = t_phi; rob = t_phi; rob(:) = NaN; else + if ischar(phi) + phi = STL_Formula('phi__tmp__', phi); + end [rob, tau] = STL_Eval(this.Sys, phi, this.P, this.P.traj,t_phi); end diff --git a/Core/BreachTraceSystem.m b/Core/BreachTraceSystem.m index 5f553aad..e6580f22 100644 --- a/Core/BreachTraceSystem.m +++ b/Core/BreachTraceSystem.m @@ -4,7 +4,7 @@ methods % constructor - takes signal names and an optional trace - function this = BreachTraceSystem(signals, trace) + function this = BreachTraceSystem(signals, trace, params) InitBreach; if (nargin==0) return; @@ -66,18 +66,23 @@ end % assumes now that we have signal names - this.Sys = CreateExternSystem('TraceObject', signal_names, {'trace_id'},1); + if exist('params', 'var')&&~isempty(params) + this.Sys = CreateSystem(signal_names, params,zeros(numel(signal_names)+numel(params),1)); + else + this.Sys = CreateSystem(signal_names, {},zeros(numel(signal_names),1)); + end + this.P = CreateParamSet(this.Sys); - if exist('trace1', 'var') + if exist('trace1', 'var')&&~isempty(trace1) this.AddTrace(trace1); end - if exist('trace', 'var') + if exist('trace', 'var')&&~isempty(trace) this.AddTrace(trace); end % Default domains - for ip = this.P.DimP + for ip = 1:this.P.DimP this.Domains(ip) = BreachDomain(); end @@ -140,7 +145,6 @@ function AddTrace(this, trace) traj.X(isig,:) = trace.signals.values(idx_sig,:); end end - end elseif isnumeric(trace) traj.X = trace(:, 2:end)'; @@ -163,7 +167,6 @@ function AddTrace(this, trace) traj.param = [this.Sys.p']; end - traj.param(this.Sys.DimX+1) = nb_traces+1; Pnew.traj={traj}; Pnew.traj_ref = 1; Pnew.traj_to_compute = []; @@ -173,9 +176,6 @@ function AddTrace(this, trace) else this.P = SConcat(this.P, Pnew); end - this.P.traj_ref = 1:nb_traces+1; - this.P.traj_to_compute = []; - this.P.pts(this.P.DimX+1,:) = 1:nb_traces+1; % index traces this.Sys.tspan = traj.time; if isfield(this.P, 'Xf') diff --git a/Core/ComputeTraj.m b/Core/ComputeTraj.m index d0a6db27..f9cd542b 100644 --- a/Core/ComputeTraj.m +++ b/Core/ComputeTraj.m @@ -351,9 +351,9 @@ [traj.time, traj.X,traj.status] = Sys.sim(Sys, tspan, P0.pts(:,ii)); traj.param = P0.pts(1:P0.DimP,ii)'; - % compute outputs - should we do something when status is not right? - if isfield(Sys, 'output_gens') - Xout = []; + % compute outputs - should we do something when status is not right? + if isfield(Sys, 'output_gens') + Xout = []; for io = 1:numel(Sys.output_gens) og = Sys.output_gens{io}; % Find in_signals @@ -361,7 +361,7 @@ ip = FindParam(P0, og.params); X_in = [traj.X(is, :); Xout] ; pts_in = P0.pts(ip,ii); - [traj.time, Xout_i] = og.computeSignals(traj.time, X_in, pts_in); + [traj.time, Xout_i] = og.computeSignals(traj.time, X_in, pts_in); Xout = [Xout ; Xout_i]; end traj.X(end-size(Xout,1)+1:end, :) = Xout; @@ -369,7 +369,7 @@ if use_caching % cache new trace traj.Properties.Writable = false; - end + end end end diff --git a/Core/CreateSystem.m b/Core/CreateSystem.m index 5bf97c65..a5737136 100644 --- a/Core/CreateSystem.m +++ b/Core/CreateSystem.m @@ -11,7 +11,7 @@ % % used in temporal logic formulas % % p0 = [ 0 0 ... % default for initial values of signals -% 0 0 0 ]; % default for parameters p0,p1 and p2 +% 0 0 0 ]'; % default for parameters p0,p1 and p2 % % Sys = CreateSystem(vars,params, p0); % creates the Sys structure % diff --git a/Core/OutputGen/alw_monitor.m b/Core/OutputGen/alw_monitor.m index 6267229c..a03f515f 100644 --- a/Core/OutputGen/alw_monitor.m +++ b/Core/OutputGen/alw_monitor.m @@ -18,7 +18,7 @@ end function [v, t, Xout] = eval(this, t, X,p) - [~, Xout] = this.computeSignals(t, X,p); + [t, Xout] = this.computeSignals(t, X,p); idx = this.get_time_idx_interval(t,p); Xout(end-1,:) = Xout(end,:)<0; % violation flags Xout(end-1:end, ~idx) = NaN; diff --git a/Core/OutputGen/get_monitors.m b/Core/OutputGen/get_monitors.m index 542068f3..dd1accdf 100644 --- a/Core/OutputGen/get_monitors.m +++ b/Core/OutputGen/get_monitors.m @@ -7,13 +7,16 @@ formulas = {formulas}; end - for itfo = 1:numel(formulas) formula = formulas{itfo}; if ischar(formula) formula = STL_Formula(STL_NewID('req'), formula); end - monitor = stl_monitor(formula); + if isa(formula, 'req_monitor') + monitor = formula; + else + monitor = stl_monitor(formula); + end % if isa(formula, 'STL_Formula') % % checks whether we have parameter constraint % ONHOLD @@ -25,11 +28,13 @@ % end % elseif isa(formula, 'stl_monitor') % monitor = formula; - % end - % if ~isa(monitor, 'param_constraint_monitor') - find_template(); +% end +% if ~isa(monitor, 'param_constraint_monitor') + if isa(monitor,'stl_monitor') + find_template(); + end signals = union(signals, monitor.signals, 'stable'); -% end +% end monitors = [monitors {monitor}]; end diff --git a/Core/OutputGen/req_monitor.m b/Core/OutputGen/req_monitor.m index fde1cc08..380bddd7 100644 --- a/Core/OutputGen/req_monitor.m +++ b/Core/OutputGen/req_monitor.m @@ -1,5 +1,13 @@ classdef req_monitor < output_gen + properties + name + end + methods + function [t, Xout] = computeSignals(t, Xin, pin) + Xout=[]; + end + end methods (Abstract) eval(this, t, X,p) end diff --git a/Core/OutputGen/stl_monitor.m b/Core/OutputGen/stl_monitor.m index f13e04e7..30a8dcc1 100644 --- a/Core/OutputGen/stl_monitor.m +++ b/Core/OutputGen/stl_monitor.m @@ -20,6 +20,7 @@ 'stl_monitor constructor requires a string or STL_Formula as argument.') end this.formula_id = get_id(this.formula); + this.name = get_id(this.formula); % collect signals and params names [this.signals_in, this.params, this.p0] = STL_ExtractSignals(this.formula); @@ -65,7 +66,7 @@ function plot_diagnosis(this, F) % Assumes F has data about this formula - F.BrSet.PlotRobustSat(this.formula,[],[],F.itraj); + F.BrSet.PlotRobustSat(this.formula,[],[],F.ipts); % if ~isempty(this.predicates) % F.AddAxes(); diff --git a/Core/SPropSensi.m b/Core/SPropSensi.m index 74a39b2c..21f349c2 100644 --- a/Core/SPropSensi.m +++ b/Core/SPropSensi.m @@ -109,11 +109,8 @@ Pr = Pcopy_traj(Pr,P); end -%NM : it is better to compute the truth value of phi at time=tprop if tau < tspan(1) tspan = [tau,tspan]; -%elseif tprop > tspan(end) % don't compute it in case it is too far from -% tspan = [tspan, tprop]; % the last time instant computed end Pr = ComputeTraj(Sys, Pr, tspan); diff --git a/Core/m_src/isaSys.m b/Core/m_src/isaSys.m index a5800f0f..e3d3cb8f 100644 --- a/Core/m_src/isaSys.m +++ b/Core/m_src/isaSys.m @@ -1,4 +1,4 @@ function b = isaSys(S) % isaSys Returns true if the argument is a classic Breach Sys structureb -b = isstruct(S)&&all(isfield(S,{'DimX','DimP','ParamList','p','Dir'})); +b = isstruct(S)&&all(isfield(S,{'DimX','DimP','ParamList','p','type','x0'})); diff --git a/Examples/+BrDemo/InitAFC.m b/Examples/+BrDemo/InitAFC.m index 8293a4fa..de306907 100644 --- a/Examples/+BrDemo/InitAFC.m +++ b/Examples/+BrDemo/InitAFC.m @@ -8,7 +8,6 @@ BrAFC = BreachSimulinkSystem(mdl, 'all', [], {}, [], 'Verbose',0,'SimInModelsDataFolder', true); - pedal_angle_gen = pulse_signal_gen({'Pedal_Angle'}); % Generate a pulse signal for pedal angle engine_gen = fixed_cp_signal_gen({'Engine_Speed'}, ... % signal name 3,... % number of control points diff --git a/Examples/+BrDemo/InitAutotrans.m b/Examples/+BrDemo/InitAutotrans.m new file mode 100644 index 00000000..0216a2a4 --- /dev/null +++ b/Examples/+BrDemo/InitAutotrans.m @@ -0,0 +1,44 @@ +% Init Model with two inputs + +mdl = 'Autotrans_shift'; +BrAutotrans_nominal = BreachSimulinkSystem(mdl, 'all', [], {}, [], 'Verbose',0,'SimInModelsDataFolder', true); + +BrAutotrans_nominal.SetTime(0:.01:40); % default simulation time +BrAutotrans_nominal.SetInputGen('VarStep2') + +%% Set input values (other than 0) +% Accelerate for 20 s at 100% +BrAutotrans_nominal.SetParam( 'throttle_dt0', 20); +BrAutotrans_nominal.SetParam( 'throttle_u0', 100); +BrAutotrans_nominal.SetParam( 'brake_u0', 0); +BrAutotrans_nominal.SetParam( 'brake_dt0', 20); + +% Brake ever after +BrAutotrans_nominal.SetParam( 'throttle_u1', 0); +BrAutotrans_nominal.SetParam( 'brake_u1', 325); + +%% 3 Ranges +BrAutotrans_3ranges = BrAutotrans_nominal.copy(); + +% Acceleration +BrAutotrans_3ranges.SetParamRanges( 'throttle_u0', [0 100]); +BrAutotrans_3ranges.SetParam( 'throttle_dt0', 20); +BrAutotrans_3ranges.SetParamRanges( 'throttle_u1', [0 100]); + +% Braking +BrAutotrans_3ranges.SetParam('brake_u0', 0); +BrAutotrans_3ranges.SetParam('brake_dt0', 20); +BrAutotrans_3ranges.SetParamRanges( 'brake_u1', [0 325]); + +%% 6 ranges +BrAutotrans_6ranges = BrAutotrans_nominal.copy(); + +% Acceleration +BrAutotrans_6ranges.SetParamRanges( 'throttle_u0', [0 100]); +BrAutotrans_6ranges.SetParamRanges( 'throttle_dt0', [0 40]); +BrAutotrans_6ranges.SetParamRanges( 'throttle_u1', [0 100]); + +% Braking +BrAutotrans_6ranges.SetParamRanges( 'brake_u0', [0 325]); +BrAutotrans_6ranges.SetParamRanges( 'brake_dt0', [0 40]); +BrAutotrans_6ranges.SetParamRanges( 'brake_u1', [0 325]); diff --git a/Examples/Simulink/Automatic_Transmission/Demo_move_CachingFolder_Path.m b/Examples/Simulink/Automatic_Transmission/Demo_move_CachingFolder_Path.m new file mode 100644 index 00000000..e0811ef1 --- /dev/null +++ b/Examples/Simulink/Automatic_Transmission/Demo_move_CachingFolder_Path.m @@ -0,0 +1,14 @@ +%% 1. Creating log "allLogFalsify" +display('******** Start tuto_falsify_w_disk_caching.m ********') +tuto_falsify_w_disk_caching; + +%% 2. Use-case is storing log on different file server +display('******** Rename CachingFolder Name ********') +movefile('allLogFalsify','fileServerFolder/allLogFalsify') +clear; + +%% 3. Use stored folder again +display('******** Recreate Blog ********') +falsif_pb = FalsificationProblem.load_runs('fileServerFolder/allLogFalsify'); +Blog = falsif_pb.GetLog(); +BreachSamplesPlot(Blog); \ No newline at end of file diff --git a/Examples/Simulink/Automatic_Transmission/init_autotrans.m b/Examples/Simulink/Automatic_Transmission/init_autotrans.m index 8524d3cd..40d541a6 100644 --- a/Examples/Simulink/Automatic_Transmission/init_autotrans.m +++ b/Examples/Simulink/Automatic_Transmission/init_autotrans.m @@ -15,7 +15,7 @@ Br.SetParam( 'brake_u0', 0); % Brake for 20s after -Br.SetParam( 'throttle_u1', 0); +Br.SetParam( 'throttle_u1', 0); Br.SetParam( 'brake_dt0', 20); Br.SetParam( 'brake_u0', 0); Br.SetParam( 'brake_u1', 325); diff --git a/Examples/Simulink/Automatic_Transmission/tuto_BreachSimulinkSystem.m b/Examples/Simulink/Automatic_Transmission/tuto_BreachSimulinkSystem.m index 2abf6afc..aeca03ed 100644 --- a/Examples/Simulink/Automatic_Transmission/tuto_BreachSimulinkSystem.m +++ b/Examples/Simulink/Automatic_Transmission/tuto_BreachSimulinkSystem.m @@ -30,7 +30,7 @@ %% % Change some values -BrSys.SetParam({'throttle_u0','dt_u0'}, [10 10]); +BrSys.SetParam({'throttle_u0','throttle_dt0'}, [10 10]); BrSys.Sim(); BrSys.PlotSignals; diff --git a/Examples/Simulink/Automatic_Transmission/tuto_falsify.m b/Examples/Simulink/Automatic_Transmission/tuto_falsify.m index 895859b3..f7dea9ce 100644 --- a/Examples/Simulink/Automatic_Transmission/tuto_falsify.m +++ b/Examples/Simulink/Automatic_Transmission/tuto_falsify.m @@ -18,6 +18,6 @@ % solves using the default solver falsif_pb.solve(); -% collect the falsifying trace -BrFalse = falsif_pb.GetBrSet_False() -BrFalse.PlotRobustSat(phi1) \ No newline at end of file +% collect the logged samples and traces +Blog = falsif_pb.GetLog(); +F = BreachSamplesPlot(Blog) diff --git a/Examples/Simulink/Automatic_Transmission/tuto_falsify_w_disk_caching.m b/Examples/Simulink/Automatic_Transmission/tuto_falsify_w_disk_caching.m new file mode 100644 index 00000000..42251a9f --- /dev/null +++ b/Examples/Simulink/Automatic_Transmission/tuto_falsify_w_disk_caching.m @@ -0,0 +1,37 @@ +%% init Breach +InitBreach; + +%% Model setting +mdl = 'Autotrans_shift'; +Br = BreachSimulinkSystem(mdl); +Br.SetTime(0:.01:50); %time setep setting + +%% Set log +Br.SetupDiskCaching('DiskCachingRoot', [pwd filesep 'allLogFalsify']); + +%% define the formula +phi = STL_Formula('phi', '(alw (speed[t] and + + +The script loadjson.m was built upon previous works by + +- Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 + date: 2009/11/02 +- François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 + date: 2009/03/22 +- Joel Feenstra: http://www.mathworks.com/matlabcentral/fileexchange/20565 + date: 2008/07/03 + + +This toolbox contains patches submitted by the following contributors: + +- Blake Johnson + part of revision 341 + +- Niclas Borlin + various fixes in revision 394, including + - loadjson crashes for all-zero sparse matrix. + - loadjson crashes for empty sparse matrix. + - Non-zero size of 0-by-N and N-by-0 empty matrices is lost after savejson/loadjson. + - loadjson crashes for sparse real column vector. + - loadjson crashes for sparse complex column vector. + - Data is corrupted by savejson for sparse real row vector. + - savejson crashes for sparse complex row vector. + +- Yul Kang + patches for svn revision 415. + - savejson saves an empty cell array as [] instead of null + - loadjson differentiates an empty struct from an empty array + +- Mykhailo Bratukha + (Pull#14) Bug fix: File path is wrongly inerpreted as JSON string + +- Insik Kim + (Pull#12) Bug fix: Resolving bug that cell type is converted to json with transposed data + +- Sertan Senturk + (Pull#10,#11) Feature: Added matlab object saving to savejson and saveubjson + +- Paul Koprowski + (Issue#29) Feature: Added support to save MATLAB tables to json. \ No newline at end of file diff --git a/Ext/Toolboxes/jsonlab/ChangeLog.txt b/Ext/Toolboxes/jsonlab/ChangeLog.txt new file mode 100644 index 00000000..cefb0fa3 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/ChangeLog.txt @@ -0,0 +1,109 @@ +== Decyphir changes decyphir.com> == +2018/08/06 renamed varargin2struct.m into varargin2struct_jsonlab.m to prevent conflict with Breach varargin2struct + +============================================================================ + + JSONlab - a toolbox to encode/decode JSON/UBJSON files in MATLAB/Octave + +---------------------------------------------------------------------------- + +JSONlab ChangeLog (key features marked by *): + +== JSONlab 1.5 (codename: Nominus - alpha), FangQ neu.edu> == + + 2017/01/02 *use Big-endian format to store floating points (d/D) in saveubjson (Issue #25) + 2017/01/02 *speedup parsing large unstructured data by 2x (Issue #9) + 2017/01/01 make parsing independent of white space (Issue #30) + 2016/08/27 allow to parse array of homogeneous elements (Issue 5) + 2016/08/22 permit [] inside file names in savejson + 2016/01/06 fix a bug that prevents saving to a file in savejson + + +== JSONlab 1.2 (codename: Optimus - Update 2), FangQ neu.edu> == + + 2015/12/16 replacing string concatenation by str cells to gain 2x speed in savejson (Issue#17) + 2015/12/11 fix FileName option case bug (SVN rev#495) + 2015/12/11 add SingletCell option, add SingletArray to replace NoRowBracket (Issue#15,#8) + 2015/11/10 fix bug for inerpreting file names as JSON string - by Mykhailo Bratukha (Pull#14) + 2015/10/16 fix bug for cell with transposed data - by Insik Kim (Pull#12) + 2015/09/25 support exporting matlab object to JSON - by Sertan Senturk (Pull#10, #11) + +== JSONlab 1.1 (codename: Optimus - Update 1), FangQ neu.edu> == + + 2015/05/05 *massively accelerating loadjson for parsing large collection of unstructured small objects + 2015/05/05 force array bracket in 1x1 struct to maintain depth (Issue#1) + 2015/05/05 parse logicals in loadjson + 2015/05/05 make options case insensitive + 2015/05/01 reading unicode encoded json files (thanks to Sertan Senturk,Issue#3) + 2015/04/30 allow \uXXXX to represent a unicode in a string (Issue#2) + 2015/03/30 save a 0x0 solid real empty array as null and handel empty struct array + 2015/03/30 properly handle escape characters in a string + 2015/01/24 *implement the UBJSON Draft12 new name format + 2015/01/13 correct cell array indentation inconsistency + +== JSONlab 1.0 (codename: Optimus - Final), FangQ neu.edu> == + + 2015/01/02 polish help info for all major functions, update examples, finalize 1.0 + 2014/12/19 fix a bug to strictly respect NoRowBracket in savejson + +== JSONlab 1.0.0-RC2 (codename: Optimus - RC2), FangQ neu.edu> == + + 2014/11/22 show progress bar in loadjson ('ShowProgress') + 2014/11/17 *add Compact option in savejson to output compact JSON format ('Compact') + 2014/11/17 add FastArrayParser in loadjson to specify fast parser applicable levels + 2014/09/18 *start official github mirror: https://github.com/fangq/jsonlab + +== JSONlab 1.0.0-RC1 (codename: Optimus - RC1), FangQ neu.edu> == + + 2014/09/17 fix several compatibility issues when running on octave versions 3.2-3.8 + 2014/09/17 *support 2D cell and struct arrays in both savejson and saveubjson + 2014/08/04 escape special characters in a JSON string + 2014/02/16 fix a bug when saving ubjson files + +== JSONlab 0.9.9 (codename: Optimus - beta), FangQ neu.edu> == + + 2014/01/22 use binary read and write in saveubjson and loadubjson + +== JSONlab 0.9.8-1 (codename: Optimus - alpha update 1), FangQ neu.edu> == + + 2013/10/07 better round-trip conservation for empty arrays and structs (patch submitted by Yul Kang) + +== JSONlab 0.9.8 (codename: Optimus - alpha), FangQ neu.edu> == + 2013/08/23 *universal Binary JSON (UBJSON) support, including both saveubjson and loadubjson + +== JSONlab 0.9.1 (codename: Rodimus, update 1), FangQ neu.edu> == + 2012/12/18 *handling of various empty and sparse matrices (fixes submitted by Niclas Borlin) + +== JSONlab 0.9.0 (codename: Rodimus), FangQ neu.edu> == + + 2012/06/17 *new format for an invalid leading char, unpacking hex code in savejson + 2012/06/01 support JSONP in savejson + 2012/05/25 fix the empty cell bug (reported by Cyril Davin) + 2012/04/05 savejson can save to a file (suggested by Patrick Rapin) + +== JSONlab 0.8.1 (codename: Sentiel, Update 1), FangQ neu.edu> == + + 2012/02/28 loadjson quotation mark escape bug, see http://bit.ly/yyk1nS + 2012/01/25 patch to handle root-less objects, contributed by Blake Johnson + +== JSONlab 0.8.0 (codename: Sentiel), FangQ neu.edu> == + + 2012/01/13 *speed up loadjson by 20 fold when parsing large data arrays in matlab + 2012/01/11 remove row bracket if an array has 1 element, suggested by Mykel Kochenderfer + 2011/12/22 *accept sequence of 'param',value input in savejson and loadjson + 2011/11/18 fix struct array bug reported by Mykel Kochenderfer + +== JSONlab 0.5.1 (codename: Nexus Update 1), FangQ neu.edu> == + + 2011/10/21 fix a bug in loadjson, previous code does not use any of the acceleration + 2011/10/20 loadjson supports JSON collections - concatenated JSON objects + +== JSONlab 0.5.0 (codename: Nexus), FangQ neu.edu> == + + 2011/10/16 package and release jsonlab 0.5.0 + 2011/10/15 *add json demo and regression test, support cpx numbers, fix double quote bug + 2011/10/11 *speed up readjson dramatically, interpret _Array* tags, show data in root level + 2011/10/10 create jsonlab project, start jsonlab website, add online documentation + 2011/10/07 *speed up savejson by 25x using sprintf instead of mat2str, add options support + 2011/10/06 *savejson works for structs, cells and arrays + 2011/09/09 derive loadjson from JSON parser from MATLAB Central, draft savejson.m diff --git a/Ext/Toolboxes/jsonlab/LICENSE_BSD.txt b/Ext/Toolboxes/jsonlab/LICENSE_BSD.txt new file mode 100644 index 00000000..1f80c5a2 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/LICENSE_BSD.txt @@ -0,0 +1,25 @@ +Copyright 2011-2018 Qianqian Fang neu.edu>. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are +permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, this list + of conditions and the following disclaimer in the documentation and/or other materials + provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those of the +authors and should not be interpreted as representing official policies, either expressed +or implied, of the copyright holders. diff --git a/Ext/Toolboxes/jsonlab/LICENSE_GPLv3.txt b/Ext/Toolboxes/jsonlab/LICENSE_GPLv3.txt new file mode 100644 index 00000000..ed488ef4 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/LICENSE_GPLv3.txt @@ -0,0 +1,699 @@ +=============================================================================== += JSONlab = += An open-source MATLAB/Octave JSON encoder and decoder = +=============================================================================== + +Copyright (C) 2011-2018 Qianqian Fang neu.edu> + +------------------------------------------------------------------------------- + +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 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +------------------------------------------------------------------------ + + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Ext/Toolboxes/jsonlab/README.rst b/Ext/Toolboxes/jsonlab/README.rst new file mode 100644 index 00000000..cec02a16 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/README.rst @@ -0,0 +1,459 @@ +############################################################################## + JSONLab: An open-source MATLAB/Octave JSON encoder and decoder +############################################################################## + +* Copyright (C) 2011-2018 Qianqian Fang +* License: BSD or GNU General Public License version 3 (GPL v3), see License*.txt +* Version: 1.8 (Nominus) + + +################# +Table of Contents +################# +.. contents:: + :local: + :depth: 3 + +============ +Introduction +============ + +JSON (`JavaScript Object Notation `_) is a highly portable, +human-readable and " `fat-free `_" text format +to represent complex and hierarchical data. It is as powerful as `XML `_, but less verbose. JSON format is widely used for data-exchange in applications, and is essential for the wild success +of (programming) `Ajax `_ and `Web2.0 `_. + +UBJSON (Universal Binary JSON) is a binary JSON format, specifically +optimized for compact file size and better performance while keeping +the semantics as simple as the text-based JSON format. Using the UBJSON +format allows to wrap complex binary data in a flexible and extensible +structure, making it possible to process complex and large dataset +without accuracy loss due to text conversions. + +We envision that both JSON and its binary version will serve as part of +the mainstream data-exchange formats for scientific research in the future. +It will provide the flexibility and generality achieved by other popular +general-purpose file specifications, such as `HDF5 `_, with significantly +reduced complexity and enhanced performance. + +JSONLab is a free and open-source implementation of a JSON/UBJSON encoder +and a decoder in the native MATLAB language. It can be used to convert a MATLAB +data structure (array, struct, cell, struct array and cell array) into +JSON/UBJSON formatted strings, or to decode a JSON/UBJSON file into MATLAB +data structure. JSONLab supports both MATLAB and `GNU Octave `_ (a free MATLAB clone). + +================ +Installation +================ + +The installation of JSONLab is no different than any other simple +MATLAB toolbox. You only need to download/unzip the JSONLab package +to a folder, and add the folder's path to MATLAB/Octave's path list +by using the following command: + +.. code:: shell + + addpath('/path/to/jsonlab'); + +If you want to add this path permanently, you need to type "pathtool", +browse to the jsonlab root folder and add to the list, then click "Save". +Then, run "rehash" in MATLAB, and type "which loadjson", if you see an +output, that means JSONLab is installed for MATLAB/Octave. + + +================ +Using JSONLab +================ + +JSONLab provides two functions, loadjson.m -- a MATLAB->JSON decoder, +and savejson.m -- a MATLAB->JSON encoder, for the text-based JSON, and +two equivallent functions -- loadubjson and saveubjson for the binary +JSON. The detailed help info for the four functions can be found below: + +---------- +loadjson.m +---------- + +.. code-block:: matlab + +
+        data=loadjson(fname,opt)
+           or
+        data=loadjson(fname,'param1',value1,'param2',value2,...)
+
+        parse a JSON (JavaScript Object Notation) file or string
+
+        authors:Qianqian Fang (q.fang  neu.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$
+
+        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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details 
+       
+ +---------- +savejson.m +---------- + +.. code-block:: matlab + +
+        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 (q.fang  neu.edu)
+        created on 2011/09/09
+
+        $Id$
+
+        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,
+             class instance).
+             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.SingletArray [0|1]: 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.SingletCell  [1|0]: if 1, always enclose a cell with "[]" 
+                                even it has only one element; if 0, brackets
+                                are ignored when a cell has only 1 element.
+               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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
+       
+ +------------- +loadubjson.m +------------- + +.. code-block:: matlab + +
+        data=loadubjson(fname,opt)
+           or
+        data=loadubjson(fname,'param1',value1,'param2',value2,...)
+
+        parse a JSON (JavaScript Object Notation) file or string
+
+        authors:Qianqian Fang (q.fang  neu.edu)
+        created on 2013/08/01
+
+        $Id$
+
+        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.
+                  opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or 
+                                earlier versions (JSONLab 1.0 final or earlier), 
+                                the "name" tag is treated as a string. To load 
+                                these UBJSON data, you need to manually set this 
+                                flag to 1.
+
+        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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details 
+      
+ +------------- +saveubjson.m +------------- + + +.. code-block:: matlab + + +
+        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 (q.fang  neu.edu)
+        created on 2013/08/17
+
+        $Id$
+
+        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,
+             class instance)
+             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.SingletArray [0|1]: 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.SingletCell  [1|0]: if 1, always enclose a cell with "[]" 
+                                even it has only one element; if 0, brackets
+                                are ignored when a cell has only 1 element.
+               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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
+      
+ +--------- +examples +--------- + +Under the ``"examples"`` folder, you can find several scripts to demonstrate the +basic utilities of JSONLab. Running the ``"demo_jsonlab_basic.m"`` script, you +will see the conversions from MATLAB data structure to JSON text and backward. +In ``"jsonlab_selftest.m"``, we load complex JSON files downloaded from the Internet +and validate the ``loadjson/savejson`` functions for regression testing purposes. +Similarly, a ``"demo_ubjson_basic.m"`` script is provided to test the saveubjson +and loadubjson functions for various matlab data structures. + +Please run these examples and understand how JSONLab works before you use +it to process your data. + +======================= +Known Issues and TODOs +======================= + +JSONLab has several known limitations. We are striving to make it more general +and robust. Hopefully in a few future releases, the limitations become less. + +Here are the known issues: + + * 3D or higher dimensional cell/struct-arrays will be converted to 2D arrays + + * When processing names containing multi-byte characters, Octave and MATLAB can give different field-names; you can use feature('DefaultCharacterSet','latin1') in MATLAB to get consistant results + + * savejson can not handle class and dataset. + + * saveubjson converts a logical array into a uint8 ([U]) array + + * an unofficial N-D array count syntax is implemented in saveubjson. We are actively communicating with the UBJSON spec maintainer to investigate the possibility of making it upstream + + * loadubjson can not parse all UBJSON Specification (Draft 9) compliant files, however, it can parse all UBJSON files produced by saveubjson. + +========================== +Contribution and feedback +========================== + +JSONLab is an open-source project. This means you can not only use it and modify +it as you wish, but also you can contribute your changes back to JSONLab so +that everyone else can enjoy the improvement. For anyone who want to contribute, +please download JSONLab source code from its source code repositories by using the +following command: + + +.. code:: shell + + git clone https://github.com/fangq/jsonlab.git jsonlab + +or browsing the github site at + +.. code:: shell + + https://github.com/fangq/jsonlab + + +alternatively, if you prefer svn, you can checkout the latest code by using + +.. code:: shell + + svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab + +You can make changes to the files as needed. Once you are satisfied with your +changes, and ready to share it with others, please cd the root directory of +JSONLab, and type + +.. code:: shell + + git diff --no-prefix > yourname_featurename.patch + + +or + +.. code:: shell + + svn diff > yourname_featurename.patch + +You then email the .patch file to JSONLab's maintainer, Qianqian Fang, at +the email address shown in the beginning of this file. Qianqian will review +the changes and commit it to the subversion if they are satisfactory. + +We appreciate any suggestions and feedbacks from you. Please use the following +mailing list to report any questions you may have regarding JSONLab: + +`forum/jsonlab-users `_ + +(Subscription to the mailing list is needed in order to post messages). diff --git a/Ext/Toolboxes/jsonlab/README.txt b/Ext/Toolboxes/jsonlab/README.txt new file mode 100644 index 00000000..ada6a854 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/README.txt @@ -0,0 +1,431 @@ +=============================================================================== += JSONLab = += An open-source MATLAB/Octave JSON encoder and decoder = +=============================================================================== + +*Copyright (C) 2011-2018 Qianqian Fang +*License: BSD or GNU General Public License version 3 (GPL v3), see License*.txt +*Version: 1.8 (Nominus) + +------------------------------------------------------------------------------- + +Table of Content: + +I. Introduction +II. Installation +III.Using JSONLab +IV. Known Issues and TODOs +V. Contribution and feedback + +------------------------------------------------------------------------------- + +I. Introduction + +JSON ([http://www.json.org/ JavaScript Object Notation]) is a highly portable, +human-readable and "[http://en.wikipedia.org/wiki/JSON fat-free]" text format +to represent complex and hierarchical data. It is as powerful as +[http://en.wikipedia.org/wiki/XML XML], but less verbose. JSON format is widely +used for data-exchange in applications, and is essential for the wild success +of [http://en.wikipedia.org/wiki/Ajax_(programming) Ajax] and +[http://en.wikipedia.org/wiki/Web_2.0 Web2.0]. + +UBJSON (Universal Binary JSON) is a binary JSON format, specifically +optimized for compact file size and better performance while keeping +the semantics as simple as the text-based JSON format. Using the UBJSON +format allows to wrap complex binary data in a flexible and extensible +structure, making it possible to process complex and large dataset +without accuracy loss due to text conversions. + +We envision that both JSON and its binary version will serve as part of +the mainstream data-exchange formats for scientific research in the future. +It will provide the flexibility and generality achieved by other popular +general-purpose file specifications, such as +[http://www.hdfgroup.org/HDF5/whatishdf5.html HDF5], with significantly +reduced complexity and enhanced performance. + +JSONLab is a free and open-source implementation of a JSON/UBJSON encoder +and a decoder in the native MATLAB language. It can be used to convert a MATLAB +data structure (array, struct, cell, struct array and cell array) into +JSON/UBJSON formatted strings, or to decode a JSON/UBJSON file into MATLAB +data structure. JSONLab supports both MATLAB and +[http://www.gnu.org/software/octave/ GNU Octave] (a free MATLAB clone). + +------------------------------------------------------------------------------- + +II. Installation + +The installation of JSONLab is no different than any other simple +MATLAB toolbox. You only need to download/unzip the JSONLab package +to a folder, and add the folder's path to MATLAB/Octave's path list +by using the following command: + + addpath('/path/to/jsonlab'); + +If you want to add this path permanently, you need to type "pathtool", +browse to the jsonlab root folder and add to the list, then click "Save". +Then, run "rehash" in MATLAB, and type "which loadjson", if you see an +output, that means JSONLab is installed for MATLAB/Octave. + +------------------------------------------------------------------------------- + +III.Using JSONLab + +JSONLab provides two functions, loadjson.m -- a MATLAB->JSON decoder, +and savejson.m -- a MATLAB->JSON encoder, for the text-based JSON, and +two equivallent functions -- loadubjson and saveubjson for the binary +JSON. The detailed help info for the four functions can be found below: + +=== loadjson.m === +
+  data=loadjson(fname,opt)
+     or
+  data=loadjson(fname,'param1',value1,'param2',value2,...)
+ 
+  parse a JSON (JavaScript Object Notation) file or string
+ 
+  authors:Qianqian Fang (q.fang  neu.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$
+ 
+  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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details 
+ 
+ +=== savejson.m === + +
+  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 (q.fang  neu.edu)
+  created on 2011/09/09
+ 
+  $Id$
+ 
+  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,
+       class instance).
+       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.SingletArray [0|1]: 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.SingletCell  [1|0]: if 1, always enclose a cell with "[]" 
+                          even it has only one element; if 0, brackets
+                          are ignored when a cell has only 1 element.
+         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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
+ 
+ +=== loadubjson.m === + +
+  data=loadubjson(fname,opt)
+     or
+  data=loadubjson(fname,'param1',value1,'param2',value2,...)
+ 
+  parse a JSON (JavaScript Object Notation) file or string
+ 
+  authors:Qianqian Fang (q.fang  neu.edu)
+  created on 2013/08/01
+ 
+  $Id$
+ 
+  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.
+            opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or 
+                          earlier versions (JSONLab 1.0 final or earlier), 
+                          the "name" tag is treated as a string. To load 
+                          these UBJSON data, you need to manually set this 
+                          flag to 1.
+ 
+  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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details 
+
+ +=== saveubjson.m === + +
+  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 (q.fang  neu.edu)
+  created on 2013/08/17
+ 
+  $Id$
+ 
+  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,
+       class instance)
+       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.SingletArray [0|1]: 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.SingletCell  [1|0]: if 1, always enclose a cell with "[]" 
+                          even it has only one element; if 0, brackets
+                          are ignored when a cell has only 1 element.
+         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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
+
+ + +=== examples === + +Under the "examples" folder, you can find several scripts to demonstrate the +basic utilities of JSONLab. Running the "demo_jsonlab_basic.m" script, you +will see the conversions from MATLAB data structure to JSON text and backward. +In "jsonlab_selftest.m", we load complex JSON files downloaded from the Internet +and validate the loadjson/savejson functions for regression testing purposes. +Similarly, a "demo_ubjson_basic.m" script is provided to test the saveubjson +and loadubjson functions for various matlab data structures. + +Please run these examples and understand how JSONLab works before you use +it to process your data. + +------------------------------------------------------------------------------- + +IV. Known Issues and TODOs + +JSONLab has several known limitations. We are striving to make it more general +and robust. Hopefully in a few future releases, the limitations become less. + +Here are the known issues: + +# 3D or higher dimensional cell/struct-arrays will be converted to 2D arrays; +# When processing names containing multi-byte characters, Octave and MATLAB \ +can give different field-names; you can use feature('DefaultCharacterSet','latin1') \ +in MATLAB to get consistant results +# savejson can not handle class and dataset. +# saveubjson converts a logical array into a uint8 ([U]) array +# an unofficial N-D array count syntax is implemented in saveubjson. We are \ +actively communicating with the UBJSON spec maintainer to investigate the \ +possibility of making it upstream +# loadubjson can not parse all UBJSON Specification (Draft 9) compliant \ +files, however, it can parse all UBJSON files produced by saveubjson. + +------------------------------------------------------------------------------- + +V. Contribution and feedback + +JSONLab is an open-source project. This means you can not only use it and modify +it as you wish, but also you can contribute your changes back to JSONLab so +that everyone else can enjoy the improvement. For anyone who want to contribute, +please download JSONLab source code from its source code repositories by using the +following command: + + git clone https://github.com/fangq/jsonlab.git jsonlab + +or browsing the github site at + + https://github.com/fangq/jsonlab + +alternatively, if you prefer svn, you can checkout the latest code by using + + svn checkout svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab jsonlab + +You can make changes to the files as needed. Once you are satisfied with your +changes, and ready to share it with others, please cd the root directory of +JSONLab, and type + + git diff --no-prefix > yourname_featurename.patch + +or + + svn diff > yourname_featurename.patch + +You then email the .patch file to JSONLab's maintainer, Qianqian Fang, at +the email address shown in the beginning of this file. Qianqian will review +the changes and commit it to the subversion if they are satisfactory. + +We appreciate any suggestions and feedbacks from you. Please use the following +mailing list to report any questions you may have regarding JSONLab: + +https://groups.google.com/forum/?hl=en#!forum/jsonlab-users + +(Subscription to the mailing list is needed in order to post messages). diff --git a/Ext/Toolboxes/jsonlab/examples/demo_jsonlab_basic.m b/Ext/Toolboxes/jsonlab/examples/demo_jsonlab_basic.m new file mode 100644 index 00000000..d44d4ff1 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/demo_jsonlab_basic.m @@ -0,0 +1,181 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Demonstration of Basic Utilities of JSONlab +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +rngstate = rand ('state'); +randseed=hex2dec('623F9A9E'); +clear data2json json2data + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a simple scalar value \n') +fprintf(1,'%%=================================================\n\n') + +data2json=pi +savejson('',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a complex number\n') +fprintf(1,'%%=================================================\n\n') + +clear i; +data2json=1+2*i +savejson('',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a complex matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=magic(6); +data2json=data2json(:,1:3)+data2json(:,4:6)*i +savejson('',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% MATLAB special constants\n') +fprintf(1,'%%=================================================\n\n') + +data2json=[NaN Inf -Inf] +savejson('specials',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a real sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sprand(10,10,0.1) +savejson('sparse',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a complex sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=data2json-data2json*i +savejson('complex_sparse',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an all-zero sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse(2,3); +savejson('all_zero_sparse',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an empty sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse([]); +savejson('empty_sparse',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an empty 0-by-0 real matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=[]; +savejson('empty_0by0_real',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an empty 0-by-3 real matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=zeros(0,3); +savejson('empty_0by3_real',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse real column vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse([0,3,0,1,4]'); +savejson('sparse_column_vector',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse complex column vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=data2json-1i*data2json; +savejson('complex_sparse_column_vector',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse real row vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse([0,3,0,1,4]); +savejson('sparse_row_vector',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse complex row vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=data2json-1i*data2json; +savejson('complex_sparse_row_vector',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a structure\n') +fprintf(1,'%%=================================================\n\n') + +data2json=struct('name','Think Different','year',1997,'magic',magic(3),... + 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false)) +savejson('astruct',data2json,struct('ParseLogical',1)) +json2data=loadjson(ans) +class(json2data.astruct.embedded.left) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a structure array\n') +fprintf(1,'%%=================================================\n\n') + +data2json=struct('name','Nexus Prime','rank',9); +data2json(2)=struct('name','Sentinel Prime','rank',9); +data2json(3)=struct('name','Optimus Prime','rank',9); +savejson('Supreme Commander',data2json) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a cell array\n') +fprintf(1,'%%=================================================\n\n') + +data2json=cell(3,1); +data2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,... + 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0); +data2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']); +data2json{3}=[10.04,10.10,11.04,11.10] +savejson('debian',data2json,struct('FloatFormat','%.2f')) +json2data=loadjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% invalid field-name handling\n') +fprintf(1,'%%=================================================\n\n') + +json2data=loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"绝密"}') + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a 2D cell array\n') +fprintf(1,'%%=================================================\n\n') + +data2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}}; +savejson('data2json',data2json) +json2data=loadjson(ans) % only savejson works for cell arrays, loadjson has issues + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a 2D struct array\n') +fprintf(1,'%%=================================================\n\n') + +data2json=repmat(struct('idx',0,'data','structs'),[2,3]) +for i=1:6 + data2json(i).idx=i; +end +savejson('data2json',data2json) +json2data=loadjson(ans) + +rand ('state',rngstate); + diff --git a/Ext/Toolboxes/jsonlab/examples/demo_ubjson_basic.m b/Ext/Toolboxes/jsonlab/examples/demo_ubjson_basic.m new file mode 100644 index 00000000..0c35433a --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/demo_ubjson_basic.m @@ -0,0 +1,180 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Demonstration of Basic Utilities of JSONlab +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +rngstate = rand ('state'); +randseed=hex2dec('623F9A9E'); +clear data2json json2data + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a simple scalar value \n') +fprintf(1,'%%=================================================\n\n') + +data2json=pi +saveubjson('',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a complex number\n') +fprintf(1,'%%=================================================\n\n') + +clear i; +data2json=1+2*i +saveubjson('',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a complex matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=magic(6); +data2json=data2json(:,1:3)+data2json(:,4:6)*i +saveubjson('',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% MATLAB special constants\n') +fprintf(1,'%%=================================================\n\n') + +data2json=[NaN Inf -Inf] +saveubjson('specials',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a real sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sprand(10,10,0.1) +saveubjson('sparse',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a complex sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=data2json-data2json*i +saveubjson('complex_sparse',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an all-zero sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse(2,3); +saveubjson('all_zero_sparse',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an empty sparse matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse([]); +saveubjson('empty_sparse',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an empty 0-by-0 real matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=[]; +saveubjson('empty_0by0_real',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% an empty 0-by-3 real matrix\n') +fprintf(1,'%%=================================================\n\n') + +data2json=zeros(0,3); +saveubjson('empty_0by3_real',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse real column vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse([0,3,0,1,4]'); +saveubjson('sparse_column_vector',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse complex column vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=data2json-1i*data2json; +saveubjson('complex_sparse_column_vector',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse real row vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=sparse([0,3,0,1,4]); +saveubjson('sparse_row_vector',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a sparse complex row vector\n') +fprintf(1,'%%=================================================\n\n') + +data2json=data2json-1i*data2json; +saveubjson('complex_sparse_row_vector',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a structure\n') +fprintf(1,'%%=================================================\n\n') + +data2json=struct('name','Think Different','year',1997,'magic',magic(3),... + 'misfits',[Inf,NaN],'embedded',struct('left',true,'right',false)) +saveubjson('astruct',data2json,struct('ParseLogical',1)) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a structure array\n') +fprintf(1,'%%=================================================\n\n') + +data2json=struct('name','Nexus Prime','rank',9); +data2json(2)=struct('name','Sentinel Prime','rank',9); +data2json(3)=struct('name','Optimus Prime','rank',9); +saveubjson('Supreme Commander',data2json) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a cell array\n') +fprintf(1,'%%=================================================\n\n') + +data2json=cell(3,1); +data2json{1}=struct('buzz',1.1,'rex',1.2,'bo',1.3,'hamm',2.0,'slink',2.1,'potato',2.2,... + 'woody',3.0,'sarge',3.1,'etch',4.0,'lenny',5.0,'squeeze',6.0,'wheezy',7.0); +data2json{2}=struct('Ubuntu',['Kubuntu';'Xubuntu';'Lubuntu']); +data2json{3}=[10.04,10.10,11.04,11.10] +saveubjson('debian',data2json,struct('FloatFormat','%.2f')) +json2data=loadubjson(ans) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% invalid field-name handling\n') +fprintf(1,'%%=================================================\n\n') + +json2data=loadubjson(saveubjson('',loadjson('{"ValidName":1, "_InvalidName":2, ":Field:":3, "项目":"绝密"}'))) + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a 2D cell array\n') +fprintf(1,'%%=================================================\n\n') + +data2json={{1,{2,3}},{4,5},{6};{7},{8,9},{10}}; +saveubjson('data2json',data2json) +json2data=loadubjson(ans) % only savejson works for cell arrays, loadjson has issues + +fprintf(1,'\n%%=================================================\n') +fprintf(1,'%% a 2D struct array\n') +fprintf(1,'%%=================================================\n\n') + +data2json=repmat(struct('idx',0,'data','structs'),[2,3]) +for i=1:6 + data2json(i).idx=i; +end +saveubjson('data2json',data2json) +json2data=loadubjson(ans) + +rand ('state',rngstate); + diff --git a/Ext/Toolboxes/jsonlab/examples/example1.json b/Ext/Toolboxes/jsonlab/examples/example1.json new file mode 100644 index 00000000..850488fc --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/example1.json @@ -0,0 +1,21 @@ +{ + "firstName": "John", + "lastName": "Smith", + "age": 25, + "address": { + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021" + }, + "phoneNumber": [ + { + "type": "home", + "number": "212 555-1234" + }, + { + "type": "fax", + "number": "646 555-4567" + } + ] +} diff --git a/Ext/Toolboxes/jsonlab/examples/example2.json b/Ext/Toolboxes/jsonlab/examples/example2.json new file mode 100644 index 00000000..eacfbf5e --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/example2.json @@ -0,0 +1,22 @@ +{ + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": ["GML", "XML"] + }, + "GlossSee": "markup" + } + } + } + } +} diff --git a/Ext/Toolboxes/jsonlab/examples/example3.json b/Ext/Toolboxes/jsonlab/examples/example3.json new file mode 100644 index 00000000..f52661bf --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/example3.json @@ -0,0 +1,11 @@ +{"menu": { + "id": "file", + "value": "_&File", + "popup": { + "menuitem": [ + {"value": "_&New", "onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")"}, + {"value": "_&Open", "onclick": "OpenDoc()"}, + {"value": "_&Close", "onclick": "CloseDoc()"} + ] + } +}} diff --git a/Ext/Toolboxes/jsonlab/examples/example4.json b/Ext/Toolboxes/jsonlab/examples/example4.json new file mode 100644 index 00000000..1872c12f --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/example4.json @@ -0,0 +1,35 @@ +[ + { + "sample" : { + "rho" : 1 + } + }, + { + "sample" : { + "rho" : 2 + } + }, + [ + { + "_ArrayType_" : "double", + "_ArraySize_" : [1,2], + "_ArrayData_" : [1,0] + }, + { + "_ArrayType_" : "double", + "_ArraySize_" : [1,2], + "_ArrayData_" : [1,1] + }, + { + "_ArrayType_" : "double", + "_ArraySize_" : [1,2], + "_ArrayData_" : [1,2] + } + ], + [ + "Paper", + "Scissors", + "Stone" + ], + ["a", "b\\", "c\"","d\\\"","e\"[","f\\\"[","g[\\","h[\\\""] +] diff --git a/Ext/Toolboxes/jsonlab/examples/jsonlab_basictest.matlab b/Ext/Toolboxes/jsonlab/examples/jsonlab_basictest.matlab new file mode 100644 index 00000000..4bd16fa6 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/jsonlab_basictest.matlab @@ -0,0 +1,671 @@ + + < M A T L A B (R) > + Copyright 1984-2010 The MathWorks, Inc. + Version 7.11.0.584 (R2010b) 64-bit (glnxa64) + August 16, 2010 + + + To get started, type one of these: helpwin, helpdesk, or demo. + For product information, visit www.mathworks.com. + +>> >> >> >> >> >> >> >> >> +%================================================= +>> % a simple scalar value +>> %================================================= + +>> >> +data2json = + + 3.1416 + +>> +ans = + +[3.141592654] + + +>> +json2data = + + 3.1416 + +>> >> +%================================================= +>> % a complex number +>> %================================================= + +>> >> >> +data2json = + + 1.0000 + 2.0000i + +>> +ans = + +{ + "_ArrayType_": "double", + "_ArraySize_": [1,1], + "_ArrayIsComplex_": 1, + "_ArrayData_": [1,2] +} + + +>> +json2data = + + 1.0000 + 2.0000i + +>> >> +%================================================= +>> % a complex matrix +>> %================================================= + +>> >> >> +data2json = + + 35.0000 +26.0000i 1.0000 +19.0000i 6.0000 +24.0000i + 3.0000 +21.0000i 32.0000 +23.0000i 7.0000 +25.0000i + 31.0000 +22.0000i 9.0000 +27.0000i 2.0000 +20.0000i + 8.0000 +17.0000i 28.0000 +10.0000i 33.0000 +15.0000i + 30.0000 +12.0000i 5.0000 +14.0000i 34.0000 +16.0000i + 4.0000 +13.0000i 36.0000 +18.0000i 29.0000 +11.0000i + +>> +ans = + +{ + "_ArrayType_": "double", + "_ArraySize_": [6,3], + "_ArrayIsComplex_": 1, + "_ArrayData_": [ + [35,26], + [3,21], + [31,22], + [8,17], + [30,12], + [4,13], + [1,19], + [32,23], + [9,27], + [28,10], + [5,14], + [36,18], + [6,24], + [7,25], + [2,20], + [33,15], + [34,16], + [29,11] + ] +} + + +>> +json2data = + + 35.0000 +26.0000i 1.0000 +19.0000i 6.0000 +24.0000i + 3.0000 +21.0000i 32.0000 +23.0000i 7.0000 +25.0000i + 31.0000 +22.0000i 9.0000 +27.0000i 2.0000 +20.0000i + 8.0000 +17.0000i 28.0000 +10.0000i 33.0000 +15.0000i + 30.0000 +12.0000i 5.0000 +14.0000i 34.0000 +16.0000i + 4.0000 +13.0000i 36.0000 +18.0000i 29.0000 +11.0000i + +>> >> +%================================================= +>> % MATLAB special constants +>> %================================================= + +>> >> +data2json = + + NaN Inf -Inf + +>> +ans = + +{ + "specials": ["_NaN_","_Inf_","-_Inf_"] +} + + +>> +json2data = + + specials: [NaN Inf -Inf] + +>> >> +%================================================= +>> % a real sparse matrix +>> %================================================= + +>> >> +data2json = + + (1,2) 0.6557 + (9,2) 0.7577 + (3,5) 0.8491 + (10,5) 0.7431 + (10,8) 0.3922 + (7,9) 0.6787 + (2,10) 0.0357 + (6,10) 0.9340 + (10,10) 0.6555 + +>> +ans = + +{ + "sparse": { + "_ArrayType_": "double", + "_ArraySize_": [10,10], + "_ArrayIsSparse_": 1, + "_ArrayData_": [ + [1,2,0.6557406992], + [9,2,0.7577401306], + [3,5,0.8491293059], + [10,5,0.7431324681], + [10,8,0.3922270195], + [7,9,0.6787351549], + [2,10,0.03571167857], + [6,10,0.9339932478], + [10,10,0.6554778902] + ] + } +} + + +>> +json2data = + + sparse: [10x10 double] + +>> >> +%================================================= +>> % a complex sparse matrix +>> %================================================= + +>> >> +data2json = + + (1,2) 0.6557 - 0.6557i + (9,2) 0.7577 - 0.7577i + (3,5) 0.8491 - 0.8491i + (10,5) 0.7431 - 0.7431i + (10,8) 0.3922 - 0.3922i + (7,9) 0.6787 - 0.6787i + (2,10) 0.0357 - 0.0357i + (6,10) 0.9340 - 0.9340i + (10,10) 0.6555 - 0.6555i + +>> +ans = + +{ + "complex_sparse": { + "_ArrayType_": "double", + "_ArraySize_": [10,10], + "_ArrayIsComplex_": 1, + "_ArrayIsSparse_": 1, + "_ArrayData_": [ + [1,2,0.6557406992,-0.6557406992], + [9,2,0.7577401306,-0.7577401306], + [3,5,0.8491293059,-0.8491293059], + [10,5,0.7431324681,-0.7431324681], + [10,8,0.3922270195,-0.3922270195], + [7,9,0.6787351549,-0.6787351549], + [2,10,0.03571167857,-0.03571167857], + [6,10,0.9339932478,-0.9339932478], + [10,10,0.6554778902,-0.6554778902] + ] + } +} + + +>> +json2data = + + complex_sparse: [10x10 double] + +>> >> +%================================================= +>> % an all-zero sparse matrix +>> %================================================= + +>> >> >> +ans = + +{ + "all_zero_sparse": { + "_ArrayType_": "double", + "_ArraySize_": [2,3], + "_ArrayIsSparse_": 1, + "_ArrayData_": null + } +} + + +>> +json2data = + + all_zero_sparse: [2x3 double] + +>> >> +%================================================= +>> % an empty sparse matrix +>> %================================================= + +>> >> >> +ans = + +{ + "empty_sparse": { + "_ArrayType_": "double", + "_ArraySize_": [0,0], + "_ArrayIsSparse_": 1, + "_ArrayData_": null + } +} + + +>> +json2data = + + empty_sparse: [] + +>> >> +%================================================= +>> % an empty 0-by-0 real matrix +>> %================================================= + +>> >> >> +ans = + +{ + "empty_0by0_real": null +} + + +>> +json2data = + + empty_0by0_real: [] + +>> >> +%================================================= +>> % an empty 0-by-3 real matrix +>> %================================================= + +>> >> >> +ans = + +{ + "empty_0by3_real": { + "_ArrayType_": "double", + "_ArraySize_": [0,3], + "_ArrayData_": null + } +} + + +>> +json2data = + + empty_0by3_real: [0x3 double] + +>> >> +%================================================= +>> % a sparse real column vector +>> %================================================= + +>> >> >> +ans = + +{ + "sparse_column_vector": { + "_ArrayType_": "double", + "_ArraySize_": [5,1], + "_ArrayIsSparse_": 1, + "_ArrayData_": [ + [2,3], + [4,1], + [5,4] + ] + } +} + + +>> +json2data = + + sparse_column_vector: [5x1 double] + +>> >> +%================================================= +>> % a sparse complex column vector +>> %================================================= + +>> >> >> +ans = + +{ + "complex_sparse_column_vector": { + "_ArrayType_": "double", + "_ArraySize_": [5,1], + "_ArrayIsComplex_": 1, + "_ArrayIsSparse_": 1, + "_ArrayData_": [ + [2,3,-3], + [4,1,-1], + [5,4,-4] + ] + } +} + + +>> +json2data = + + complex_sparse_column_vector: [5x1 double] + +>> >> +%================================================= +>> % a sparse real row vector +>> %================================================= + +>> >> >> +ans = + +{ + "sparse_row_vector": { + "_ArrayType_": "double", + "_ArraySize_": [1,5], + "_ArrayIsSparse_": 1, + "_ArrayData_": [ + [2,3], + [4,1], + [5,4] + ] + } +} + + +>> +json2data = + + sparse_row_vector: [0 3 0 1 4] + +>> >> +%================================================= +>> % a sparse complex row vector +>> %================================================= + +>> >> >> +ans = + +{ + "complex_sparse_row_vector": { + "_ArrayType_": "double", + "_ArraySize_": [1,5], + "_ArrayIsComplex_": 1, + "_ArrayIsSparse_": 1, + "_ArrayData_": [ + [2,3,-3], + [4,1,-1], + [5,4,-4] + ] + } +} + + +>> +json2data = + + complex_sparse_row_vector: [1x5 double] + +>> >> +%================================================= +>> % a structure +>> %================================================= + +>> >> +data2json = + + name: 'Think Different' + year: 1997 + magic: [3x3 double] + misfits: [Inf NaN] + embedded: [1x1 struct] + +>> +ans = + +{ + "astruct": { + "name": "Think Different", + "year": 1997, + "magic": [ + [8,1,6], + [3,5,7], + [4,9,2] + ], + "misfits": ["_Inf_","_NaN_"], + "embedded": { + "left": true, + "right": false + } + } +} + + +>> +json2data = + + astruct: [1x1 struct] + +>> +ans = + +logical + +>> >> +%================================================= +>> % a structure array +>> %================================================= + +>> >> >> >> >> +ans = + +{ + "Supreme Commander": [ + { + "name": "Nexus Prime", + "rank": 9 + }, + { + "name": "Sentinel Prime", + "rank": 9 + }, + { + "name": "Optimus Prime", + "rank": 9 + } + ] +} + + +>> +json2data = + + Supreme_0x20_Commander: {[1x1 struct] [1x1 struct] [1x1 struct]} + +>> >> +%================================================= +>> % a cell array +>> %================================================= + +>> >> >> >> >> +data2json = + + [1x1 struct] + [1x1 struct] + [1x4 double] + +>> +ans = + +{ + "debian": [ + [ + { + "buzz": 1.10, + "rex": 1.20, + "bo": 1.30, + "hamm": 2.00, + "slink": 2.10, + "potato": 2.20, + "woody": 3.00, + "sarge": 3.10, + "etch": 4.00, + "lenny": 5.00, + "squeeze": 6.00, + "wheezy": 7.00 + } + ], + [ + { + "Ubuntu": [ + "Kubuntu", + "Xubuntu", + "Lubuntu" + ] + } + ], + [ + [10.04,10.10,11.04,11.10] + ] + ] +} + + +>> +json2data = + + debian: {{1x1 cell} {1x1 cell} [10.0400 10.1000 11.0400 11.1000]} + +>> >> +%================================================= +>> % invalid field-name handling +>> %================================================= + +>> >> +json2data = + + ValidName: 1 + x0x5F_InvalidName: 2 + x0x3A_Field_0x3A_: 3 + x0xE9A1B9__0xE79BAE_: '绝密' + +>> >> +%================================================= +>> % a 2D cell array +>> %================================================= + +>> >> >> +ans = + +{ + "data2json": [ + [ + [ + 1, + [ + 2, + 3 + ] + ], + [ + 4, + 5 + ], + [ + 6 + ] + ], + [ + [ + 7 + ], + [ + 8, + 9 + ], + [ + 10 + ] + ] + ] +} + + +>> +json2data = + + data2json: {{3x1 cell} {3x1 cell}} + +>> >> +%================================================= +>> % a 2D struct array +>> %================================================= + +>> >> +data2json = + +2x3 struct array with fields: + idx + data + +>> >> +ans = + +{ + "data2json": [ + [ + { + "idx": 1, + "data": "structs" + }, + { + "idx": 2, + "data": "structs" + } + ], + [ + { + "idx": 3, + "data": "structs" + }, + { + "idx": 4, + "data": "structs" + } + ], + [ + { + "idx": 5, + "data": "structs" + }, + { + "idx": 6, + "data": "structs" + } + ] + ] +} + + +>> +json2data = + + data2json: {{1x2 cell} {1x2 cell} {1x2 cell}} + +>> >> >> >> \ No newline at end of file diff --git a/Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.m b/Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.m new file mode 100644 index 00000000..27aee244 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.m @@ -0,0 +1,27 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Regression Test Unit of loadjson and savejson +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +for i=1:4 + fname=sprintf('example%d.json',i); + if(exist(fname,'file')==0) break; end + fprintf(1,'===============================================\n>> %s\n',fname); + json=savejson('data',loadjson(fname)); + fprintf(1,'%s\n',json); + fprintf(1,'%s\n',savejson('data',loadjson(fname),'Compact',1)); + data=loadjson(json); + savejson('data',data,'selftest.json'); + data=loadjson('selftest.json'); +end + +for i=1:4 + fname=sprintf('example%d.json',i); + if(exist(fname,'file')==0) break; end + fprintf(1,'===============================================\n>> %s\n',fname); + json=saveubjson('data',loadjson(fname)); + fprintf(1,'%s\n',json); + data=loadubjson(json); + savejson('',data); + saveubjson('data',data,'selftest.ubj'); + data=loadubjson('selftest.ubj'); +end diff --git a/Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.matlab b/Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.matlab new file mode 100644 index 00000000..ac652c56 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/jsonlab_selftest.matlab @@ -0,0 +1,154 @@ + + < M A T L A B (R) > + Copyright 1984-2010 The MathWorks, Inc. + Version 7.11.0.584 (R2010b) 64-bit (glnxa64) + August 16, 2010 + + + To get started, type one of these: helpwin, helpdesk, or demo. + For product information, visit www.mathworks.com. + +>> >> >> >> >> =============================================== +>> example1.json +{ + "data": { + "firstName": "John", + "lastName": "Smith", + "age": 25, + "address": { + "streetAddress": "21 2nd Street", + "city": "New York", + "state": "NY", + "postalCode": "10021" + }, + "phoneNumber": [ + { + "type": "home", + "number": "212 555-1234" + }, + { + "type": "fax", + "number": "646 555-4567" + } + ] + } +} + +{"data": {"firstName": "John","lastName": "Smith","age": 25,"address": {"streetAddress": "21 2nd Street","city": "New York","state": "NY","postalCode": "10021"},"phoneNumber": [{"type": "home","number": "212 555-1234"},{"type": "fax","number": "646 555-4567"}]}} + +=============================================== +>> example2.json +{ + "data": { + "glossary": { + "title": "example glossary", + "GlossDiv": { + "title": "S", + "GlossList": { + "GlossEntry": { + "ID": "SGML", + "SortAs": "SGML", + "GlossTerm": "Standard Generalized Markup Language", + "Acronym": "SGML", + "Abbrev": "ISO 8879:1986", + "GlossDef": { + "para": "A meta-markup language, used to create markup languages such as DocBook.", + "GlossSeeAlso": [ + "GML", + "XML" + ] + }, + "GlossSee": "markup" + } + } + } + } + } +} + +{"data": {"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML","XML"]},"GlossSee": "markup"}}}}}} + +=============================================== +>> example3.json +{ + "data": { + "menu": { + "id": "file", + "value": "_&File", + "popup": { + "menuitem": [ + { + "value": "_&New", + "onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")" + }, + { + "value": "_&Open", + "onclick": "OpenDoc()" + }, + { + "value": "_&Close", + "onclick": "CloseDoc()" + } + ] + } + } + } +} + +{"data": {"menu": {"id": "file","value": "_&File","popup": {"menuitem": [{"value": "_&New","onclick": "CreateNewDoc(\"'\\\"Untitled\\\"'\")"},{"value": "_&Open","onclick": "OpenDoc()"},{"value": "_&Close","onclick": "CloseDoc()"}]}}}} + +=============================================== +>> example4.json +{ + "data": [ + { + "sample": { + "rho": 1 + } + }, + { + "sample": { + "rho": 2 + } + }, + [ + [1,0], + [1,1], + [1,2] + ], + [ + "Paper", + "Scissors", + "Stone" + ], + [ + "a", + "b\\", + "c\"", + "d\\\"", + "e\"[", + "f\\\"[", + "g[\\", + "h[\\\"" + ] + ] +} + +{"data": [{"sample": {"rho": 1}},{"sample": {"rho": 2}},[[1,0],[1,1],[1,2]],["Paper","Scissors","Stone"],["a","b\\","c\"","d\\\"","e\"[","f\\\"[","g[\\","h[\\\""]]} + +>> >> =============================================== +>> example1.json +{Udata{U firstNameSUJohnUlastNameSUSmithUageiUaddress{U streetAddressSU 21 2nd StreetUcitySUNew YorkUstateSUNYU +postalCodeSU10021}U phoneNumber[{UtypeSUhomeUnumberSU 212 555-1234}{UtypeSUfaxUnumberSU 646 555-4567}]}} +=============================================== +>> example2.json +{Udata{Uglossary{UtitleSUexample glossaryUGlossDiv{UtitleCSU GlossList{U +GlossEntry{UIDSUSGMLUSortAsSUSGMLU GlossTermSU$Standard Generalized Markup LanguageUAcronymSUSGMLUAbbrevSU ISO 8879:1986UGlossDef{UparaSUHA meta-markup language, used to create markup languages such as DocBook.U GlossSeeAlso[SUGMLSUXML]}UGlossSeeSUmarkup}}}}}} +=============================================== +>> example3.json +{Udata{Umenu{UidSUfileUvalueSU_&FileUpopup{Umenuitem[{UvalueSU_&NewUonclickSUCreateNewDoc("'\"Untitled\"'")}{UvalueSU_&OpenUonclickSU OpenDoc()}{UvalueSU_&CloseUonclickSU +CloseDoc()}]}}}} +=============================================== +>> example4.json +{Udata[{Usample{Urhoi}}{Usample{Urhoi}}[[$i#U[$i#U[$i#U][SUPaperSUScissorsSUStone][CaSUb\SUc"SUd\"SUe"[SUf\"[SUg[\SUh[\"]]} +>> \ No newline at end of file diff --git a/Ext/Toolboxes/jsonlab/examples/jsonlab_speedtest.m b/Ext/Toolboxes/jsonlab/examples/jsonlab_speedtest.m new file mode 100644 index 00000000..4990fba0 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/examples/jsonlab_speedtest.m @@ -0,0 +1,21 @@ +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Benchmarking processing speed of savejson and loadjson +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +datalen=[1e3 1e4 1e5 1e6]; +len=length(datalen); +tsave=zeros(len,1); +tload=zeros(len,1); +for i=1:len + tic; + json=savejson('data',struct('d1',rand(datalen(i),3),'d2',rand(datalen(i),3)>0.5)); + tsave(i)=toc; + data=loadjson(json); + tload(i)=toc-tsave(i); + fprintf(1,'matrix size: %d\n',datalen(i)); +end + +loglog(datalen,tsave,'o-',datalen,tload,'r*-'); +legend('savejson runtime (s)','loadjson runtime (s)'); +xlabel('array size'); +ylabel('running time (s)'); diff --git a/Ext/Toolboxes/jsonlab/jsonopt.m b/Ext/Toolboxes/jsonlab/jsonopt.m new file mode 100644 index 00000000..fd970eb0 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/jsonopt.m @@ -0,0 +1,35 @@ +function val=jsonopt(key,default,varargin) +% +% val=jsonopt(key,default,optstruct) +% +% setting options based on a struct. The struct can be produced +% by varargin2struct from a list of 'param','value' pairs +% +% authors:Qianqian Fang (q.fang neu.edu) +% +% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $ +% +% input: +% key: a string with which one look up a value from a struct +% default: if the key does not exist, return default +% optstruct: a struct where each sub-field is a key +% +% output: +% val: if key exists, val=optstruct.key; otherwise val=default +% +% license: +% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details +% +% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) +% + +val=default; +if(nargin<=2) return; end +opt=varargin{1}; +if(isstruct(opt)) + if(isfield(opt,key)) + val=getfield(opt,key); + elseif(isfield(opt,lower(key))) + val=getfield(opt,lower(key)); + end +end diff --git a/Ext/Toolboxes/jsonlab/loadjson.m b/Ext/Toolboxes/jsonlab/loadjson.m new file mode 100644 index 00000000..f9b28eb0 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/loadjson.m @@ -0,0 +1,504 @@ +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 (q.fang neu.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$ +% +% 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 or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details +% +% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) +% + +global pos index_esc isoct arraytoken + +if(regexp(fname,'^\s*(?:\[.*\])|(?:\{.*\})\s*$','once')) + string=fname; +elseif(exist(fname,'file')) + try + string = fileread(fname); + catch + try + string = urlread(['file://',fname]); + catch + string = urlread(['file://',fullfile(pwd,fname)]); + end + end +else + error('input file does not exist'); +end + +pos = 1; len = length(string); inStr = string; +isoct=exist('OCTAVE_VERSION','builtin'); +arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); +jstr=regexprep(inStr,'\\\\',' '); +escquote=regexp(jstr,'\\"'); +arraytoken=sort([arraytoken escquote]); + +% String delimiters and escape chars identified to improve speed: +esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); +index_esc = 1; + +opt=varargin2struct_jsonlab(varargin{:}); + +if(jsonopt('ShowProgress',0,opt)==1) + opt.progressbar_=waitbar(0,'loading ...'); +end +jsoncount=1; +while pos <= len + switch(next_char(inStr)) + case '{' + data{jsoncount} = parse_object(inStr, esc, opt); + case '[' + data{jsoncount} = parse_array(inStr, esc, opt); + otherwise + error_pos('Outer level structure must be an object or an array',inStr); + end + jsoncount=jsoncount+1; +end % while + +jsoncount=length(data); +if(jsoncount==1 && iscell(data)) + data=data{1}; +end + +if(isfield(opt,'progressbar_')) + close(opt.progressbar_); +end + +%%------------------------------------------------------------------------- +function object = parse_object(inStr, esc, varargin) + parse_char(inStr, '{'); + object = []; + if next_char(inStr) ~= '}' + while 1 + str = parseStr(inStr, esc, varargin{:}); + if isempty(str) + error_pos('Name of value at position %d cannot be empty',inStr); + end + parse_char(inStr, ':'); + val = parse_value(inStr, esc, varargin{:}); + object.(valid_field(str))=val; + if next_char(inStr) == '}' + break; + end + parse_char(inStr, ','); + end + end + parse_char(inStr, '}'); + if(isstruct(object)) + object=struct2jdata(object); + end + +%%------------------------------------------------------------------------- + +function object = parse_array(inStr, esc, varargin) % JSON array is written in row-major order + global pos isoct + parse_char(inStr, '['); + object = cell(0, 1); + dim2=[]; + arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); + pbar=-1; + if(isfield(varargin{1},'progressbar_')) + pbar=varargin{1}.progressbar_; + end + + if next_char(inStr) ~= ']' + if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) + [endpos, e1l, e1r]=matching_bracket(inStr,pos); + arraystr=['[' inStr(pos:endpos)]; + arraystr=regexprep(arraystr,'"_NaN_"','NaN'); + arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); + arraystr(arraystr==sprintf('\n'))=[]; + arraystr(arraystr==sprintf('\r'))=[]; + %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed + if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D + astr=inStr((e1l+1):(e1r-1)); + astr=regexprep(astr,'"_NaN_"','NaN'); + astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); + astr(astr==sprintf('\n'))=[]; + astr(astr==sprintf('\r'))=[]; + astr(astr==' ')=''; + if(isempty(find(astr=='[', 1))) % array is 2D + dim2=length(sscanf(astr,'%f,',[1 inf])); + end + else % array is 1D + astr=arraystr(2:end-1); + astr(astr==' ')=''; + [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); + if(nextidx>=length(astr)-1) + object=obj; + pos=endpos; + parse_char(inStr, ']'); + return; + end + end + + try + if(~isempty(dim2)) + astr=arraystr; + astr(astr=='[')=''; + astr(astr==']')=''; + astr=regexprep(astr,'\s*$',''); + 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(inStr, ']'); + if(pbar>0) + waitbar(pos/length(inStr),pbar,'loading ...'); + end + return; + end + end + arraystr=regexprep(arraystr,'\]\s*,','];'); + catch + end + else + arraystr='['; + end + try + arraystr=regexprep(arraystr,'^\s*\[','{','once'); + arraystr=regexprep(arraystr,'\]\s*$','}','once'); + if(isoct && regexp(arraystr,'"','once')) + error('Octave eval can produce empty cells for JSON-like input'); + end + if(regexp(arraystr,':','once')) + error('One can not use MATLAB-like ":" construct inside a JSON array'); + end + object=eval(arraystr); + pos=endpos; + catch + while 1 + newopt=varargin2struct_jsonlab(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); + val = parse_value(inStr, esc, newopt); + object{end+1} = val; + if next_char(inStr) == ']' + break; + end + parse_char(inStr, ','); + end + end + end + if(jsonopt('SimplifyCell',0,varargin{:})==1) + try + oldobj=object; + object=cell2mat(object')'; + if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) + object=oldobj; + elseif(size(object,1)>1 && ismatrix(object)) + object=object'; + end + catch + end + end + parse_char(inStr, ']'); + + if(pbar>0) + waitbar(pos/length(inStr),pbar,'loading ...'); + end +%%------------------------------------------------------------------------- + +function parse_char(inStr, c) + global pos + pos=skip_whitespace(pos, inStr); + if pos > length(inStr) || inStr(pos) ~= c + error_pos(sprintf('Expected %c at position %%d', c),inStr); + else + pos = pos + 1; + pos=skip_whitespace(pos, inStr); + end + +%%------------------------------------------------------------------------- + +function c = next_char(inStr) + global pos + pos=skip_whitespace(pos, inStr); + if pos > length(inStr) + c = []; + else + c = inStr(pos); + end + +%%------------------------------------------------------------------------- + +function newpos=skip_whitespace(pos, inStr) + newpos=pos; + while newpos <= length(inStr) && isspace(inStr(newpos)) + newpos = newpos + 1; + end + +%%------------------------------------------------------------------------- +function str = parseStr(inStr, esc, varargin) + global pos index_esc + % len, ns = length(inStr), keyboard + if inStr(pos) ~= '"' + error_pos('String starting with " expected at position %d',inStr); + else + pos = pos + 1; + end + str = ''; + while pos <= length(inStr) + while index_esc <= length(esc) && esc(index_esc) < pos + index_esc = index_esc + 1; + end + if index_esc > length(esc) + str = [str inStr(pos:end)]; + pos = length(inStr) + 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 > length(inStr) + error_pos('End of file reached right after escape character',inStr); + 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 > length(inStr) + error_pos('End of file reached in escaped unicode character',inStr); + 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',inStr); + +%%------------------------------------------------------------------------- + +function num = parse_number(inStr, varargin) + global pos isoct + currstr=inStr(pos:min(pos+30,end)); + if(isoct~=0) + numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); + [num] = sscanf(currstr, '%f', 1); + delta=numstr+1; + else + [num, one, err, delta] = sscanf(currstr, '%f', 1); + if ~isempty(err) + error_pos('Error reading number at position %d',inStr); + end + end + pos = pos + delta-1; + +%%------------------------------------------------------------------------- + +function val = parse_value(inStr, esc, varargin) + global pos + len=length(inStr); + if(isfield(varargin{1},'progressbar_')) + waitbar(pos/len,varargin{1}.progressbar_,'loading ...'); + end + + switch(inStr(pos)) + case '"' + val = parseStr(inStr, esc, varargin{:}); + return; + case '[' + val = parse_array(inStr, esc, varargin{:}); + return; + case '{' + val = parse_object(inStr, esc, varargin{:}); + return; + case {'-','0','1','2','3','4','5','6','7','8','9'} + val = parse_number(inStr, 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',inStr); +%%------------------------------------------------------------------------- + +function error_pos(msg, inStr) + global pos 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)) '' 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(1)+0 > 255) + 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(pos1 && 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 + elseif(c=='[') + if(isempty(e1l)) + e1l=bpos(pos); + end + level=level+1; + maxlevel=max(maxlevel,level); + elseif(c=='"') + pos=matching_quote(tokens,pos+1); + end + pos=pos+1; +end +if(endpos==0) + error('unmatched "]"'); +end diff --git a/Ext/Toolboxes/jsonlab/loadubjson.m b/Ext/Toolboxes/jsonlab/loadubjson.m new file mode 100644 index 00000000..3418b02f --- /dev/null +++ b/Ext/Toolboxes/jsonlab/loadubjson.m @@ -0,0 +1,449 @@ +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 (q.fang neu.edu) +% created on 2013/08/01 +% +% $Id$ +% +% 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. +% opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or +% earlier versions (JSONLab 1.0 final or earlier), +% the "name" tag is treated as a string. To load +% these UBJSON data, you need to manually set this +% flag to 1. +% +% 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 or GPL version 3, see LICENSE_{BSD,GPLv3}.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_jsonlab(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 + +%%------------------------------------------------------------------------- +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 + if(jsonopt('NameIsString',0,varargin{:})) + str = parseStr(varargin{:}); + else + str = parse_name(varargin{:}); + end + if isempty(str) + error_pos('Name of value at position %d cannot be empty'); + end + %parse_char(':'); + val = parse_value(varargin{:}); + num=num+1; + object.(valid_field(str))=val; + if next_char == '}' || (count>=0 && num>=count) + break; + end + %parse_char(','); + end + end + if(count==-1) + parse_char('}'); + end + if(isstruct(object)) + object=struct2jdata(object); + 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); +newdata=uint8(datastr); +id=strfind('iUIlLdD',type); +if(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 + 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 && ismatrix(object)) + 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 = parse_name(varargin) + global pos inStr + 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 name'); + end +%%------------------------------------------------------------------------- + +function str = parseStr(varargin) + global pos inStr + % 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 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)); + newdata=uint8(datastr); + if(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 + + switch(inStr(pos)) + case {'S','C','H'} + val = parseStr(varargin{:}); + return; + case '[' + val = parse_array(varargin{:}); + return; + case '{' + val = parse_object(varargin{:}); + 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)) '' 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(pos1 && 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 + diff --git a/Ext/Toolboxes/jsonlab/mergestruct.m b/Ext/Toolboxes/jsonlab/mergestruct.m new file mode 100644 index 00000000..afc82712 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/mergestruct.m @@ -0,0 +1,33 @@ +function s=mergestruct(s1,s2) +% +% s=mergestruct(s1,s2) +% +% merge two struct objects into one +% +% authors:Qianqian Fang (q.fang neu.edu) +% date: 2012/12/22 +% +% input: +% s1,s2: a struct object, s1 and s2 can not be arrays +% +% output: +% s: the merged struct object. fields in s1 and s2 will be combined in s. +% +% license: +% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details +% +% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) +% + +if(~isstruct(s1) || ~isstruct(s2)) + error('input parameters contain non-struct'); +end +if(length(s1)>1 || length(s2)>1) + error('can not merge struct arrays'); +end +fn=fieldnames(s2); +s=s1; +for i=1:length(fn) + s=setfield(s,fn{i},getfield(s2,fn{i})); +end + diff --git a/Ext/Toolboxes/jsonlab/package.json b/Ext/Toolboxes/jsonlab/package.json new file mode 100644 index 00000000..3604355a --- /dev/null +++ b/Ext/Toolboxes/jsonlab/package.json @@ -0,0 +1,21 @@ +{ + "name": "jsonlab", + "version": "1.5.0", + "description": "An open-source MATLAB/Octave JSON encoder and decoder", + "directories": { + "example": "examples" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/fangq/jsonlab.git" + }, + "author": "Qianqian Fang ", + "license": "GPL-3.0", + "bugs": { + "url": "https://github.com/fangq/jsonlab/issues" + }, + "homepage": "https://github.com/fangq/jsonlab#readme" +} diff --git a/Ext/Toolboxes/jsonlab/savejson.m b/Ext/Toolboxes/jsonlab/savejson.m new file mode 100644 index 00000000..7b589285 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/savejson.m @@ -0,0 +1,593 @@ +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 (q.fang neu.edu) +% created on 2011/09/09 +% +% $Id$ +% +% 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, +% class instance). +% 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.SingletArray [0|1]: 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.SingletCell [1|0]: if 1, always enclose a cell with "[]" +% even it has only one element; if 0, brackets +% are ignored when a cell has only 1 element. +% 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 or GPL version 3, see LICENSE_{BSD,GPLv3}.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_jsonlab(varargin{:}); +end +opt.IsOctave=exist('OCTAVE_VERSION','builtin'); +if(isfield(opt,'norowbracket')) + warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)'); + if(~isfield(opt,'singletarray')) + opt.singletarray=not(opt.norowbracket); + end +end +rootisarray=0; +rootlevel=1; +forceroot=jsonopt('ForceRootName',0,opt); +if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ... + iscell(obj) || isobject(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 +filename=jsonopt('FileName','',opt); +if(~isempty(filename)) + if(jsonopt('SaveBinary',0,opt)==1) + fid = fopen(filename, 'wb'); + fwrite(fid,json); + else + fid = fopen(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{:}); +elseif(isa(item,'string')) + txt=str2json(name,item{:},level,varargin{:}); +elseif(isobject(item)) + if(~exist('OCTAVE_VERSION','builtin') && istable(item)) + txt=matlabtable2json(name,item,level,varargin{:}); + else + txt=matlabobject2json(name,item,level,varargin{:}); + end +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; +bracketlevel=~jsonopt('singletcell',1,varargin{:}); +if(len>bracketlevel) + if(~isempty(name)) + txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name=''; + else + txt={padding0, '[', nl}; + end +elseif(len==0) + if(~isempty(name)) + txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name=''; + else + txt={padding0, '[]'}; + end +end +for i=1:dim(1) + if(dim(1)>1) + txt(end+1:end+3)={padding2,'[',nl}; + end + for j=1:dim(2) + txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:}); + if(j1) + txt(end+1:end+3)={nl,padding2,']'}; + end + if(ibracketlevel) + txt(end+1:end+3)={nl,padding0,']'}; +end +txt = sprintf('%s',txt{:}); + +%%------------------------------------------------------------------------- +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); +forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0)); +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)+forcearray); +nl=ws.newline; + +if(isempty(item)) + if(~isempty(name)) + txt={padding0, '"', checkname(name,varargin{:}),'": []'}; + else + txt={padding0, '[]'}; + end + txt = sprintf('%s',txt{:}); + return; +end +if(~isempty(name)) + if(forcearray) + txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; + end +else + if(forcearray) + txt={padding0, '[', nl}; + end +end +for j=1:dim(2) + if(dim(1)>1) + txt(end+1:end+3)={padding2,'[',nl}; + end + for i=1:dim(1) + names = fieldnames(item(i,j)); + if(~isempty(name) && len==1 && ~forcearray) + txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl}; + else + txt(end+1:end+3)={padding1, '{', nl}; + end + if(~isempty(names)) + for e=1:length(names) + txt{end+1}=obj2json(names{e},item(i,j).(names{e}),... + level+(dim(1)>1)+1+forcearray,varargin{:}); + if(e1) + txt(end+1:end+3)={nl,padding2,']'}; + end + if(j1) + txt={padding1, '"', checkname(name,varargin{:}),'": [', nl}; + end +else + if(len>1) + txt={padding1, '[', nl}; + end +end +for e=1:len + val=escapejsonstring(item(e,:)); + if(len==1) + obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; + if(isempty(name)) + obj=['"',val,'"']; + end + txt(end+1:end+2)={padding1, obj}; + else + txt(end+1:end+4)={padding0,'"',val,'"'}; + end + if(e==len) + sep=''; + end + txt{end+1}=sep; +end +if(len>1) + txt(end+1:end+3)={nl,padding1,']'}; +end +txt = sprintf('%s',txt{:}); + +%%------------------------------------------------------------------------- +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) && any(size(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('SingletArray',0,varargin{:})==0 && 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('SingletArray',0,varargin{:})==0) + 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=matlabobject2json(name,item,level,varargin) +if numel(item) == 0 %empty object + st = struct(); +elseif numel(item) == 1 % + st = struct(); + txt = str2json(name, char(item), level, varargin(:)); + return +else + % "st = struct(item);" would produce an inmutable warning, because it + % make the protected and private properties visible. Instead we get the + % visible properties + propertynames = properties(item); + for p = 1:numel(propertynames) + for o = numel(item):-1:1 % aray of objects + st(o).(propertynames{p}) = item(o).(propertynames{p}); + end + end +end +txt=struct2json(name,st,level,varargin{:}); + +%%------------------------------------------------------------------------- +function txt=matlabtable2json(name,item,level,varargin) +if numel(item) == 0 %empty object + st = struct(); +else + % "st = struct(item);" would produce an inmutable warning, because it + % make the protected and private properties visible. Instead we get the + % visible properties + st = struct(); + propertynames = properties(item); + if(isfield(item.Properties,'RowNames') && ~isempty(item.Properties.RowNames)) + rownames=item.Properties.RowNames; + for p = 1:(numel(propertynames)-1) + for j = 1:size(item(:,p),1) + st.(rownames{j}).(propertynames{p}) = item{j,p}; + end + end + else + for p = 1:(numel(propertynames)-1) + for j = 1:size(item(:,p),1) + st(j).(propertynames{p}) = item{j,p}; + end + end + end +end +txt=struct2json(name,st,level,varargin{:}); + +%%------------------------------------------------------------------------- +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 +if(isinteger(mat)) + floatformat=jsonopt('FloatFormat','%d',varargin{:}); +else + floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); +end +%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 + newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1'); +else + escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'}; + for i=1:length(escapechars); + newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); + end + newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1'); +end diff --git a/Ext/Toolboxes/jsonlab/saveubjson.m b/Ext/Toolboxes/jsonlab/saveubjson.m new file mode 100644 index 00000000..7acaa8ad --- /dev/null +++ b/Ext/Toolboxes/jsonlab/saveubjson.m @@ -0,0 +1,561 @@ +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 (q.fang neu.edu) +% created on 2013/08/17 +% +% $Id$ +% +% 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, +% class instance) +% 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.SingletArray [0|1]: 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.SingletCell [1|0]: if 1, always enclose a cell with "[]" +% even it has only one element; if 0, brackets +% are ignored when a cell has only 1 element. +% 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 or GPL version 3, see LICENSE_{BSD,GPLv3}.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_jsonlab(varargin{:}); +end +opt.IsOctave=exist('OCTAVE_VERSION','builtin'); +if(isfield(opt,'norowbracket')) + warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)'); + if(~isfield(opt,'singletarray')) + opt.singletarray=not(opt.norowbracket); + end +end +rootisarray=0; +rootlevel=1; +forceroot=jsonopt('ForceRootName',0,opt); +if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ... + iscell(obj) || isobject(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 +filename=jsonopt('FileName','',opt); +if(~isempty(filename)) + fid = fopen(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{:}); +elseif(isobject(item)) + txt=matlabobject2ubjson(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 +bracketlevel=~jsonopt('singletcell',1,varargin{:}); +len=numel(item); % let's handle 1D cell first +if(len>bracketlevel) + if(~isempty(name)) + txt=[N_(checkname(name,varargin{:})) '[']; name=''; + else + txt='['; + end +elseif(len==0) + if(~isempty(name)) + txt=[N_(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>bracketlevel),varargin{:})]; + end + if(dim(1)>1) + txt=[txt ']']; + end +end +if(len>bracketlevel) + 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); +forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0)); + +if(~isempty(name)) + if(forcearray) + txt=[N_(checkname(name,varargin{:})) '[']; + end +else + if(forcearray) + 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 && ~forcearray) + txt=[txt N_(checkname(name,varargin{:})) '{']; + else + txt=[txt '{']; + end + if(~isempty(names)) + for e=1:length(names) + txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),... + level+(dim(1)>1)+1+forcearray,varargin{:})]; + end + end + txt=[txt '}']; + end + if(dim(1)>1) + txt=[txt ']']; + end +end +if(forcearray) + 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=[N_(checkname(name,varargin{:})) '[']; + end +else + if(len>1) + txt='['; + end +end +for e=1:len + val=item(e,:); + if(len==1) + obj=[N_(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) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:})) + cid=I_(uint32(max(size(item)))); + if(isempty(name)) + txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ]; + else + if(isempty(item)) + txt=[N_(checkname(name,varargin{:})),'Z']; + return; + else + txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_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('SingletArray',0,varargin{:})==0) + numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); + txt=[N_(checkname(name,varargin{:})) numtxt]; + else + txt=[N_(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,N_('_ArrayIsComplex_'),'T']; + end + txt=[txt,N_('_ArrayIsSparse_'),'T']; + if(size(item,1)==1) + % Row vector, store only column indices. + txt=[txt,N_('_ArrayData_'),... + matdata2ubjson([iy(:),data'],level+2,varargin{:})]; + elseif(size(item,2)==1) + % Column vector, store only row indices. + txt=[txt,N_('_ArrayData_'),... + matdata2ubjson([ix,data],level+2,varargin{:})]; + else + % General case, store row and column indices. + txt=[txt,N_('_ArrayData_'),... + matdata2ubjson([ix,iy,data],level+2,varargin{:})]; + end +else + if(isreal(item)) + txt=[txt,N_('_ArrayData_'),... + matdata2ubjson(item(:)',level+2,varargin{:})]; + else + txt=[txt,N_('_ArrayIsComplex_'),'T']; + txt=[txt,N_('_ArrayData_'),... + matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; + end +end +txt=[txt,'}']; + +%%------------------------------------------------------------------------- +function txt=matlabobject2ubjson(name,item,level,varargin) +st = struct(); +if numel(item) > 0 %non-empty object + % "st = struct(item);" would produce an inmutable warning, because it + % make the protected and private properties visible. Instead we get the + % visible properties + propertynames = properties(item); + for p = 1:numel(propertynames) + for o = numel(item):-1:1 % aray of objects + st(o).(propertynames{p}) = item(o).(propertynames{p}); + end + end +end +txt=struct2ubjson(name,st,level,varargin{:}); + +%%------------------------------------------------------------------------- +function txt=matdata2ubjson(mat,level,varargin) +if(isempty(mat)) + txt='Z'; + return; +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(id~=0)) + error('high-precision data is not yet supported'); + end + key='iIlL'; + type=key(id~=0); + 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=N_(str) +val=[I_(int32(length(str))) str]; +%%------------------------------------------------------------------------- +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(swapbytes(num),'uint8')]; +else + val=['D' data2byte(swapbytes(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(swapbytes(single(num)),'uint8'); +elseif(id==2) + data=data2byte(swapbytes(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=char(bytes(:)'); diff --git a/Ext/Toolboxes/jsonlab/struct2jdata.m b/Ext/Toolboxes/jsonlab/struct2jdata.m new file mode 100644 index 00000000..28a5faae --- /dev/null +++ b/Ext/Toolboxes/jsonlab/struct2jdata.m @@ -0,0 +1,96 @@ +function newdata=struct2jdata(data,varargin) +% +% newdata=struct2jdata(data,opt,...) +% +% convert a JData object (in the form of a struct array) into an array +% +% authors:Qianqian Fang (q.fang neu.edu) +% +% input: +% data: a struct array. If data contains JData keywords in the first +% level children, these fields are parsed and regrouped into a +% data object (arrays, trees, graphs etc) based on JData +% specification. The JData keywords are +% "_ArrayType_", "_ArraySize_", "_ArrayData_" +% "_ArrayIsSparse_", "_ArrayIsComplex_" +% opt: (optional) a list of 'Param',value pairs for additional options +% The supported options include +% 'Recursive', if set to 1, will apply the conversion to +% every child; 0 to disable +% +% output: +% newdata: the covnerted data if the input data does contain a JData +% structure; otherwise, the same as the input. +% +% examples: +% obj=struct('_ArrayType_','double','_ArraySize_',[2 3], +% '_ArrayIsSparse_',1 ,'_ArrayData_',null); +% ubjdata=struct2jdata(obj); +% +% license: +% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details +% +% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) +% + +fn=fieldnames(data); +newdata=data; +len=length(data); +if(jsonopt('Recursive',0,varargin{:})==1) + for i=1:length(fn) % depth-first + for j=1:len + if(isstruct(getfield(data(j),fn{i}))) + newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); + end + end + end +end +if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) + newdata=cell(len,1); + for j=1:len + ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); + iscpx=0; + if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) + if(data(j).x0x5F_ArrayIsComplex_) + iscpx=1; + end + end + if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) + if(data(j).x0x5F_ArrayIsSparse_) + if(~isempty(strmatch('x0x5F_ArraySize_',fn))) + dim=double(data(j).x0x5F_ArraySize_); + if(iscpx && size(ndata,2)==4-any(dim==1)) + ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); + end + if isempty(ndata) + % All-zeros sparse + ndata=sparse(dim(1),prod(dim(2:end))); + elseif dim(1)==1 + % Sparse row vector + ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); + elseif dim(2)==1 + % Sparse column vector + ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); + else + % Generic sparse array. + ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); + end + else + if(iscpx && size(ndata,2)==4) + ndata(:,3)=complex(ndata(:,3),ndata(:,4)); + end + ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); + end + end + elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) + if(iscpx && size(ndata,2)==2) + ndata=complex(ndata(:,1),ndata(:,2)); + end + ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); + end + newdata{j}=ndata; + end + if(len==1) + newdata=newdata{1}; + end +end \ No newline at end of file diff --git a/Ext/Toolboxes/jsonlab/varargin2struct_jsonlab.m b/Ext/Toolboxes/jsonlab/varargin2struct_jsonlab.m new file mode 100644 index 00000000..d5355de4 --- /dev/null +++ b/Ext/Toolboxes/jsonlab/varargin2struct_jsonlab.m @@ -0,0 +1,40 @@ +function opt=varargin2struct(varargin) +% +% opt=varargin2struct('param1',value1,'param2',value2,...) +% or +% opt=varargin2struct(...,optstruct,...) +% +% convert a series of input parameters into a structure +% +% authors:Qianqian Fang (q.fang neu.edu) +% date: 2012/12/22 +% +% input: +% 'param', value: the input parameters should be pairs of a string and a value +% optstruct: if a parameter is a struct, the fields will be merged to the output struct +% +% output: +% opt: a struct where opt.param1=value1, opt.param2=value2 ... +% +% license: +% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details +% +% -- this function is part of jsonlab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab) +% + +len=length(varargin); +opt=struct; +if(len==0) return; end +i=1; +while(i<=len) + if(isstruct(varargin{i})) + opt=mergestruct(opt,varargin{i}); + elseif(ischar(varargin{i}) && i=0) = 0; - + % idx pos and neg num_vals_pos = sum(vals_pos>=0&vals_neg==0,1); num_vals_neg = sum(vals_neg<0,1); idx_pos = num_vals_pos >0; - idx_neg = num_vals_neg >0; + idx_neg = num_vals_neg >0; + + if any(idx_pos) + this.data.pos_pts.idx= all_pts(idx_pos); + this.data.pos_pts.idx_traj = this.BrSet.P.traj_ref(this.data.pos_pts.idx); + this.data.pos_pts.v_sum_pos = sum(vals_pos(:,idx_pos),1); + this.data.pos_pts.v_num_pos = num_vals_pos(idx_pos); + end - % Attempt to pick the most interesting plot + if any(idx_neg) + this.data.neg_pts.idx= all_pts(idx_neg); + this.data.neg_pts.idx_traj = this.BrSet.P.traj_ref(this.data.neg_pts.idx); + this.data.neg_pts.v_sum_neg = sum(vals_neg(:, idx_neg),1); + this.data.neg_pts.v_num_neg = -num_vals_neg(idx_neg); + end + + end + + function update_plot(this) - if size(vals_pos,1)==1|| (all(idx_pos)&&(~any(idx_neg))) ||(all(idx_neg)&&(~any(idx_pos)) ) % only one requirement or all positive or all negative - plot_sum(); + this.update_data(); + + if isa(this.BrSet, 'BreachRequirement') + B = this.BrSet.BrSet; + else + B = this.BrSet; + end + + figure(this.Fig); + if isempty(this.ax) + this.ax = axes(); else - plot_num(); + axes(this.ax) end + cla; + grid on; + + has_pos = isfield(this.data, 'pos_pts'); + has_neg = isfield(this.data, 'neg_pts'); + if has_pos + pos_idx = this.data.pos_pts.idx; + switch this.x_axis + case 'idx' + xdata_pos = pos_idx; + otherwise % assumes x_axis is a parameter name + xdata_pos = B.GetParam(this.x_axis, pos_idx); + end - function plot_sum() - if any(idx_pos) - y_pos = sum(vals_pos(:,idx_pos),1); - plot(all_pts(idx_pos),y_pos,'.g', 'MarkerSize', 20); + switch this.y_axis + case 'auto' + if ~isa(this.BrSet,'BreachRequirement')||(isa(this.BrSet,'BreachRequirement')&&numel(this.BrSet.req_monitors)==1)||... + has_neg&&~has_pos||... + has_pos&&~has_neg + ydata_pos = this.data.pos_pts.v_sum_pos; + plot_this = @plot_sum; + else + ydata_pos = this.data.neg_pts.v_num_neg; + plot_this = @plot_num; + end + + case 'sum' + ydata_pos = this.data.pos_pts.v_sum_pos; + plot_this = @plot_sum; + case 'num' + ydata_pos = this.data.pos_pts.v_num_pos; + plot_this = @plot_num; + otherwise + ydata_pos = B.GetParam(this.y_axis, pos_idx); + plot_this = @plot_param; + end + end + + if has_neg + neg_idx = this.data.neg_pts.idx; + + switch this.x_axis + case 'idx' + xdata_neg = neg_idx; + otherwise % assumes parameter name + xdata_neg = B.GetParam(this.x_axis, neg_idx); end + switch this.y_axis + case 'auto' + if ~isa(this.BrSet,'BreachRequirement')||(isa(this.BrSet,'BreachRequirement')&&numel(this.BrSet.req_monitors)==1)||... + has_neg&&~has_pos||... + has_pos&&~has_neg + ydata_neg = this.data.neg_pts.v_sum_neg; + plot_this = @plot_sum; + else + ydata_neg = this.data.neg_pts.v_num_neg; + plot_this=@plot_num; + end + case 'sum' + ydata_neg = this.data.neg_pts.v_sum_neg; + plot_this = @plot_sum; + case 'num' + ydata_neg = this.data.neg_pts.v_num_neg; + plot_this = @plot_num; + otherwise + ydata_neg = B.GetParam(this.y_axis, neg_idx); + plot_this = @plot_param; + end + end + + plot_this(); + + function plot_param() + if has_pos + this.pos_plot = plot(xdata_pos,ydata_pos,'.g', 'MarkerSize', 20); + end hold on; - if any(idx_neg) - y_neg = sum(vals_neg(:, idx_neg),1); - plot(all_pts(idx_neg),y_neg,'.r', 'MarkerSize', 20); + if has_neg + this.neg_plot = plot(xdata_neg,ydata_neg,'.r', 'MarkerSize', 20); end grid on; - xlabel('idx trace'); - set(gca, 'Xtick', []); + xlabel(this.x_axis, 'Interpreter', 'None'); + ylabel(this.y_axis, 'Interpreter', 'None'); + end + + function plot_sum() + if has_pos + this.pos_plot = plot(xdata_pos,ydata_pos,'.g', 'MarkerSize', 20); + end + hold on; + if has_neg + this.neg_plot = plot(xdata_neg,ydata_neg,'.r', 'MarkerSize', 20); + end + grid on; + xlabel(this.x_axis, 'Interpreter', 'None'); ylabel('Cumulative satisfactions/violations'); end function plot_num() - if any(idx_pos) - y_pos = num_vals_pos(idx_pos); - bar(all_pts(idx_pos), y_pos ,0.1,'g'); + if has_pos + ydata_pos = this.data.pos_pts.v_num_pos; + this.pos_plot = bar(xdata_pos, ydata_pos ,0.5,'g'); end hold on; - if any(idx_neg) - y_neg = -num_vals_neg(idx_neg); - bar(all_pts(idx_neg),y_neg,0.1,'r'); - end grid on; - xlabel('idx trace'); + if has_neg + ydata_neg = this.data.neg_pts.v_num_neg; + this.neg_plot = bar(xdata_neg, ydata_neg ,0.5,'r'); + set(gca, 'YLim', [min(ydata_neg)-.1, max(ydata_pos)+.1], 'Ytick', ceil(min(ydata_neg)-.1):1:floor(max(ydata_pos)+.1)); + end + xlabel(this.x_axis, 'Interpreter', 'None'); ylabel('Num. requirement falsified/satisfied'); - set(gca, 'YLim', [min(y_neg)-.1, max(y_pos)+.1], 'Ytick', [ceil(min(y_neg)-.1):1:floor(max(y_pos)+.1)]); end - h = title('Left click on data to get details, right click to plot signals/diagnosis', 'FontWeight', 'normal', 'FontSize', 10); - + h = title('Left click on data to get details, right click to plot signals', 'FontWeight', 'normal', 'FontSize', 10); + %% Datacursor mode customization cursor_h = datacursormode(this.Fig); @@ -109,26 +238,34 @@ function plot_num() cursor_h.SnapToDataVertex = 'on'; datacursormode on - function [txt] = myupdatefcn(obj,event_obj) pos = event_obj.Position; - ipts = pos(1); - val = pos(2); - this.idx_tipped = ipts; - - txt{1} = ['idx trace:' num2str(ipts)] ; + ipos = find(event_obj.Target.XData==pos(1)&event_obj.Target.YData==pos(2),1); + if isequal(this.neg_plot, event_obj.Target) + i_pts_req = neg_idx(ipos); + elseif isequal(this.pos_plot, event_obj.Target) + i_pts_req = pos_idx(ipos); + end + + this.idx_tipped = i_pts_req; - for irr = 1:numel(this.summary.requirements.names) - if (this.summary.requirements.rob(ipts, irr)*val>0||(this.summary.requirements.rob(ipts, irr) ==0&&val>=0)) - txt{end+1} = [this.summary.requirements.names{irr} ':' num2str(this.summary.requirements.rob(ipts, irr))]; + if isa(this.BrSet,'BreachRequirement') + data_trace_idx_ = this.BrSet.GetParam('data_trace_idx_',i_pts_req); + txt{1} = ['req_val_idx_:' num2str(i_pts_req)] ; + txt{2} = ['data_trace_idx_:' num2str(data_trace_idx_)] ; + txt{3} = '--------------'; + for irr = 1:numel(this.summary.requirements.names) + txt{end+1} = [this.summary.requirements.names{irr} ':' num2str(this.summary.requirements.rob(i_pts_req, irr))]; end + else + txt{1} = ['Sample idx:' num2str(i_pts_req)] ; end - - if isfield(this.summary.signature, 'variables_idx') + + if isfield(this.signature, 'variables_idx') txt{end+1} = '--------------'; - for irr = 1:numel(this.summary.signature.variables_idx) - var_name = this.summary.signature.params{this.summary.signature.variables_idx(irr)}; - var_value = this.BrSet.GetParam(var_name, ipts); + for irr = 1:numel(this.signature.variables_idx) + var_name = this.signature.params{this.signature.variables_idx(irr)}; + var_value =B.GetParam(var_name, i_pts_req); txt{end+1} = [var_name ': ' num2str(var_value)]; end end @@ -137,11 +274,27 @@ function plot_num() %% Context menu cm = uicontextmenu; uimenu(cm, 'Label', 'Open signals plot','Callback', @ctxtfn_signals_plot) - top = uimenu(cm, 'Label', ['Plot diagnosis']); - for ir = 1:numel(this.summary.requirements.names) - uimenu(top,'Label', this.summary.requirements.names{ir},'Callback', @(o,e)ctxtfn_plot_diagnosis(ir, o, e)); - end + if isa(this.BrSet, 'BreachRequirement') + top_diag = uimenu(cm, 'Label', ['Plot diagnosis']); + for ir = 1:numel(this.summary.requirements.names) + uimenu(top_diag,'Label', this.summary.requirements.names{ir},'Callback', @(o,e)ctxtfn_plot_diagnosis(ir, o, e)); + end + end + top_x = uimenu(cm, 'Label', ['Change x-axis']); + uimenu(top_x, 'Label', 'idx','Callback',@(o,e)(this.set_x_axis('idx'))); + for ip = 1:numel(this.data.variables) + uimenu(top_x, 'Label', this.data.variables{ip},'Callback',@(o,e)(this.set_x_axis(this.data.variables{ip}))); + end + + top_y = uimenu(cm, 'Label', ['Change y-axis']); + uimenu(top_y, 'Label', 'auto','Callback',@(o,e)(this.set_y_axis('auto'))); + uimenu(top_y, 'Label', 'sum','Callback',@(o,e)(this.set_y_axis('sum'))); + uimenu(top_y, 'Label', 'num','Callback',@(o,e)(this.set_y_axis('num'))); + for ip = 1:numel(this.data.variables) + uimenu(top_y, 'Label', this.data.variables{ip},'Callback',@(o,e)(this.set_y_axis(this.data.variables{ip}))); + end + set(cursor_h, 'UIContextMenu', cm); function ctxtfn_plot_diagnosis(ir, o,e) @@ -160,11 +313,38 @@ function ctxtfn_signals_plot(o,e) else it = this.idx_tipped(1); end - F = BreachSignalsPlot(this.BrSet,this.BrSet.P.ParamList{1}, it); + sig = this.signature.signals{1}; + F = BreachSignalsPlot(this.BrSet,sig, it); set(F.Fig,'Name', ['Trace idx= ' num2str(it)]); end end + + function set_x_axis(this, param) + current_axis = this.x_axis; + try + this.x_axis = param; + cla(this.ax,'reset'); + this.update_plot(); + catch ME + warning('BreachSamplesPlot:set_axis_fail', 'set_x_axis failed with error %s', ME.message ); + this.set_x_axis(current_axis) + end + end + + function set_y_axis(this, param) + current_axis = this.y_axis; + try + this.y_axis = param; + cla(this.ax,'reset'); + this.update_plot(); + catch ME + warning('BreachSamplesPlot:set_axis_fail', 'set_y_axis failed with error %s', ME.message ); + this.set_y_axis(current_axis) + end + + end + end end diff --git a/Plots/BreachSignalsPlot.m b/Plots/BreachSignalsPlot.m index b00495e6..a8189953 100644 --- a/Plots/BreachSignalsPlot.m +++ b/Plots/BreachSignalsPlot.m @@ -4,26 +4,26 @@ BrSet Fig Axes - itraj + ipts end methods - function this = BreachSignalsPlot(BrSet, signals, itraj) + function this = BreachSignalsPlot(BrSet, signals, ipts) switch nargin case 0 return; case 1 signals = BrSet.P.ParamList{1}; - itraj = 1; + ipts = 1; case 2 - itraj = 1; + ipts = 1; end this.BrSet = BrSet; this.Fig = figure; - this.itraj = itraj; + this.ipts = ipts; if exist('signals','var') if ischar(signals) @@ -92,7 +92,7 @@ % signals by attributes try - signature = this.BrSet.P.traj{this.itraj}.signature; + signature = this.BrSet.P.traj{this.ipts}.signature; catch signature = this.BrSet.GetSignature(); end @@ -241,7 +241,7 @@ function AddSignals(this,sigs, ax) axes(ax); hold on; - traj = this.BrSet.P.traj{this.itraj}; + traj = this.BrSet.P.traj{this.ipts}; idx = FindParam(this.BrSet.P, sig); tau = traj.time; val = traj.X(idx,:); @@ -287,8 +287,9 @@ function update_legend(this, ax) function plot_signal(this, sig, ax) axes(ax); hold on; - time = this.BrSet.P.traj{this.itraj}.time; - sig_values = this.BrSet.GetSignalValues(sig, this.itraj); + itraj = this.BrSet.P.traj_ref(this.ipts); + time = this.BrSet.P.traj{itraj}.time; + sig_values = this.BrSet.GetSignalValues(sig, itraj); if ~isempty(sig_values) l = plot(time , sig_values, 'DisplayName', sig); end diff --git a/VERSION b/VERSION index 31e5c843..88c5fb89 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.3.3 +1.4.0