diff --git a/docs/matlab_scripts/ppg/1-2-3_signal_quality.m b/docs/matlab_scripts/ppg/1-2-3_signal_quality.m deleted file mode 100644 index 0657cf99..00000000 --- a/docs/matlab_scripts/ppg/1-2-3_signal_quality.m +++ /dev/null @@ -1,379 +0,0 @@ -%% Main script to perform signal quality assessment of wearable PPG -% This script uses both PPG and accelerometer and performs the following -% steps: -% 1. Loading all metadata of PPG and IMU - get all metafiles and find pairs and do pairwise synchronization -% 2. Query on data availability + synchronization -% 3. Loading relevant segment sensor data using tsdf wrapper (start for loop over synchronized segment indices) -% 4. Synchronize the data (correct indices etc) -% 5. Data preprocessing -% 6. Feature extraction -% 7. Classification - combine after this - - -% Architecture overview -% The script implements the following steps: -% 1. IMU and PPG preprocessing -% 2. IMU and PPG feature extraction -% 3. Signal quality assessment - -%% Initalization -% Setting data paths + extracting metafilenames already -clearvars; close all; clc -addpath(genpath('..\..\..\paradigma-toolbox')) % Add git repository to the path -addpath(genpath("..\..\..\tsdf4matlab")) % Add wrapper to the path - -unix_ticks_ms = 1000.0; -fs_ppg = 30; % Establish the sampling rate desired for resampling PPG --> now chosen to be fixed on 30 Hz -fs_imu = 100; % Establish the sampling rate desired for resampling IMU --> now chosen to be fixed on 30 Hz - -raw_data_root = '..\..\..\tests\data\1.prepared_data\'; -ppp_data_path_ppg = [raw_data_root 'PPG\']; -ppp_data_path_imu = [raw_data_root 'IMU\']; - -%% 1. Loading all metadata of PPG and IMU -meta_ppg = tsdf_scan_meta(ppp_data_path_ppg); % tsdf_scan_meta returns metafile struct containing information of all metafiles from all patients in tsdf_dirlist -meta_imu = tsdf_scan_meta(ppp_data_path_imu); - -%% 2. Query on data availability + synchronization -[segment_ppg, segment_imu] = synchronization(meta_ppg, meta_imu); % PPG segment and IMU segment indices corresponding to eachother (where there is overlapping data) -% NOT NEEDED FOR TEST DATA BUT SHOULD BE FUNCTIONALITY IN THE TOOLBOX - -%% 3. Loading relevant segment sensor data using tsdf wrapper --> TO BE ADJUSTED -%%--------Load PPG + IMU data-------%% -n_files_sync = length(segment_ppg); % For test data this is 1 for final application it can be anything and it requires looping through the script - -% for n = 1:n_files_sync --> if there are more segments!! -% end - -n = 1; -meta_path_ppg = meta_ppg(segment_ppg(n)).tsdf_meta_fullpath; -meta_path_imu = meta_imu(segment_imu(n)).tsdf_meta_fullpath; - -[metadata_list_ppg, data_list_ppg] = load_tsdf_metadata_from_path(meta_path_ppg); -[metadata_list_imu, data_list_imu] = load_tsdf_metadata_from_path(meta_path_imu); - -time_idx_ppg = tsdf_values_idx(metadata_list_ppg, 'time'); % added for correctness instead of assuming that the idx is the same for every time we use load_tsdf_metadata_from_path --> or is this unnecessary --> assumption it is different for PPG and IMU!! -time_idx_imu = tsdf_values_idx(metadata_list_imu, 'time'); -values_idx_ppg = tsdf_values_idx(metadata_list_ppg, 'values'); -values_idx_imu = tsdf_values_idx(metadata_list_imu, 'values'); - -t_iso_ppg = metadata_list_ppg{time_idx_ppg}.start_iso8601; -t_iso_imu = metadata_list_imu{time_idx_imu}.start_iso8601; - -datetime_ppg = datetime(t_iso_ppg, 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'TimeZone', 'UTC'); -datetime_imu = datetime(t_iso_imu, 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'TimeZone', 'UTC'); - -tr_ppg = data_list_ppg{time_idx_ppg}; -tr_imu = data_list_imu{time_idx_imu}; - -ts_ppg = posixtime(datetime_ppg) * unix_ticks_ms; % calculate the unix timestamp in ms -ts_imu = posixtime(datetime_imu) * unix_ticks_ms; % calculate the unix timestamp in ms - -t_ppg = tr_ppg + ts_ppg(n); -t_imu = tr_imu + ts_imu(n); - - -v_ppg = data_list_ppg{values_idx_ppg}; -v_imu = data_list_imu{values_idx_imu}; % store data values for every seperate tsdf file in cell -%scale_factors = metadata_list_imu{values_idx_imu}.scale_factors'; - -%% 4. Data synchronization on right indices -fs_ppg_est = 1/median(diff(tr_ppg)); -fs_imu_est = 1/median(diff(tr_imu)); -[ppg_indices, imu_indices] = extract_overlapping_segments(t_ppg, t_imu); % List of two pairs of indices, e.g., [(0, 1000), (1, 2002)] - they might differ depending on the sampling rate - -%%---Update data vectors on synchronized labels---%% -v_ppg = v_ppg(ppg_indices(1):ppg_indices(2)); -v_imu = v_imu(imu_indices(1):imu_indices(2),:); -t_ppg = t_ppg(ppg_indices(1):ppg_indices(2)); -t_imu = t_imu(imu_indices(1):imu_indices(2)); -tr_ppg = tr_ppg(ppg_indices(1):ppg_indices(2)); -tr_imu = tr_imu(imu_indices(1):imu_indices(2)); - -ts_sync = ts_ppg + tr_ppg(1)*unix_ticks_ms; % update ts_sync by the first relative time point containing both PPG and IMU a - -tr_ppg = tr_ppg - tr_ppg(1); % update tr_ppg by the first relative time point containing both PPG and IMU --> should be done after ts_sync is updated -tr_imu = tr_imu - tr_imu(1); % update tr_imu by the first relative time point containing both PPG and IMU - -%% 5. Data preprocessing -%%--Preprocessing both IMU and PPG%% -v_acc_scaled = double(v_imu(:,1:3)); % Extract only the accelerometer channels and multiply them using scale factors! --> now based on indices but preferably on channel names in metadata??? -min_window_length = 30; - -%%----NEEDS TO BE IMPLEMENTED IN FUNCTION!!--%% -if length(v_ppg) < fs_ppg * min_window_length || length(v_acc_scaled) < fs_imu * min_window_length % Only resample, feature calculation and classification on arrays > 30s since these are required for HR(V) analysis later on --> maybe add this to the synchronization - warning('Sample is of insufficient length!') -else - [v_ppg_pre, tr_ppg_pre] = preprocessing_ppg(tr_ppg, v_ppg, fs_ppg); % 2 matrices, one for ppg (Nx1) and for time (Nx1) - [v_acc_pre, tr_acc_pre] = preprocessing_imu(tr_imu, v_acc_scaled, fs_imu); % 2 matrices, one for accel imu (Nx3) and for time (Nx1) -end - -%% 5a. Write TSDF PPG preprocessing output -location = "..\..\tests\data\2.preprocessed_data\ppg"; -data_pre_ppg{1} = tr_ppg_pre; -data_pre_ppg{2} = v_ppg_pre; - -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(ts_sync/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime((ts_sync+tr_ppg_pre(end)*1000)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -metafile_pre_template.ppp_source_protobuf = "WatchData.PPG.Week104.raw"; - -metafile_time = metafile_pre_template; % time vector metadata list as a template and adjust it -metafile_values = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'relative_ms'}; -metafile_time.freq_sampling_original = fs_ppg_est; -metafile_time.file_name = 'PPG_time.bin'; - -metafile_values.channels = {'green'}; -metafile_values.units = {'none'}; -metafile_values.freq_sampling_original = fs_ppg_est; -metafile_values.file_name = 'PPG_samples.bin'; - -meta_pre_ppg{1} = metafile_time; -meta_pre_ppg{2} = metafile_values; -mat_metadata_file_name = "PPG_meta.json"; -save_tsdf_data(meta_pre_ppg, data_pre_ppg, location, mat_metadata_file_name) - -%% 5b. Write TSDF PPG preprocessing output -data_pre_acc{1} = tr_acc_pre; -data_pre_acc{2} = v_acc_pre; - -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(ts_sync/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime((ts_sync+tr_acc_pre(end)*unix_ticks_ms)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -metafile_pre_template.ppp_source_protobuf = "WatchData.IMU.Week104.raw"; - -metafile_time = metafile_pre_template; % time vector metadata list -metafile_values = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'ms'}; -metafile_time.freq_sampling_original = fs_imu_est; -metafile_time.file_name = 'accelerometer_time.bin'; - -metafile_values.channels = {'acceleration_x', 'acceleration_y', 'acceleration_z'}; -metafile_values.units = {'m/s/s', 'm/s/s', 'm/s/s'}; -metafile_values.freq_sampling_original = fs_imu_est; % Sampling rate in Hz -metafile_values.file_name = 'accelerometer_samples.bin'; - -meta_pre_acc{1} = metafile_time; -meta_pre_acc{2} = metafile_values; -mat_metadata_file_name = "accelerometer_meta.json"; -save_tsdf_data(meta_pre_acc, data_pre_acc, location, mat_metadata_file_name) -%% 6. Feature extraction -tic -% Create loop for 6s epochs with 5s overlap -epoch_length = 6; % in seconds -overlap = 5; % in seconds - -% Number of samples in epoch -samples_per_epoch_ppg = epoch_length * fs_ppg; -samples_per_epoch_acc = epoch_length * fs_imu; - -% Calculate number of samples to shift for each epoch -samples_shift_ppg = (epoch_length - overlap) * fs_ppg; -samples_shift_acc = (epoch_length - overlap) * fs_imu; % Hoe krijg ik mijn segmenten precies gelijk zodat het niet toevallig een error geeft dat 1 langer is dan de ander - -pwelchwin_acc = 3*fs_imu; % window length for pwelch -pwelchwin_ppg = 3*fs_ppg; % window length for pwelch -noverlap_acc = 0.5*pwelchwin_acc; % overlap for pwelch -noverlap_ppg = 0.5*pwelchwin_ppg; % overlap for pwelch - -f_bin_res = 0.05; % the treshold is set based on this binning --> so range of 0.1 Hz for calculating the PSD feature -nfft_ppg = 0:f_bin_res:fs_ppg/2; % frequency bins for pwelch ppg -nfft_acc = 0:f_bin_res:fs_imu/2; % frequency bins for pwelch imu - -features_ppg_scaled = []; -feature_acc = []; -t_unix_feat_total = []; -count = 0; -acc_idx = 1; - -% Load classifier with corresponding mu and sigma to z-score the features -load("LR_model.mat") -mu = LR_model.mu; -sigma = LR_model.sigma; -classifier = LR_model.classifier; % this classifier is only used later at the stage 7 - -% DESCRIBE THE LOOPING OVER 6s SEGMENTS FOR BOTH PPG AND IMU AND CALCULATE FEATURES -for i = 1:samples_shift_ppg:(length(v_ppg_pre) - samples_per_epoch_ppg + 1) - - if acc_idx + samples_per_epoch_acc - 1 > length(v_acc_pre) % For the last epoch, check if the segment for IMU is too short (not 6 seconds), add a check for the last epoch first (if i == last then...) - break - else - acc_segment = v_acc_pre(acc_idx:(acc_idx+samples_per_epoch_acc-1),:); % Extract the IMU window (6seconds) - end - ppg_segment = v_ppg_pre(i:(i + samples_per_epoch_ppg - 1)); % Extract the PPG window (6seconds) - - count = count + 1; - - %%--------Feature extraction + scaling--------%% - % calculate features using ppg_features.m - %features = ppg_features(ppg_segment, fs_ppg); % for now PPG_segment --> name can be adjusted! - - % Scaling using z-score - %features_ppg_scaled(count,:) = normalize(features, 'center', mu, 'scale', sigma); - - % Calculating psd (power spectral density) of imu and ppg - % in the Gait pipeline this is done using the Fourier transformation - % [pxx1,f1] = pwelch(acc_segment,hann(pwelchwin_acc), noverlap_acc, nfft_acc, fs_imu); - [pxx1,f1] = pwelch(acc_segment,hann(pwelchwin_acc), noverlap_acc, 2000, fs_imu); - PSD_imu = sum(pxx1,2); % sum over the three axis - % [pxx2,f2] = pwelch(ppg_segment,hann(pwelchwin_ppg), noverlap_ppg, nfft_ppg, fs_ppg); - [pxx2,f2] = pwelch(ppg_segment,hann(pwelchwin_ppg), noverlap_ppg, 600, fs_ppg); - PSD_ppg = pxx2; % this does nothing, equal to PSD_ppg = pxx2 - - % IMU feature extraction - feature_acc(count,1) = acc_feature(f1, PSD_imu, f2, PSD_ppg); % Calculate the power ratio of the accelerometer signal in the PPG frequency range and store it as a row in the feature matrix (which has only 1 column) - - % time channel - t_unix_feat_total(count,1) = tr_ppg_pre(i)*unix_ticks_ms + t_ppg(1); % Save in absolute unix time ms - acc_idx = acc_idx + samples_shift_acc; % update IMU_idx -end -% at this point we have a matrix with features for PPG (10 column), IMU (1 columns), and a time vector -toc -% THis is stored for later (stage 4) -v_sync_ppg_total(1,1) = ppg_indices(1); % start index --> needed for HR pipeline -v_sync_ppg_total(1,2) = ppg_indices(2); % end index --> needed for HR pipeline -v_sync_ppg_total(1,3) = segment_ppg(1); % Segment index --> needed for HR pipeline --> in loop this is n -v_sync_ppg_total(1,4) = count; % Number of epochs in the segment --> needed for HR pipeline - - -%% 6a. Write TSDF PPG feature extraction output (ppg features) -location = "..\..\tests\data\3.extracted_features\ppg"; -data_feat_ppg{1} = t_unix_feat_total; -data_feat_ppg{2} = single(features_ppg_scaled); - -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(ts_sync/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime((ts_sync+tr_acc_pre(end)*unix_ticks_ms)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -metafile_pre_template.ppp_source_protobuf = "WatchData.PPG.Week104.raw"; - -metafile_time = metafile_pre_template; % time vector metadata list as a template and adjust it -metafile_values = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_ms'}; -metafile_time.freq_sampling_original = fs_ppg_est; -metafile_time.file_name = 'features_ppg_time.bin'; - -metafile_values.channels = {'variance', 'mean', 'median', 'kurtosis', 'skewness', 'dominant frequency', 'relative power', 'spectral entropy', 'SNR', 'correlation peak'}; -metafile_values.units = {'none', 'none', 'none', 'none', 'none', 'Hz', 'none', 'none', 'none', 'none'}; -metafile_values.freq_sampling_original = fs_ppg_est; -metafile_values.file_name = 'features_ppg_samples.bin'; - -meta_feat_ppg{1} = metafile_time; -meta_feat_ppg{2} = metafile_values; -mat_metadata_file_name = "features_ppg_meta.json"; -save_tsdf_data(meta_feat_ppg, data_feat_ppg, location, mat_metadata_file_name) - -%% 6b. Write TSDF PPG preprocessing output (accelerometer feature) -location = "..\..\tests\data\3.extracted_features\ppg"; -data_feat_acc{1} = t_unix_feat_total; -data_feat_acc{2} = single(feature_acc); -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(ts_sync/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime((ts_sync+tr_acc_pre(end)*unix_ticks_ms)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -metafile_pre_template.ppp_source_protobuf = "WatchData.IMU.Week104.raw"; - -metafile_time = metafile_pre_template; % time vector metadata list -metafile_values = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_ms'}; -metafile_time.freq_sampling_original = fs_imu_est; -metafile_time.file_name = 'feature_acc_time.bin'; - -metafile_values.channels = {'relative power acc'}; -metafile_values.units = {'none'}; -metafile_values.freq_sampling_original = fs_imu_est; % Sampling rate in Hz -metafile_values.file_name = 'feature_acc_samples.bin'; - -meta_feat_acc{1} = metafile_time; -meta_feat_acc{2} = metafile_values; -mat_metadata_file_name = "feature_acc_meta.json"; -save_tsdf_data(meta_feat_acc, data_feat_acc, location, mat_metadata_file_name) -%% 7. Classification - - -threshold_acc = 0.13; % Final threshold -[~, ppg_post_prob] = predict(classifier, features_ppg_scaled); % Calculate posterior probability using LR model, python provides a similar function -ppg_post_prob_HQ = ppg_post_prob(:,1); -acc_label = feature_acc < threshold_acc; % logical (boolean) for not surpassing threshold_acc for imu feature. imu_label is one if we don't suspect the epoch to be disturbed by periodic movements! That is in line with 1 for HQ PPG - -%% 7a. Storage of classification in tsdf, each element is a separate binary file (all but the 4th one include one column) -data_class{1} = int32(t_unix_feat_total/unix_ticks_ms); % 32 bit integer and store it in unix seconds -data_class{2} = single(ppg_post_prob_HQ); % 32 bit float -data_class{3} = int8(acc_label); % 8 bit integer -data_class{4} = int32(v_sync_ppg_total); % 64 bit integer - 4 columns -data_class{5} = single(feature_acc); % 32 bit float - -location = "..\..\tests\data\4.predictions\ppg"; -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(t_unix_feat_total(1)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime(t_unix_feat_total(end)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); % Convert the start and end time to ISO8601 format - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -%metafile_pre_template.ppp_source_protobuf = "WatchData.IMU.Week104.raw"; -% Contains both IMU and PPG original raw files for classification --> what -% is the most neat thing to do - -metafile_time = metafile_pre_template; % time vector metadata list -metafile_values_ppg = metafile_pre_template; -metafile_values_imu = metafile_pre_template; -metafile_sync = metafile_pre_template; -metafile_values_imu_feat = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_ms'}; -metafile_time.file_name = 'classification_sqa_time.bin'; - -metafile_values_ppg.channels = {'post probability'}; -metafile_values_ppg.units = {'probability'}; -metafile_values_ppg.freq_sampling_original = fs_ppg_est; % Sampling rate in Hz -metafile_values_ppg.file_name = 'classification_sqa_ppg.bin'; - -metafile_values_imu.channels = {'accelerometer classification'}; -metafile_values_imu.units = {'boolean_num'}; -metafile_values_imu.freq_sampling_original = fs_imu_est; % Sampling rate in Hz -metafile_values_imu.file_name = 'classification_sqa_imu.bin'; - -metafile_sync.channels = {'ppg start index', 'ppg end index', 'ppg segment index', 'number of windows'}; % Define the channels -metafile_sync.units = {'index', 'index', 'index', 'none'}; -metafile_sync.file_name = 'classification_sqa_sync.bin'; - -metafile_values_imu_feat.channels = {'Relative power'}; -metafile_values_imu_feat.units = {'none'}; -metafile_values_imu_feat.file_name = 'classification_sqa_feat_imu.bin'; -metafile_values_imu_feat.bin_width = 2*f_bin_res; % Save the bin width of the relative power ratio feature - -meta_class{1} = metafile_time; -meta_class{2} = metafile_values_ppg; -meta_class{3} = metafile_values_imu; -meta_class{4} = metafile_sync; -meta_class{5} = metafile_values_imu_feat; - -mat_metadata_file_name = "classification_sqa_meta.json"; -save_tsdf_data(meta_class, data_class, location, mat_metadata_file_name) - -%% 8. Incorporate HR estimation \ No newline at end of file diff --git a/docs/matlab_scripts/ppg/1-4_HR_estimation.m b/docs/matlab_scripts/ppg/1-4_HR_estimation.m deleted file mode 100644 index 8d396c70..00000000 --- a/docs/matlab_scripts/ppg/1-4_HR_estimation.m +++ /dev/null @@ -1,223 +0,0 @@ -%% Main script to perform heart rate estimation of wearable PPG -% This script uses both PPG and accelerometer and performs the following -% steps: -% 1. Loading all metadata of PPG and IMU -% 2. Query on data availability + synchronization -% 3. Loading relevant segment sensor data using tsdf wrapper (start for loop over synchronized segment indices) -% 4. Synchronize the data (correct indices etc) -% 5. Data preprocessing -% 6. Perform pseude-smoothed wigner-ville distribution (PSWVD) on PPG -% 7. Saving the HR estimates in tsdf format - -%% Architecture overview -% The script implements the following steps: -% 1. PPG preprocessing -% 4. HR estimation - -%% Initalization -% Setting data paths + extracting metafilenames already -clearvars; close all; clc -addpath(genpath('..\..\..\paradigma-toolbox')) % Add git repository to the path -addpath(genpath("..\..\..\tsdf4matlab")) % Add wrapper to the path -warning('off','all') % Turn off warnings to improve speed in spwvd especially - -% Setting the data paths -unix_ticks_ms = 1000.0; -fs_ppg = 30; % Establish the sampling rate desired for resampling PPG --> now chosen to be fixed on 30 Hz - -raw_data_root = '..\..\..\tests\data\1.prepared_data\'; -ppp_data_path_ppg = [raw_data_root 'PPG\']; -meta_ppg = tsdf_scan_meta(ppp_data_path_ppg); % tsdf_scan_meta returns metafile struct containing information of all metafiles from all patients in tsdf_dirlist -n_files_ppg = length(meta_ppg); - -sqa_data_path = '..\..\..\tests\data\4.predictions\ppg'; % Set the path to the SQA data -sqa_output_list = dir(fullfile(sqa_data_path, '*_meta.json')); % seperate for the SQA output files - -meta_path_sqa = fullfile(sqa_output_list.folder, sqa_output_list.name); % Get the name of the SQA output file -[metadata_list_sqa, data_list_sqa] = load_tsdf_metadata_from_path(meta_path_sqa); % Load the metadata of the SQA output file - -sync_idx = tsdf_values_idx(metadata_list_sqa, 'sync'); % Get the index of the sync field in the SQA output file -data_sync = data_list_sqa{sync_idx}; % Get the sync data of the SQA output file -data_sync_zeros = all(data_sync == 0, 2); % Find rows containing only zeros --> in updated code this should not be possible anymore -data_sync(data_sync_zeros, :) = []; % Remove rows containing only zeros - -n_segments_sync = size(data_sync,1); % Get the number of segments in the SQA output file - -% Load the classification data -ppg_prob_idx = tsdf_values_idx(metadata_list_sqa, 'ppg'); % Get the index of the ppg field in the SQA output file -ppg_post_prob = data_list_sqa{ppg_prob_idx}; % Get the PPG probability data of the SQA output file - -imu_idx = tsdf_values_idx(metadata_list_sqa, 'sqa_imu'); % Get the index of the imu field in the SQA output file -imu_label = data_list_sqa{imu_idx}; % Get the IMU label data of the SQA output file - -% Calculate start_end indices of the classification corresponding to the -% correct segment --> needed since only number of segments is stored - -% Initialize the start_end_indices array of the classification epochs -for i = 1:length(data_sync(:,4)) - if i == 1 - start_end_indices(i, 1) = 1; - else - start_end_indices(i, 1) = start_end_indices(i-1, 2) + 1; - end - start_end_indices(i, 2) = sum(data_sync(1:i,4)); -end - - -%% Setting some parameters for HR analysis -min_window_length = 10; -min_hr_samples = min_window_length*fs_ppg; -threshold_sqa = 0.5; -fs_ppg_est = []; % Initialize the estimated sampling rate of the PPG - -hr_est_length = 2; %Estimation of HR is per 2 s (implemented in the PPG_TFD_HR function) -hr_est_samples = hr_est_length*fs_ppg; % number of samples - -% Time-frequency distribution parameters -tfd_length = 10; % Length of the epoch to calculate the time-frequency distribution in seconds -kern_type = 'sep'; % sep is the spwvd from the J. O'Toole box;) -win_type_doppler = 'hamm'; win_type_lag = 'hamm'; -win_length_doppler = 1; win_length_lag = 8; -doppler_samples = fs_ppg * win_length_doppler; lag_samples = win_length_lag * fs_ppg; -kern_params = { {doppler_samples, win_type_doppler}, {lag_samples ,win_type_lag} }; - -% Initialze a moving average filter struct -MA = struct; -MA.value = 0; % set MA to 1 if you want a moving average filter over the tfd from WVD and SPWVD to overcome unwanted fundamental frequency switching. -MA.window = 30; % Window size for the filter (order = 30-1) --> is not really necessary to have in the struct but for simplicity it is -MA.FC = 1/MA.window*ones(MA.window,1); % Set the filter coefficients for the MA filter - -v_hr_ppg = []; -t_hr_unix = []; -%% Loop over all synchronized segments -for n = 1:n_segments_sync - ppg_indices = data_sync(n,1:2); % Get the indices of the PPG segment - ppg_segment = data_sync(n,3); % Get the segment number of the PPG segment - - class_start = start_end_indices(n,1); - class_end = start_end_indices(n,2); - - meta_path_ppg = meta_ppg(ppg_segment).tsdf_meta_fullpath; - - [metadata_list_ppg, data_list_ppg] = load_tsdf_metadata_from_path(meta_path_ppg); - - time_idx_ppg = tsdf_values_idx(metadata_list_ppg, 'time'); - values_idx_ppg = tsdf_values_idx(metadata_list_ppg, 'values'); - - - t_iso_ppg = metadata_list_ppg{time_idx_ppg}.start_iso8601; - datetime_ppg = datetime(t_iso_ppg, 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'TimeZone', 'UTC'); - ts_ppg = posixtime(datetime_ppg) * unix_ticks_ms; - - t_ppg = cumsum(double(data_list_ppg{time_idx_ppg})) + ts_ppg; - - tr_ppg = (t_ppg - ts_ppg) / unix_ticks_ms; - - v_ppg = data_list_ppg{values_idx_ppg}; - - clear t_ppg data_list_ppg - - v_ppg = v_ppg(ppg_indices(1):ppg_indices(2)); - - tr_ppg = tr_ppg(ppg_indices(1):ppg_indices(2)); - - ts_sync = ts_ppg + tr_ppg(1) * unix_ticks_ms; - tr_ppg = tr_ppg - tr_ppg(1); - - fs_ppg_est = 1/median(diff(tr_ppg)); - - if length(v_ppg) < fs_ppg * min_window_length % Check if the sample is of sufficient length - warning('Sample is of insufficient length!') - continue - else - [v_ppg_pre, tr_ppg_pre] = preprocessing_ppg(tr_ppg, v_ppg, fs_ppg); - end - clear v_ppg tr_ppg % Clear the redundant variables to free up memory - - % Select the correct classification data - class_ppg_segment = ppg_post_prob(class_start:class_end); - class_acc_segment = imu_label(class_start:class_end); - - % Assign the window-level probabilities to the individual samples - %data_prob_sample = sample_prob_final(class_ppg_segment, fs_ppg, class_acc_segment); - data_prob_sample = sample_prob_final(class_ppg_segment, fs_ppg); - - - sqa_label = []; - - for i = 1:length(data_prob_sample) - if data_prob_sample(i) > threshold_sqa - sqa_label(i,1) = 1; % Assign label 1 --> high-quality - else - sqa_label(i,1) = 0; % Assign low quality - end - end - - [v_start_idx, v_end_idx] = extract_hr_segments(sqa_label, min_hr_samples); - - for i = 1:length(v_start_idx) - - % The things below can be written to a function if desired?? - rel_ppg = v_ppg_pre(v_start_idx(i):v_end_idx(i)); - rel_time = tr_ppg_pre(v_start_idx(i):v_end_idx(i)); - - % Check whether the epoch can be extended by 2 s on both - % sides --> not possible if it is the end of the epoch or - % the start - if v_start_idx(i)<2*fs_ppg || v_end_idx(i)>length(v_ppg_pre)-2*fs_ppg - continue % for now skip these epoch since these are probably an artifact (see example) but this could be relevant to check later on! - end - - rel_ppg_spwvd = v_ppg_pre(v_start_idx(i)-fs_ppg*2:v_end_idx(i)+fs_ppg*2); %extract epoch with two extra seconds at start and end to overcome boundary effects of the WVD/SPWVD function, necessary for the for loop --> also implemented for cwt to make it more or less the same! - hr_est = PPG_TFD_HR(rel_ppg_spwvd, tfd_length, MA, fs_ppg, kern_type, kern_params); %wvd distribution does not require additional parameters for windowing - - %%-----Corresponding HR estimation time array-----&& - if mod(length(rel_ppg),60)~=0 %if segment length is uneven --> substract fs - hr_time = rel_time(1:hr_est_samples:length(rel_ppg)-fs_ppg); - else - hr_time = rel_time(1:hr_est_samples:length(rel_ppg)); - end - %%-------Save output-------%% - t_epoch_unix = hr_time'*unix_ticks_ms + ts_sync; - v_hr_ppg = [v_hr_ppg; hr_est]; - t_hr_unix = [t_hr_unix; t_epoch_unix]; - - end -end - -% Save the hr output in tsdf format -data_hr_est{1} = int32(t_hr_unix/unix_ticks_ms); % 32 bit integer and store it in unix seconds -data_hr_est{2} = single(v_hr_ppg); % 32 bit float - -location = "..\..\tests\data\5.quantification\ppg"; % Location to save the data -mkdir(location) -metafile_pre_template = metadata_list_sqa{time_idx_ppg}; % Copy the metadata template from the sqa time data --> most clean - -if isempty (t_hr_unix) - start_time_iso = datetime(0, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - end_time_iso = datetime(0, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -else - start_time_iso = datetime(t_hr_unix(1)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - end_time_iso = datetime(t_hr_unix(end)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); % Convert the start and end time to ISO8601 format -end -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); - -metafile_time = metafile_pre_template; % time vector metadata list -metafile_values_hr = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_s'}; -metafile_time.file_name = 'hr_est_time.bin'; - -metafile_values_hr.channels = {'HR estimates'}; -metafile_values_hr.units = {'min^-1'}; -metafile_values_hr.freq_sampling_original = round(fs_ppg_est, 2); % Sampling rate in Hz of the raw data -metafile_values_hr.file_name = 'hr_est_values.bin'; - - -meta_class{1} = metafile_time; -meta_class{2} = metafile_values_hr; - -mat_metadata_file_name = "hr_est_meta.json"; -% save_tsdf_data(meta_class, data_hr_est, location, mat_metadata_file_name); \ No newline at end of file diff --git a/docs/matlab_scripts/ppg/2-3_signal_quality_dbpd_update.m b/docs/matlab_scripts/ppg/2-3_signal_quality_dbpd_update.m deleted file mode 100644 index 18c105e8..00000000 --- a/docs/matlab_scripts/ppg/2-3_signal_quality_dbpd_update.m +++ /dev/null @@ -1,253 +0,0 @@ -%% Main script to perform feature extraction for the signal quality assessment -% This script uses both PPG and accelerometer and performs the following -% steps: -% 1. Loading the preprocessed PPG and accelerometer data from the -% implementation of the paradigma toolbox -% 2. Feature extraction -% 3. Storing the features - - -% Architecture overview -% The script implements the following steps: -% 2. IMU and PPG feature extraction -% 3. Signal quality assessment - - -%% Initalization -% Setting data paths + extracting metafilenames already -clearvars; close all; clc -addpath(genpath('..\..\..\..\paradigma-toolbox')) % Add git repository to the path -addpath(genpath("..\..\..\..\tsdf4matlab")) % Add wrapper to the path - -unix_ticks_ms = 1000.0; -fs_ppg = 30; % Establish the sampling rate desired for resampling PPG --> now chosen to be fixed on 30 Hz -fs_imu = 100; % Establish the sampling rate desired for resampling IMU --> now chosen to be fixed on 30 Hz - -raw_data_root = '..\..\..\tests\data\2.preprocessed_data\PPG\'; -ppp_data_path_ppg = [raw_data_root 'PPG_new\']; -ppp_data_path_imu = [raw_data_root 'IMU_new\']; - -%% 1. Loading all metadata of PPG and IMU -meta_ppg = tsdf_scan_meta(ppp_data_path_ppg); % tsdf_scan_meta returns metafile struct containing information of all metafiles from all patients in tsdf_dirlist -meta_imu = tsdf_scan_meta(ppp_data_path_imu); - -%% 2. Loading the preprocessed PPG and accelerometer data -meta_path_ppg = meta_ppg.tsdf_meta_fullpath; -meta_path_imu = meta_imu.tsdf_meta_fullpath; -[metadata_list_ppg, data_list_ppg] = load_tsdf_metadata_from_path(meta_path_ppg); -[metadata_list_imu, data_list_imu] = load_tsdf_metadata_from_path(meta_path_imu); - -time_idx_ppg = tsdf_values_idx(metadata_list_ppg, 'time'); -tr_ppg_pre = data_list_ppg{time_idx_ppg}; -values_idx_ppg = tsdf_values_idx(metadata_list_ppg, 'samples'); -v_ppg_pre = data_list_ppg{values_idx_ppg}; - -time_idx_imu = tsdf_values_idx(metadata_list_imu, 'time'); -tr_imu_pre = data_list_imu{time_idx_ppg}; -values_idx_imu = tsdf_values_idx(metadata_list_imu, 'samples'); -v_imu_pre = data_list_imu{values_idx_imu}; - -%% 3. Feature extraction -% Create loop for 6s epochs with 5s overlap -epoch_length = 6; % in seconds -overlap = 5; % in seconds - -% Number of samples in epoch -samples_per_epoch_ppg = epoch_length * fs_ppg; -samples_per_epoch_acc = epoch_length * fs_imu; - -% Calculate number of samples to shift for each epoch -samples_shift_ppg = (epoch_length - overlap) * fs_ppg; -samples_shift_acc = (epoch_length - overlap) * fs_imu; % Hoe krijg ik mijn segmenten precies gelijk zodat het niet toevallig een error geeft dat 1 langer is dan de ander - -pwelchwin_acc = 3*fs_imu; % window length for pwelch -pwelchwin_ppg = 3*fs_ppg; % window length for pwelch -noverlap_acc = 0.5*pwelchwin_acc; % overlap for pwelch -noverlap_ppg = 0.5*pwelchwin_ppg; % overlap for pwelch - -f_bin_res = 0.05; % the treshold is set based on this binning --> so range of 0.1 Hz for calculating the PSD feature -nfft_ppg = 0:f_bin_res:fs_ppg/2; % frequency bins for pwelch ppg -nfft_acc = 0:f_bin_res:fs_imu/2; % frequency bins for pwelch imu - -features_ppg_scaled = []; -feature_acc = []; -t_unix_feat_total = []; -count = 0; -acc_idx = 1; - -% Load classifier with corresponding mu and sigma to z-score the features -load("LR_model.mat") -mu = LR_model.mu; -sigma = LR_model.sigma; -classifier = LR_model.classifier; % this classifier is only used later at the stage 7 - -% DESCRIBE THE LOOPING OVER 6s SEGMENTS FOR BOTH PPG AND IMU AND CALCULATE FEATURES -for i = 1:samples_shift_ppg:(length(v_ppg_pre) - samples_per_epoch_ppg + 1) - - if acc_idx + samples_per_epoch_acc - 1 > length(v_acc_pre) % For the last epoch, check if the segment for IMU is too short (not 6 seconds), add a check for the last epoch first (if i == last then...) - break - else - acc_segment = v_acc_pre(acc_idx:(acc_idx+samples_per_epoch_acc-1),:); % Extract the IMU window (6seconds) - end - ppg_segment = v_ppg_pre(i:(i + samples_per_epoch_ppg - 1)); % Extract the PPG window (6seconds) - - count = count + 1; - - %%--------Feature extraction + scaling--------%% - % calculate features using ppg_features.m - features = ppg_features(ppg_segment, fs_ppg); % for now PPG_segment --> name can be adjusted! - - % Scaling using z-score - features_ppg_scaled(count,:) = normalize(features, 'center', mu, 'scale', sigma); - - % Calculating psd (power spectral density) of imu and ppg - % in the Gait pipeline this is done using the Fourier transformation - [pxx1,f1] = pwelch(acc_segment,hann(pwelchwin_acc), noverlap_acc, nfft_acc, fs_imu); - PSD_imu = sum(pxx1,2); % sum over the three axis - [pxx2,f2] = pwelch(ppg_segment,hann(pwelchwin_ppg), noverlap_ppg, nfft_ppg, fs_ppg); - PSD_ppg = sum(pxx2,1); % this does nothing, equal to PSD_ppg = pxx2 - - % IMU feature extraction - feature_acc(count,1) = acc_feature(f1, PSD_imu, f2, PSD_ppg); % Calculate the power ratio of the accelerometer signal in the PPG frequency range and store it as a row in the feature matrix (which has only 1 column) - - % time channel - t_unix_feat_total(count,1) = tr_ppg_pre(i)*unix_ticks_ms + t_ppg(1); % Save in absolute unix time ms - acc_idx = acc_idx + samples_shift_acc; % update IMU_idx -end -% at this point we have a matrix with features for PPG (10 column), IMU (1 columns), and a time vector - -% THis is stored for later (stage 4) -v_sync_ppg_total(1,1) = ppg_indices(1); % start index --> needed for HR pipeline -v_sync_ppg_total(1,2) = ppg_indices(2); % end index --> needed for HR pipeline -v_sync_ppg_total(1,3) = segment_ppg(1); % Segment index --> needed for HR pipeline --> in loop this is n -v_sync_ppg_total(1,4) = count; % Number of epochs in the segment --> needed for HR pipeline - - -%% 4a. Write TSDF PPG feature extraction output (ppg features) -location = "..\..\tests\data\3.extracted_features\ppg"; -data_feat_ppg{1} = t_unix_feat_total; -data_feat_ppg{2} = single(features_ppg_scaled); - -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(ts_sync/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime((ts_sync+tr_acc_pre(end)*unix_ticks_ms)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -metafile_pre_template.ppp_source_protobuf = "WatchData.PPG.Week104.raw"; - -metafile_time = metafile_pre_template; % time vector metadata list as a template and adjust it -metafile_values = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_ms'}; -metafile_time.freq_sampling_original = fs_ppg_est; -metafile_time.file_name = 'features_ppg_time.bin'; - -metafile_values.channels = {'variance', 'mean', 'median', 'kurtosis', 'skewness', 'dominant frequency', 'relative power', 'spectral entropy', 'SNR', 'correlation peak'}; -metafile_values.units = {'none', 'none', 'none', 'none', 'none', 'Hz', 'none', 'none', 'none', 'none'}; -metafile_values.freq_sampling_original = fs_ppg_est; -metafile_values.file_name = 'features_ppg_samples.bin'; - -meta_feat_ppg{1} = metafile_time; -meta_feat_ppg{2} = metafile_values; -mat_metadata_file_name = "features_ppg_meta.json"; -save_tsdf_data(meta_feat_ppg, data_feat_ppg, location, mat_metadata_file_name) - -%% 4b. Write TSDF PPG preprocessing output (accelerometer feature) -location = "..\..\tests\data\3.extracted_features\ppg"; -data_feat_acc{1} = t_unix_feat_total; -data_feat_acc{2} = single(feature_acc); -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(ts_sync/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime((ts_sync+tr_acc_pre(end)*unix_ticks_ms)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -metafile_pre_template.ppp_source_protobuf = "WatchData.IMU.Week104.raw"; - -metafile_time = metafile_pre_template; % time vector metadata list -metafile_values = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_ms'}; -metafile_time.freq_sampling_original = fs_imu_est; -metafile_time.file_name = 'feature_acc_time.bin'; - -metafile_values.channels = {'relative power acc'}; -metafile_values.units = {'none'}; -metafile_values.freq_sampling_original = fs_imu_est; % Sampling rate in Hz -metafile_values.file_name = 'feature_acc_samples.bin'; - -meta_feat_acc{1} = metafile_time; -meta_feat_acc{2} = metafile_values; -mat_metadata_file_name = "feature_acc_meta.json"; -save_tsdf_data(meta_feat_acc, data_feat_acc, location, mat_metadata_file_name) -%% 5. Classification - - -threshold_acc = 0.13; % Final threshold -[~, ppg_post_prob] = predict(classifier, features_ppg_scaled); % Calculate posterior probability using LR model, python provides a similar function -ppg_post_prob_HQ = ppg_post_prob(:,1); -acc_label = feature_acc < threshold_acc; % logical (boolean) for not surpassing threshold_acc for imu feature. imu_label is one if we don't suspect the epoch to be disturbed by periodic movements! That is in line with 1 for HQ PPG - -%% 7a. Storage of classification in tsdf, each element is a separate binary file (all but the 4th one include one column) -data_class{1} = int32(t_unix_feat_total/unix_ticks_ms); % 32 bit integer and store it in unix seconds -data_class{2} = single(ppg_post_prob_HQ); % 32 bit float -data_class{3} = int8(acc_label); % 8 bit integer -data_class{4} = int32(v_sync_ppg_total); % 64 bit integer - 4 columns -data_class{5} = single(feature_acc); % 32 bit float - -location = "..\..\tests\data\4.predictions\ppg"; -metafile_pre_template = metadata_list_ppg{values_idx_ppg}; - -start_time_iso = datetime(t_unix_feat_total(1)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); -end_time_iso = datetime(t_unix_feat_total(end)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss z', 'TimeZone', 'UTC'); % Convert the start and end time to ISO8601 format - -metafile_pre_template.start_iso8601 = string(start_time_iso); -metafile_pre_template.end_iso8601 = string(end_time_iso); -%metafile_pre_template.ppp_source_protobuf = "WatchData.IMU.Week104.raw"; -% Contains both IMU and PPG original raw files for classification --> what -% is the most neat thing to do - -metafile_time = metafile_pre_template; % time vector metadata list -metafile_values_ppg = metafile_pre_template; -metafile_values_imu = metafile_pre_template; -metafile_sync = metafile_pre_template; -metafile_values_imu_feat = metafile_pre_template; - -metafile_time.channels = {'time'}; -metafile_time.units = {'time_absolute_unix_ms'}; -metafile_time.file_name = 'classification_sqa_time.bin'; - -metafile_values_ppg.channels = {'post probability'}; -metafile_values_ppg.units = {'probability'}; -metafile_values_ppg.freq_sampling_original = fs_ppg_est; % Sampling rate in Hz -metafile_values_ppg.file_name = 'classification_sqa_ppg.bin'; - -metafile_values_imu.channels = {'accelerometer classification'}; -metafile_values_imu.units = {'boolean_num'}; -metafile_values_imu.freq_sampling_original = fs_imu_est; % Sampling rate in Hz -metafile_values_imu.file_name = 'classification_sqa_imu.bin'; - -metafile_sync.channels = {'ppg start index', 'ppg end index', 'ppg segment index', 'number of windows'}; % Define the channels -metafile_sync.units = {'index', 'index', 'index', 'none'}; -metafile_sync.file_name = 'classification_sqa_sync.bin'; - -metafile_values_imu_feat.channels = {'Relative power'}; -metafile_values_imu_feat.units = {'none'}; -metafile_values_imu_feat.file_name = 'classification_sqa_feat_imu.bin'; -metafile_values_imu_feat.bin_width = 2*f_bin_res; % Save the bin width of the relative power ratio feature - -meta_class{1} = metafile_time; -meta_class{2} = metafile_values_ppg; -meta_class{3} = metafile_values_imu; -meta_class{4} = metafile_sync; -meta_class{5} = metafile_values_imu_feat; - -mat_metadata_file_name = "classification_sqa_meta.json"; -save_tsdf_data(meta_class, data_class, location, mat_metadata_file_name) - -%% 8. Incorporate HR estimation \ No newline at end of file diff --git a/docs/matlab_scripts/tremor/main_tremor_eScience.m b/docs/matlab_scripts/tremor/main_tremor_eScience.m deleted file mode 100644 index 83e2e5e6..00000000 --- a/docs/matlab_scripts/tremor/main_tremor_eScience.m +++ /dev/null @@ -1,254 +0,0 @@ -%% Code for writing TSDF output for the tremor pipeline on a test subject from PPP -% Diogo C. Soriano and Nienke Timmermans -% 20/02/2024 - -clear all; -close all; - -%% Test subject -ppp_pep_userid = '0A0B82C94960D6DCABC1F597EC0BA657F4B0EDC320702BCEE3B6955CE924DE05'; % test subject for eScience -week_id = 104; - -% Set here data location -% Nienke: -% location = "D:\ppp_data\TSDF output\Test"; % location for storing tsdf output -% Diogo: -location = 'Z:\Diogo\Snellius Pipeline\Vedran - CheckPoint\Rest-Tremor---PPP-library\Test'; - -%% Loading the data -addpath(genpath('tsdf4matlab')); % Add tsdf package -addpath(genpath('functions_eScience')); % Add all functions in the subfolder -addpath(genpath('Model')); % Add subfolder with the classifier structures -addpath(genpath('jsonlab')); % Add subfolder with functions to load json file - -% Uncomment for obtaining arm activity classifier based on MFCCs trained -% with PD@Home labels - -% addpath(genpath('Arm activity classifier')); % Add subfolder with the classifier structures -% load('ArmClass.mat'); % Load Arm Activity Classifier - -unix_ticks_ms = 1000.0; - -% Set your path here -% ppp_data_path = ['D:\ppp_data\New Conversion\WatchData.IMU.Week',num2str(week_id)]; % IMU data path -ppp_data_path = ['Z:\Diogo\PPP Sample Data\data\SampleData - eScienceTest\WatchData.IMU.Week',num2str(week_id)]; % IMU data path -meta_segments_list = dir(fullfile(ppp_data_path, ppp_pep_userid, ['WatchData.IMU.Week',num2str(week_id),'.raw_segment*_meta.json'])); % create segment list -meta_filenames = {meta_segments_list.name}; % get names -Nfiles = length(meta_filenames); % get number of files - -bad_quality_threshold_imu = 0.3; - -shift_treshold = 300; % Set shift threshold for determining a segment also as bad quality, threshold is in seconds - -[imu_indices_bq, ~] = bad_quality(strcat(ppp_data_path,'\',ppp_pep_userid), Nfiles, bad_quality_threshold_imu, shift_treshold); - -meta_filenames(imu_indices_bq) = []; % remove bad quality segments from further analysis by removing them in the metafile list which is needed for further analyses - -if ~isempty(meta_filenames) % check if there are good quality segments left - - Nfiles = length(meta_filenames); % get number of files - - t_imu = {}; - v_imu = {}; - scale_factors = []; - - for n = 1:Nfiles - meta_fullpath = fullfile(ppp_data_path, ppp_pep_userid, '/', meta_filenames{n}); - [metadata_list, data_list] = load_tsdf_metadata_from_path(meta_fullpath); - time_idx = tsdf_values_idx(metadata_list, 'time', week_id); - values_idx = tsdf_values_idx(metadata_list, 'samples', week_id); - - t_iso = metadata_list{time_idx}.start_iso8601; - date_time_obj= datetime(t_iso, 'InputFormat', 'dd-MMM-yyyy HH:mm:ss Z', 'TimeZone', 'UTC'); - t_diff_imu{n} = data_list{time_idx}; - ts_imu(n) = posixtime(date_time_obj) * unix_ticks_ms; % calculate the unix timestamp in ms - t_imu{n} = cumsum(double(data_list{time_idx})) + ts_imu(n); - tr_imu{n} = (t_imu{n}-ts_imu(n))/unix_ticks_ms; - fs_est(n) = 1/(mean(diff(tr_imu{n}))); % Check the sampling frequency for each file - inverse of the mean of sampling interval - - v_imu{n} = data_list{values_idx}; % store data values for every seperate tsdf file in cell - scale_factors(n,:) = metadata_list{values_idx}.scale_factors'; - clear data_list; - end - - %% Preprocessing and feature extraction - Fs_aprox = round(mean(fs_est)); % Approximate sampling frequency considering all files - fsvector = [50 100]; % reference sampling rate - [~,ind] = min(abs(Fs_aprox-fsvector)); % Check which sampling rate is closer to the approximate sampling rate obtained - Fs = fsvector(ind); % Stablish a sampling rate from the reference which is closest to the approximate sampling rate - - % Allocating memory - Derivative = []; % Mean absolute derivative values [x,y,z] - PowerAxis = []; % Power within the range [0.5 - 25] Hz - DomTremorPowerAxis = []; % Dominant Power in the tremor range for each axis - PSDTremorFeatures = []; - PSDHighTremorFeatures = []; - MelCepsCoeff = []; - FreqPeak = []; - WinDateTime = []; - PowerArmActv = []; - PowerHighFreq = []; - - TremorProb = []; - TremorHat = []; - RestTremorHat = []; - - v_imu_proc = {}; - t_imu_proc = {}; - - for n = 1:Nfiles - - y_curr_gyro = scale_factors(n,4:6).*double(v_imu{n}(:,4:6)); % Get the gyroscope signals scaled by the respective scaling factors - - % Interpolate the data - sampling frequency adjustment - [t_imu_proc{n}, v_imu_proc{n}] = InterpData(tr_imu{n},y_curr_gyro,Fs,unix_ticks_ms,ts_imu(n)); % pre-processing: interpolate data - - % Save pre-processed data in TSDF - procdata_tsdf{1} = int64(t_imu_proc{n}); - procdata_tsdf{2} = v_imu_proc{n}; - - metafile_template = metadata_list{1}; - - start_time_iso = datetime(t_imu_proc{n}(1)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss Z', 'TimeZone', 'UTC'); - end_time_iso = datetime(t_imu_proc{n}(end)/unix_ticks_ms+1, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss Z', 'TimeZone', 'UTC'); - - metafile_template.start_iso8601 = datestr(start_time_iso); - metafile_template.end_iso8601 = datestr(end_time_iso); - metafile_template.freq_sampling_original = Fs_aprox; - metafile_template.freq_sampling_adjusted = Fs; - - metafile_proctime = metafile_template; - metafile_procgyro = metafile_template; - - metafile_proctime.channels = {'time'}; - metafile_proctime.units = {'time_absolute_unix_ms'}; - metafile_proctime.file_name = 'Tremor_preprocessed_time.bin'; - - metafile_procgyro.channels = {'rotation_x','rotation_y','rotation_z'}; - metafile_procgyro.units = {'deg/s','deg/s','deg/s'}; - metafile_procgyro.file_name = 'Tremor_preprocessed_gyro.bin'; - - procmeta_tsdf{1} = metafile_proctime; - procmeta_tsdf{2} = metafile_procgyro; - - mat_metadata_file_name = "Tremor_preprocessed_data.json"; - save_tsdf_data(procmeta_tsdf, procdata_tsdf, location, mat_metadata_file_name); - - %% Extracting the features - % General parameter setting for Configuration structure for feature - % extraction. Other "fixed" feature extraction parameters are set - % within TremorFeature function - - Conf.WindowSizeTime = 4; % Window size of 4 seconds - Conf.Fs = Fs; % Sampling frequency - TypeOfSignal = 'Gy'; % Gyroscope signals - - tic - Features_per_segment = TremorFeaturesAndClassification(Conf,v_imu_proc{n},t_imu_proc{n},TypeOfSignal); % Calculate features - elapsed = toc - % Concatenate features - if istable(Features_per_segment.PSDTremorFeatures) - - WinDateTime = vertcat(WinDateTime, Features_per_segment.WindowIniTime); - - Derivative = vertcat(Derivative, Features_per_segment.Derivatives); - PowerAxis = vertcat(PowerAxis,Features_per_segment.PowerAxis); - DomTremorPowerAxis = vertcat(DomTremorPowerAxis,Features_per_segment.DomTremorPowerAxis); - FreqPeak = vertcat(FreqPeak, Features_per_segment.FreqPeak); - PSDTremorFeatures = vertcat(PSDTremorFeatures, Features_per_segment.PSDTremorFeatures); - PSDHighTremorFeatures = vertcat(PSDHighTremorFeatures, Features_per_segment.PSDHighTremorFeatures); - PowerArmActv = vertcat(PowerArmActv,Features_per_segment.PowerArmActv); - PowerHighFreq = vertcat(PowerHighFreq,Features_per_segment.PowerHighFreq); - MelCepsCoeff = vertcat(MelCepsCoeff, Features_per_segment.MelCepsCoeff); - - % Get Tremor Classification Variables for tsdf writting - TremorProb = vertcat(TremorProb,Features_per_segment.TremorProb); - TremorHat = vertcat(TremorHat,Features_per_segment.TremorHat); - RestTremorHat = vertcat(RestTremorHat,Features_per_segment.RestTremorHat); - - end - end - - % Features that need to be saved for further analysis - - FeaturesTremor = [Derivative PowerAxis DomTremorPowerAxis FreqPeak ... - PSDTremorFeatures PSDHighTremorFeatures PowerArmActv PowerHighFreq MelCepsCoeff]; - - %% Write TSDF output - - % Save data - data_tsdf{1} = int64(WinDateTime); - data_tsdf{2} = TremorProb; - data_tsdf{3} = [int64(TremorHat) int64(RestTremorHat)]; - data_tsdf{4} = FeaturesTremor.Variables; - - % Save metadata - metafile_template = metadata_list{1}; - - start_time_iso = datetime(WinDateTime(1)/unix_ticks_ms, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss Z', 'TimeZone', 'UTC'); - end_time_iso = datetime(WinDateTime(end)/unix_ticks_ms+1, "ConvertFrom", "posixtime", 'Format', 'dd-MMM-yyyy HH:mm:ss Z', 'TimeZone', 'UTC'); - - metafile_template.start_iso8601 = datestr(start_time_iso); - metafile_template.end_iso8601 = datestr(end_time_iso); - metafile_template.freq_sampling_original = Fs_aprox; - metafile_template.freq_sampling_adjusted = Fs; - - metafile_time = metafile_template; - metafile_prob = metafile_template; - metafile_label = metafile_template; - metafile_features = metafile_template; - metafile_imu_proc = metafile_template; - - metafile_time.channels = {'time'}; - metafile_time.units = {'time_absolute_unix_ms'}; - metafile_time.file_name = 'Tremor_time.bin'; - - metafile_prob.channels = {'tremor probability'}; - metafile_prob.units = {'probability'}; - metafile_prob.file_name = 'Tremor_prob.bin'; - - metafile_label.channels = {'tremor label', 'rest tremor label'}; - metafile_label.units = {'boolean','boolean'}; - metafile_label.file_name = 'Tremor_label.bin'; - - metafile_features.channels = FeaturesTremor.Properties.VariableNames'; - metafile_features.units = {'deg/s^2','deg/s^2','deg/s^2','(deg/s)^2','(deg/s)^2','(deg/s)^2','(deg/s)^2','(deg/s)^2','(deg/s)^2',... - 'Hz','(deg/s)^2','Hz','(deg/s)^2','(deg/s)^2','Hz','(deg/s)^2','','','','','','','','','','','','','(deg/s)^2','(deg/s)^2'}; - metafile_features.file_name = 'Tremor_features.bin'; - - % Test plot - TimeVector = datetime(WinDateTime,'ConvertFrom','epochtime',... - 'TicksPerSecond',1e3,'Format','dd-MMM-yyyy HH:mm:ss'); - - figure; - plot(TimeVector,RestTremorHat); - xlabel('Date Time'); - ylabel('Rest Tremor Label'); - title('Rest tremor time-course'); - set(gca,'fontsize',18,'fontweight','bold','linewidth',2); - - meta_tsdf{1} = metafile_time; - meta_tsdf{2} = metafile_prob; - meta_tsdf{3} = metafile_label; - meta_tsdf{4} = metafile_features; - - mat_metadata_file_name = "Tremor_features_meta.json"; - save_tsdf_data({meta_tsdf{1,[1,4]}}, {data_tsdf{1,[1,4]}}, location, mat_metadata_file_name); - - mat_metadata_file_name = "Tremor_predictions_meta.json"; - save_tsdf_data({meta_tsdf{1,[1,2,3]}}, {data_tsdf{1,[1,2,3]}}, location, mat_metadata_file_name); - - % Saving the matlab struct as a check - PPP.ID = ppp_pep_userid; - PPP.Week = week_id; - PPP.Features = FeaturesTremor; - PPP.WinDateTime = WinDateTime; - PPP.ArmActvPower = FeaturesTremor.GyArmActvPower; - PPP.TremorProb = TremorProb; - PPP.TremorHat = TremorHat; - PPP.RestTremorHat = RestTremorHat; - - % Set here your location - % save('Z:\Diogo\Snellius Pipeline\Vedran - CheckPoint\Rest-Tremor---PPP-library\Test\FeatureVector','PPP'); - -end diff --git a/src/paradigma/ppg/classifier/LR_PPG_quality.pkl b/src/paradigma/ppg/classifier/LR_PPG_quality.pkl deleted file mode 100644 index e62af52f..00000000 Binary files a/src/paradigma/ppg/classifier/LR_PPG_quality.pkl and /dev/null differ diff --git a/src/paradigma/ppg/classifier/LR_model.mat b/src/paradigma/ppg/classifier/LR_model.mat deleted file mode 100644 index 7fbd9b63..00000000 Binary files a/src/paradigma/ppg/classifier/LR_model.mat and /dev/null differ diff --git a/src/paradigma/ppg/feat_extraction/acc_feature.m b/src/paradigma/ppg/feat_extraction/acc_feature.m deleted file mode 100644 index 403586f6..00000000 --- a/src/paradigma/ppg/feat_extraction/acc_feature.m +++ /dev/null @@ -1,20 +0,0 @@ -function acc_power_ratio = acc_feature(f1, PSD_acc, f2, PSD_ppg) - % This function calculates the power ratio of the accelerometer signal in the PPG frequency range. - % The power ratio is defined as the ratio of the power in the PPG frequency range to the total power. - [~, max_PPG_psd_idx] = max(PSD_ppg); - max_PPG_freq_psd = f2(max_PPG_psd_idx); - - %%---check dominant frequency (df) indices----%% - [~, corr_acc_psd_df_idx] = min(abs(max_PPG_freq_psd-f1)); - - df_idx = corr_acc_psd_df_idx-1:corr_acc_psd_df_idx+1; - - %%---check first harmonic (fh) frequency indices----%% - [~, corr_acc_psd_fh_idx] = min(abs(max_PPG_freq_psd*2-f1)); - fh_idx = corr_acc_psd_fh_idx-1:corr_acc_psd_fh_idx+1; - - %%---calculate power ratio---%% - acc_power_PPG_range = trapz(f1(df_idx), PSD_acc(df_idx)) + trapz(f1(fh_idx), PSD_acc(fh_idx)); - acc_power_total = trapz(f1, PSD_acc); - - acc_power_ratio = acc_power_PPG_range/acc_power_total; \ No newline at end of file diff --git a/src/paradigma/ppg/feat_extraction/peakdet.m b/src/paradigma/ppg/feat_extraction/peakdet.m deleted file mode 100644 index e170df7f..00000000 --- a/src/paradigma/ppg/feat_extraction/peakdet.m +++ /dev/null @@ -1,64 +0,0 @@ -function [maxtab, mintab]=peakdet(v, delta, x) -%PEAKDET Detect peaks in a vector -% [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local -% maxima and minima ("peaks") in the vector V. -% MAXTAB and MINTAB consists of two columns. Column 1 -% contains indices in V, and column 2 the found values. -% -% With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices -% in MAXTAB and MINTAB are replaced with the corresponding -% X-values. -% -% A point is considered a maximum peak if it has the maximal -% value, and was preceded (to the left) by a value lower by -% DELTA. - -% Eli Billauer, 3.4.05 -% This function is released to the public domain; Any use is allowed. - -maxtab = []; -mintab = []; - -v = v(:); % Just in case this wasn't a proper vector - -if nargin < 3 - x = (1:length(v))'; -else - x = x(:); - if length(v)~= length(x) - error('Input vectors v and x must have same length'); - end -end - -if (length(delta(:)))>1 - error('Input argument DELTA must be a scalar'); -end - -if delta <= 0 - error('Input argument DELTA must be positive'); -end - -mn = Inf; mx = -Inf; -mnpos = NaN; mxpos = NaN; - -lookformax = 1; - -for i=1:length(v) - this = v(i); - if this > mx, mx = this; mxpos = x(i); end - if this < mn, mn = this; mnpos = x(i); end - - if lookformax - if this < mx-delta - maxtab = [maxtab ; mxpos mx]; - mn = this; mnpos = x(i); - lookformax = 0; - end - else - if this > mn+delta - mintab = [mintab ; mnpos mn]; - mx = this; mxpos = x(i); - lookformax = 1; - end - end -end \ No newline at end of file diff --git a/src/paradigma/ppg/feat_extraction/ppg_features.m b/src/paradigma/ppg/feat_extraction/ppg_features.m deleted file mode 100644 index 39a8b9b1..00000000 --- a/src/paradigma/ppg/feat_extraction/ppg_features.m +++ /dev/null @@ -1,53 +0,0 @@ -function [FeaturesPPG] = ppg_features(PPG,fs) - % extract features from the PPG signal, per 6sec window (PPG input is a 6sec window of PPG signal) - N_feat = 10; - FeaturesPPG = zeros(1, N_feat); - % Time-domain features - absPPG = abs(PPG); - FeaturesPPG(1) = var(PPG); % Feature 1: variance - FeaturesPPG(2) = mean(absPPG); % Feature 2: mean - FeaturesPPG(3) = median(absPPG); % Feature 3: median - FeaturesPPG(4) = kurtosis(PPG); % Feature 4: kurtosis - FeaturesPPG(5) = skewness(PPG); % Feature 5: skewness - - window = 3*fs; % 90 samples for Welch's method => fr = 2/3 = 0.67 Hz --> not an issue with a clear distinct frequency - overlap = 0.5*window; % 45 samples overlap for Welch's Method - - [P, f] = pwelch(PPG, window, overlap, [], fs); - - % Find the dominant frequency - [~, maxIndex] = max(P); - FeaturesPPG(6) = f(maxIndex); % Feature 6: dominant frequency - - ph_idx = find(f >= 0.75 & f <= 3); % find indices of f in relevant physiological heart range 45-180 bpm - [~, maxIndex_ph] = max(P(ph_idx)); % Index of dominant frequency - dominantFrequency_ph = f(ph_idx(maxIndex_ph)); % Extract dominant frequency - f_dom_band = find(f >= dominantFrequency_ph - 0.2 & f <= dominantFrequency_ph + 0.2); % - FeaturesPPG(7) = trapz(P(f_dom_band))/trapz(P); % Feature 7 = relative power - - - % Normalize the power spectrum - pxx_norm = P / sum(P); - - % Compute spectral entropy - FeaturesPPG(8) = -sum(pxx_norm .* log2(pxx_norm))/log2(length(PPG)); % Feature 8 = spectral entropy --> normalize between 0 and 1! Or should we perform this operation at the min-max normalization! No because the values can come from different lengths! - - % Signal to noise ratio - Signal = var(PPG); - Noise = var(absPPG); - FeaturesPPG(9) = Signal/Noise; % Feature 9 = surrogate of signal to noise ratio - - %% Autocorrelation features - - [acf, ~] = autocorr(PPG, 'NumLags', fs*3); % Compute the autocorrelation of the PPG signal with a maximum lag of 3 seconds (or 3 time the sampling rate) - [peakValues, ~] = peakdet(acf, 0.01); - sortedValues = sort(peakValues(:,2), 'descend'); % sort the peaks found in the corellogram - if length(sortedValues) > 1 - FeaturesPPG(10) = sortedValues(2); % determine the second peak as the highest peak after the peak at lag=0, the idea is to determine the periodicity of the signal - else - FeaturesPPG(10) = 0; % Set at 0 if there is no clear second peak - end - - - - \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/extract_hr_segments.m b/src/paradigma/ppg/glob_functions/extract_hr_segments.m deleted file mode 100644 index d4bdbbaa..00000000 --- a/src/paradigma/ppg/glob_functions/extract_hr_segments.m +++ /dev/null @@ -1,37 +0,0 @@ -function [start_idx, end_idx] = extract_hr_segments(label_arr, threshold) -% Function which calculates the switches between high and low quality. It -% calculates the length of the high quality parts and returns the correct -% data indices for every high quality part longer than a specific threshold! -% Input: -% - labelArray: Label array containin of 0 (low-quality) and 1 (high-quality) -% - threshold: minimal required length for HR analysis (f.e. 30s = 30*fs= -% 900 samples - - start_idx = []; - end_idx = []; - - label_arr = [0; label_arr; 0]; % padding to find switches if the label starts or ends with high quality label! - - % Find switches from 0 to 1 - zero_one_switch = find(diff(label_arr) == 1); - - % Find switches from 1 to 0 - one_zero_switch = find(diff(label_arr) == -1); - - % Ensure the lengths are the same - if length(zero_one_switch) ~= length(one_zero_switch) - error('Invalid label array'); - end - - % Calculate switch lengths for label 1 - switch_lengths = one_zero_switch - zero_one_switch; - - % Find switch lengths greater than the threshold - long_switches = find(switch_lengths >= threshold); - - % Assign start and end indices for long switches - for i = 1:length(long_switches) - start_idx(i) = zero_one_switch(long_switches(i)); - end_idx(i) = one_zero_switch(long_switches(i))-1; - end -end \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/extract_overlapping_segments.m b/src/paradigma/ppg/glob_functions/extract_overlapping_segments.m deleted file mode 100644 index 6e9d9b02..00000000 --- a/src/paradigma/ppg/glob_functions/extract_overlapping_segments.m +++ /dev/null @@ -1,23 +0,0 @@ -function [ppg_indices, imu_indices] = extract_overlapping_segments(t_unix_ppg, t_unix_imu) - % K.I. Veldkamp, PhD student AI4P, 29-02-24 - % Function to extract indices indicating overlapping data between IMU and - % PPG segment - - % Convert UNIX milliseconds to seconds - ppg_time = t_unix_ppg / 1000; % Convert milliseconds to seconds - imu_time = t_unix_imu / 1000; % Convert milliseconds to seconds - - % Determine the overlapping time interval - start_time = max(ppg_time(1), imu_time(1)); - end_time = min(ppg_time(end), imu_time(end)); - - % Convert overlapping time interval to indices - ppg_start_index = find(ppg_time >= start_time, 1); - ppg_end_index = find(ppg_time <= end_time, 1, 'last'); - imu_start_index = find(imu_time >= start_time, 1); - imu_end_index = find(imu_time <= end_time, 1, 'last'); - - % Extract overlapping segments - ppg_indices = [ppg_start_index, ppg_end_index]; - imu_indices = [imu_start_index, imu_end_index]; - end \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/jsonlab/AUTHORS.txt b/src/paradigma/ppg/glob_functions/jsonlab/AUTHORS.txt deleted file mode 100644 index 9dd3fc7b..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/AUTHORS.txt +++ /dev/null @@ -1,41 +0,0 @@ -The author of "jsonlab" toolbox is Qianqian Fang. Qianqian -is currently an Assistant Professor at Massachusetts General Hospital, -Harvard Medical School. - -Address: Martinos Center for Biomedical Imaging, - Massachusetts General Hospital, - Harvard Medical School - Bldg 149, 13th St, Charlestown, MA 02129, USA -URL: http://nmr.mgh.harvard.edu/~fangq/ -Email: or - - -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 diff --git a/src/paradigma/ppg/glob_functions/jsonlab/ChangeLog.txt b/src/paradigma/ppg/glob_functions/jsonlab/ChangeLog.txt deleted file mode 100644 index 07824f5c..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/ChangeLog.txt +++ /dev/null @@ -1,74 +0,0 @@ -============================================================================ - - JSONlab - a toolbox to encode/decode JSON/UBJSON files in MATLAB/Octave - ----------------------------------------------------------------------------- - -JSONlab ChangeLog (key features marked by *): - -== JSONlab 1.0 (codename: Optimus - Final), FangQ == - - 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 == - - 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 == - - 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 == - - 2014/01/22 use binary read and write in saveubjson and loadubjson - -== JSONlab 0.9.8-1 (codename: Optimus - alpha update 1), FangQ == - - 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 == - 2013/08/23 *universal Binary JSON (UBJSON) support, including both saveubjson and loadubjson - -== JSONlab 0.9.1 (codename: Rodimus, update 1), FangQ == - 2012/12/18 *handling of various empty and sparse matrices (fixes submitted by Niclas Borlin) - -== JSONlab 0.9.0 (codename: Rodimus), FangQ == - - 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 == - - 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 == - - 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 == - - 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 == - - 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/src/paradigma/ppg/glob_functions/jsonlab/LICENSE_BSD.txt b/src/paradigma/ppg/glob_functions/jsonlab/LICENSE_BSD.txt deleted file mode 100644 index 32d66cbc..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/LICENSE_BSD.txt +++ /dev/null @@ -1,25 +0,0 @@ -Copyright 2011-2015 Qianqian Fang . 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/src/paradigma/ppg/glob_functions/jsonlab/LICENSE_GPLv3.txt b/src/paradigma/ppg/glob_functions/jsonlab/LICENSE_GPLv3.txt deleted file mode 100644 index 210f625a..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/LICENSE_GPLv3.txt +++ /dev/null @@ -1,699 +0,0 @@ -=============================================================================== -= JSONlab = -= An open-source MATLAB/Octave JSON encoder and decoder = -=============================================================================== - -Copyright (C) 2011-2015 Qianqian Fang - -------------------------------------------------------------------------------- - -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/src/paradigma/ppg/glob_functions/jsonlab/README.txt b/src/paradigma/ppg/glob_functions/jsonlab/README.txt deleted file mode 100644 index 20688898..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/README.txt +++ /dev/null @@ -1,394 +0,0 @@ -=============================================================================== -= JSONLab = -= An open-source MATLAB/Octave JSON encoder and decoder = -=============================================================================== - -*Copyright (C) 2011-2015 Qianqian Fang -*License: BSD or GNU General Public License version 3 (GPL v3), see License*.txt -*Version: 1.0 (Optimus - Final) - -------------------------------------------------------------------------------- - -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 (fangq nmr.mgh.harvard.edu)
-  created on 2011/09/09, including previous works from 
- 
-          Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
-             created on 2009/11/02
-          Franois Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
-             created on  2009/03/22
-          Joel Feenstra:
-          http://www.mathworks.com/matlabcentral/fileexchange/20565
-             created on 2008/07/03
- 
-  $Id: loadjson.m 452 2014-11-22 16:43:33Z fangq $
- 
-  input:
-       fname: input file name, if fname contains "{}" or "[]", fname
-              will be interpreted as a JSON string
-       opt: a struct to store parsing options, opt can be replaced by 
-            a list of ('param',value) pairs - the param string is equivallent
-            to a field in opt. opt can have the following 
-            fields (first in [.|.] is the default)
- 
-            opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
-                          for each element of the JSON data, and group 
-                          arrays based on the cell2mat rules.
-            opt.FastArrayParser [1|0 or integer]: if set to 1, use a
-                          speed-optimized array parser when loading an 
-                          array object. The fast array parser may 
-                          collapse block arrays into a single large
-                          array similar to rules defined in cell2mat; 0 to 
-                          use a legacy parser; if set to a larger-than-1
-                          value, this option will specify the minimum
-                          dimension to enable the fast array parser. For
-                          example, if the input is a 3D array, setting
-                          FastArrayParser to 1 will return a 3D array;
-                          setting to 2 will return a cell array of 2D
-                          arrays; setting to 3 will return to a 2D cell
-                          array of 1D vectors; setting to 4 will return a
-                          3D cell array.
-            opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
- 
-  output:
-       dat: a cell array, where {...} blocks are converted into cell arrays,
-            and [...] are converted to arrays
- 
-  examples:
-       dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
-       dat=loadjson(['examples' filesep 'example1.json'])
-       dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
-
- -=== 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 (fangq nmr.mgh.harvard.edu)
-  created on 2011/09/09
- 
-  $Id: savejson.m 458 2014-12-19 22:17:17Z fangq $
- 
-  input:
-       rootname: the name of the root-object, when set to '', the root name
-         is ignored, however, when opt.ForceRootName is set to 1 (see below),
-         the MATLAB variable name will be used as the root name.
-       obj: a MATLAB object (array, cell, cell array, struct, struct array).
-       filename: a string for the file name to save the output JSON data.
-       opt: a struct for additional options, ignore to use default values.
-         opt can have the following fields (first in [.|.] is the default)
- 
-         opt.FileName [''|string]: a file name to save the output JSON data
-         opt.FloatFormat ['%.10g'|string]: format to show each numeric element
-                          of a 1D/2D array;
-         opt.ArrayIndent [1|0]: if 1, output explicit data array with
-                          precedent indentation; if 0, no indentation
-         opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
-                          array in JSON array format; if sets to 1, an
-                          array will be shown as a struct with fields
-                          "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
-                          sparse arrays, the non-zero elements will be
-                          saved to _ArrayData_ field in triplet-format i.e.
-                          (ix,iy,val) and "_ArrayIsSparse_" will be added
-                          with a value of 1; for a complex array, the 
-                          _ArrayData_ array will include two columns 
-                          (4 for sparse) to record the real and imaginary 
-                          parts, and also "_ArrayIsComplex_":1 is added. 
-         opt.ParseLogical [0|1]: if this is set to 1, logical array elem
-                          will use true/false rather than 1/0.
-         opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
-                          numerical element will be shown without a square
-                          bracket, unless it is the root object; if 0, square
-                          brackets are forced for any numerical arrays.
-         opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
-                          will use the name of the passed obj variable as the 
-                          root object name; if obj is an expression and 
-                          does not have a name, 'root' will be used; if this 
-                          is set to 0 and rootname is empty, the root level 
-                          will be merged down to the lower level.
-         opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
-                          to represent +/-Inf. The matched pattern is '([-+]*)Inf'
-                          and $1 represents the sign. For those who want to use
-                          1e999 to represent Inf, they can set opt.Inf to '$11e999'
-         opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
-                          to represent NaN
-         opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
-                          for example, if opt.JSONP='foo', the JSON data is
-                          wrapped inside a function call as 'foo(...);'
-         opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson 
-                          back to the string form
-         opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
-         opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
- 
-         opt can be replaced by a list of ('param',value) pairs. The param 
-         string is equivallent to a field in opt and is case sensitive.
-  output:
-       json: a string in the JSON format (see http://json.org)
- 
-  examples:
-       jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... 
-                'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
-                'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
-                           2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
-                'MeshCreator','FangQ','MeshTitle','T6 Cube',...
-                'SpecialData',[nan, inf, -inf]);
-       savejson('jmesh',jsonmesh)
-       savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
- 
- -=== 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 (fangq nmr.mgh.harvard.edu)
-  created on 2013/08/01
- 
-  $Id: loadubjson.m 436 2014-08-05 20:51:40Z fangq $
- 
-  input:
-       fname: input file name, if fname contains "{}" or "[]", fname
-              will be interpreted as a UBJSON string
-       opt: a struct to store parsing options, opt can be replaced by 
-            a list of ('param',value) pairs - the param string is equivallent
-            to a field in opt. opt can have the following 
-            fields (first in [.|.] is the default)
- 
-            opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
-                          for each element of the JSON data, and group 
-                          arrays based on the cell2mat rules.
-            opt.IntEndian [B|L]: specify the endianness of the integer fields
-                          in the UBJSON input data. B - Big-Endian format for 
-                          integers (as required in the UBJSON specification); 
-                          L - input integer fields are in Little-Endian order.
- 
-  output:
-       dat: a cell array, where {...} blocks are converted into cell arrays,
-            and [...] are converted to arrays
- 
-  examples:
-       obj=struct('string','value','array',[1 2 3]);
-       ubjdata=saveubjson('obj',obj);
-       dat=loadubjson(ubjdata)
-       dat=loadubjson(['examples' filesep 'example1.ubj'])
-       dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
-
- -=== 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 (fangq nmr.mgh.harvard.edu)
-  created on 2013/08/17
- 
-  $Id: saveubjson.m 440 2014-09-17 19:59:45Z fangq $
- 
-  input:
-       rootname: the name of the root-object, when set to '', the root name
-         is ignored, however, when opt.ForceRootName is set to 1 (see below),
-         the MATLAB variable name will be used as the root name.
-       obj: a MATLAB object (array, cell, cell array, struct, struct array)
-       filename: a string for the file name to save the output UBJSON data
-       opt: a struct for additional options, ignore to use default values.
-         opt can have the following fields (first in [.|.] is the default)
- 
-         opt.FileName [''|string]: a file name to save the output JSON data
-         opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
-                          array in JSON array format; if sets to 1, an
-                          array will be shown as a struct with fields
-                          "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
-                          sparse arrays, the non-zero elements will be
-                          saved to _ArrayData_ field in triplet-format i.e.
-                          (ix,iy,val) and "_ArrayIsSparse_" will be added
-                          with a value of 1; for a complex array, the 
-                          _ArrayData_ array will include two columns 
-                          (4 for sparse) to record the real and imaginary 
-                          parts, and also "_ArrayIsComplex_":1 is added. 
-         opt.ParseLogical [1|0]: if this is set to 1, logical array elem
-                          will use true/false rather than 1/0.
-         opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single
-                          numerical element will be shown without a square
-                          bracket, unless it is the root object; if 0, square
-                          brackets are forced for any numerical arrays.
-         opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
-                          will use the name of the passed obj variable as the 
-                          root object name; if obj is an expression and 
-                          does not have a name, 'root' will be used; if this 
-                          is set to 0 and rootname is empty, the root level 
-                          will be merged down to the lower level.
-         opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
-                          for example, if opt.JSON='foo', the JSON data is
-                          wrapped inside a function call as 'foo(...);'
-         opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson 
-                          back to the string form
- 
-         opt can be replaced by a list of ('param',value) pairs. The param 
-         string is equivallent to a field in opt and is case sensitive.
-  output:
-       json: a binary string in the UBJSON format (see http://ubjson.org)
- 
-  examples:
-       jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... 
-                'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
-                'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
-                           2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
-                'MeshCreator','FangQ','MeshTitle','T6 Cube',...
-                'SpecialData',[nan, inf, -inf]);
-       saveubjson('jsonmesh',jsonmesh)
-       saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
-
- - -=== 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 pairs 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 it's subversion repository by using the -following command: - - 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 - - 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 iso2mesh's -mailing list to report any questions you may have with JSONLab: - -http://groups.google.com/group/iso2mesh-users?hl=en&pli=1 - -(Subscription to the mailing list is needed in order to post messages). diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/entries b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/entries deleted file mode 100644 index e9863ff8..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/entries +++ /dev/null @@ -1,368 +0,0 @@ -10 - -dir -461 -svn://svn.code.sf.net/p/iso2mesh/code/trunk/jsonlab/examples -svn://svn.code.sf.net/p/iso2mesh/code - - - -2014-12-19T22:17:17.588936Z -458 -fangq - - - - - - - - - - - - - - -786e58fb-9377-0410-9ff7-e4ac0ac0635c - -example3.json -file - - - - -2015-01-03T04:20:29.256062Z -e6b003f8ee84d86aba88e14c01b07fc7 -2012-02-28T19:02:09.069024Z -358 -fangq - - - - - - - - - - - - - - - - - - - - - -256 - -example4.json -file - - - - -2015-01-03T04:20:29.260062Z -a4b38b1880e47cbb0769142ba91fc794 -2011-11-20T23:24:44.699088Z -328 -fangq - - - - - - - - - - - - - - - - - - - - - -500 - -demo_jsonlab_basic.m -file - - - - -2015-01-03T04:20:29.260062Z -5d259fcb8b5162c33794139a0c938e9b -2014-09-15T18:59:36.423526Z -437 -fangq - - - - - - - - - - - - - - - - - - - - - -6414 - -jsonlab_basictest.matlab -file - - - - -2015-01-03T04:20:29.260062Z -5d6e43bb6d4444a496e29f17ec57dd5e -2014-12-19T22:17:17.588936Z -458 -fangq - - - - - - - - - - - - - - - - - - - - - -9973 - -jsonlab_selftest.m -file - - - - -2015-01-03T04:20:29.260062Z -b3c2fb061defb8ccb6d30c4c08da26ce -2014-11-18T20:53:31.695652Z -450 -fangq - - - - - - - - - - - - - - - - - - - - - -995 - -demo_ubjson_basic.m -file - - - - -2015-01-03T04:20:29.252062Z -47b39a73fb8a3027f2d57964fb6a71ed -2014-09-17T04:09:49.677992Z -438 -fangq - - - - - - - - - - - - - - - - - - - - - -6517 - -jsonlab_selftest.matlab -file - - - - -2015-01-03T04:20:29.252062Z -141fc287d6f343f00f7b966dc0d6a28f -2014-11-23T17:37:18.671649Z -454 -fangq - - - - - - - - - - - - - - - - - - - - - -4131 - -jsonlab_speedtest.m -file - - - - -2015-01-03T04:20:29.256062Z -0d4adef6414ffa3958fa3df0503a28b7 -2011-10-24T22:58:20.295860Z -319 -fangq - - - - - - - - - - - - - - - - - - - - - -675 - -example1.json -file - - - - -2015-01-03T04:20:29.256062Z -5867f865b1708e5c9eb3a22211ffc914 -2011-10-11T22:30:21.329885Z -310 -fangq - - - - - - - - - - - - - - - - - - - - - -436 - -example2.json -file - - - - -2015-01-03T04:20:29.256062Z -ef38b0c11d9f8eed7e016fbf9d21de38 -2011-10-11T22:30:21.329885Z -310 -fangq - - - - - - - - - - - - - - - - - - - - - -583 - diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/demo_jsonlab_basic.m.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/demo_jsonlab_basic.m.svn-base deleted file mode 100644 index 43d70665..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/demo_jsonlab_basic.m.svn-base +++ /dev/null @@ -1,180 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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) - -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/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/demo_ubjson_basic.m.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/demo_ubjson_basic.m.svn-base deleted file mode 100644 index 0c35433a..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/demo_ubjson_basic.m.svn-base +++ /dev/null @@ -1,180 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example1.json.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example1.json.svn-base deleted file mode 100644 index be0993ef..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example1.json.svn-base +++ /dev/null @@ -1,23 +0,0 @@ - { - "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/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example2.json.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example2.json.svn-base deleted file mode 100644 index eacfbf5e..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example2.json.svn-base +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example3.json.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example3.json.svn-base deleted file mode 100644 index b7ca9411..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example3.json.svn-base +++ /dev/null @@ -1,11 +0,0 @@ -{"menu": { - "id": "file", - "value": "_&File", - "popup": { - "menuitem": [ - {"value": "_&New", "onclick": "CreateNewDoc(\"\"\")"}, - {"value": "_&Open", "onclick": "OpenDoc()"}, - {"value": "_&Close", "onclick": "CloseDoc()"} - ] - } -}} diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example4.json.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example4.json.svn-base deleted file mode 100644 index 66deeafb..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/example4.json.svn-base +++ /dev/null @@ -1,34 +0,0 @@ -[ - { - "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" - ] -] diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_basictest.matlab.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_basictest.matlab.svn-base deleted file mode 100644 index d51ba96c..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_basictest.matlab.svn-base +++ /dev/null @@ -1,662 +0,0 @@ - - < M A T L A B > - Copyright 1984-2007 The MathWorks, Inc. - Version 7.4.0.287 (R2007a) - January 29, 2007 - - - 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": { - "_ArrayType_": "double", - "_ArraySize_": [0,0], - "_ArrayData_": 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] - ->> >> -%================================================= ->> % 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: {{1x3 cell}} - ->> >> -%================================================= ->> % 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 - ] - ], - 7 - ], - [ - [ - 4, - 5 - ], - [ - 8, - 9 - ] - ], - [ - 6, - 10 - ] - ] -} - - ->> -json2data = - - data2json: {{1x2 cell} [2x2 double] [6 10]} - ->> >> -%================================================= ->> % 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/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_selftest.m.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_selftest.m.svn-base deleted file mode 100644 index 27aee244..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_selftest.m.svn-base +++ /dev/null @@ -1,27 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_selftest.matlab.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_selftest.matlab.svn-base deleted file mode 100644 index 17e2d4b8..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_selftest.matlab.svn-base +++ /dev/null @@ -1,144 +0,0 @@ - - < M A T L A B > - Copyright 1984-2007 The MathWorks, Inc. - Version 7.4.0.287 (R2007a) - January 29, 2007 - - - 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(\"\"\")" - }, - { - "value": "_&Open", - "onclick": "OpenDoc()" - }, - { - "value": "_&Close", - "onclick": "CloseDoc()" - } - ] - } - } - } -} - -{"data": {"menu": {"id": "file","value": "_&File","popup": {"menuitem": [{"value": "_&New","onclick": "CreateNewDoc(\"\"\")"},{"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" - ] - ] -} - -{"data": [{"sample": {"rho": 1}},{"sample": {"rho": 2}},[[1,0],[1,1],[1,2]],["Paper","Scissors","Stone"]]} - ->> >> =============================================== ->> example1.json -{SUdata{SU firstNameSUJohnSUlastNameSUSmithSUageiSUaddress{SU streetAddressSU 21 2nd StreetSUcitySUNew YorkSUstateSUNYSU -postalCodeSU10021}SU phoneNumber[{SUtypeSUhomeSUnumberSU 212 555-1234}{SUtypeSUfaxSUnumberSU 646 555-4567}]}} -=============================================== ->> example2.json -{SUdata{SUglossary{SUtitleSUexample glossarySUGlossDiv{SUtitleCSSU GlossList{SU -GlossEntry{SUIDSUSGMLSUSortAsSUSGMLSU GlossTermSU$Standard Generalized Markup LanguageSUAcronymSUSGMLSUAbbrevSU ISO 8879:1986SUGlossDef{SUparaSUHA meta-markup language, used to create markup languages such as DocBook.SU GlossSeeAlso[SUGMLSUXML]}SUGlossSeeSUmarkup}}}}}} -=============================================== ->> example3.json -{SUdata{SUmenu{SUidSUfileSUvalueSU_&FileSUpopup{SUmenuitem[{SUvalueSU_&NewSUonclickSUCreateNewDoc(""")}{SUvalueSU_&OpenSUonclickSU OpenDoc()}{SUvalueSU_&CloseSUonclickSU -CloseDoc()}]}}}} -=============================================== ->> example4.json -{SUdata[{SUsample{SUrhoi}}{SUsample{SUrhoi}}[[$i#U ->> \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_speedtest.m.svn-base b/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_speedtest.m.svn-base deleted file mode 100644 index 4990fba0..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/.svn/text-base/jsonlab_speedtest.m.svn-base +++ /dev/null @@ -1,21 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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/src/paradigma/ppg/glob_functions/jsonlab/examples/demo_jsonlab_basic.m b/src/paradigma/ppg/glob_functions/jsonlab/examples/demo_jsonlab_basic.m deleted file mode 100644 index 43d70665..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/demo_jsonlab_basic.m +++ /dev/null @@ -1,180 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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) - -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/src/paradigma/ppg/glob_functions/jsonlab/examples/demo_ubjson_basic.m b/src/paradigma/ppg/glob_functions/jsonlab/examples/demo_ubjson_basic.m deleted file mode 100644 index 0c35433a..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/demo_ubjson_basic.m +++ /dev/null @@ -1,180 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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/src/paradigma/ppg/glob_functions/jsonlab/examples/example1.json b/src/paradigma/ppg/glob_functions/jsonlab/examples/example1.json deleted file mode 100644 index be0993ef..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/example1.json +++ /dev/null @@ -1,23 +0,0 @@ - { - "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/src/paradigma/ppg/glob_functions/jsonlab/examples/example2.json b/src/paradigma/ppg/glob_functions/jsonlab/examples/example2.json deleted file mode 100644 index eacfbf5e..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/example2.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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/src/paradigma/ppg/glob_functions/jsonlab/examples/example3.json b/src/paradigma/ppg/glob_functions/jsonlab/examples/example3.json deleted file mode 100644 index b7ca9411..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/example3.json +++ /dev/null @@ -1,11 +0,0 @@ -{"menu": { - "id": "file", - "value": "_&File", - "popup": { - "menuitem": [ - {"value": "_&New", "onclick": "CreateNewDoc(\"\"\")"}, - {"value": "_&Open", "onclick": "OpenDoc()"}, - {"value": "_&Close", "onclick": "CloseDoc()"} - ] - } -}} diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/example4.json b/src/paradigma/ppg/glob_functions/jsonlab/examples/example4.json deleted file mode 100644 index 66deeafb..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/example4.json +++ /dev/null @@ -1,34 +0,0 @@ -[ - { - "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" - ] -] diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_basictest.matlab b/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_basictest.matlab deleted file mode 100644 index d51ba96c..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_basictest.matlab +++ /dev/null @@ -1,662 +0,0 @@ - - < M A T L A B > - Copyright 1984-2007 The MathWorks, Inc. - Version 7.4.0.287 (R2007a) - January 29, 2007 - - - 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": { - "_ArrayType_": "double", - "_ArraySize_": [0,0], - "_ArrayData_": 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] - ->> >> -%================================================= ->> % 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: {{1x3 cell}} - ->> >> -%================================================= ->> % 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 - ] - ], - 7 - ], - [ - [ - 4, - 5 - ], - [ - 8, - 9 - ] - ], - [ - 6, - 10 - ] - ] -} - - ->> -json2data = - - data2json: {{1x2 cell} [2x2 double] [6 10]} - ->> >> -%================================================= ->> % 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/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_selftest.m b/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_selftest.m deleted file mode 100644 index 27aee244..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_selftest.m +++ /dev/null @@ -1,27 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_selftest.matlab b/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_selftest.matlab deleted file mode 100644 index 17e2d4b8..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_selftest.matlab +++ /dev/null @@ -1,144 +0,0 @@ - - < M A T L A B > - Copyright 1984-2007 The MathWorks, Inc. - Version 7.4.0.287 (R2007a) - January 29, 2007 - - - 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(\"\"\")" - }, - { - "value": "_&Open", - "onclick": "OpenDoc()" - }, - { - "value": "_&Close", - "onclick": "CloseDoc()" - } - ] - } - } - } -} - -{"data": {"menu": {"id": "file","value": "_&File","popup": {"menuitem": [{"value": "_&New","onclick": "CreateNewDoc(\"\"\")"},{"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" - ] - ] -} - -{"data": [{"sample": {"rho": 1}},{"sample": {"rho": 2}},[[1,0],[1,1],[1,2]],["Paper","Scissors","Stone"]]} - ->> >> =============================================== ->> example1.json -{SUdata{SU firstNameSUJohnSUlastNameSUSmithSUageiSUaddress{SU streetAddressSU 21 2nd StreetSUcitySUNew YorkSUstateSUNYSU -postalCodeSU10021}SU phoneNumber[{SUtypeSUhomeSUnumberSU 212 555-1234}{SUtypeSUfaxSUnumberSU 646 555-4567}]}} -=============================================== ->> example2.json -{SUdata{SUglossary{SUtitleSUexample glossarySUGlossDiv{SUtitleCSSU GlossList{SU -GlossEntry{SUIDSUSGMLSUSortAsSUSGMLSU GlossTermSU$Standard Generalized Markup LanguageSUAcronymSUSGMLSUAbbrevSU ISO 8879:1986SUGlossDef{SUparaSUHA meta-markup language, used to create markup languages such as DocBook.SU GlossSeeAlso[SUGMLSUXML]}SUGlossSeeSUmarkup}}}}}} -=============================================== ->> example3.json -{SUdata{SUmenu{SUidSUfileSUvalueSU_&FileSUpopup{SUmenuitem[{SUvalueSU_&NewSUonclickSUCreateNewDoc(""")}{SUvalueSU_&OpenSUonclickSU OpenDoc()}{SUvalueSU_&CloseSUonclickSU -CloseDoc()}]}}}} -=============================================== ->> example4.json -{SUdata[{SUsample{SUrhoi}}{SUsample{SUrhoi}}[[$i#U ->> \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_speedtest.m b/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_speedtest.m deleted file mode 100644 index 4990fba0..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/examples/jsonlab_speedtest.m +++ /dev/null @@ -1,21 +0,0 @@ -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% 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/src/paradigma/ppg/glob_functions/jsonlab/jsonopt.m b/src/paradigma/ppg/glob_functions/jsonlab/jsonopt.m deleted file mode 100644 index 4b541d33..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/jsonopt.m +++ /dev/null @@ -1,32 +0,0 @@ -function val=jsonopt(key,default,varargin) -% -% val=jsonopt(key,default,optstruct) -% -% setting options based on a struct. The struct can be produced -% by varargin2struct from a list of 'param','value' pairs -% -% authors:Qianqian Fang (fangq nmr.mgh.harvard.edu) -% -% $Id: loadjson.m 371 2012-06-20 12:43:06Z fangq $ -% -% input: -% key: a string with which one look up a value from a struct -% default: if the key does not exist, return default -% optstruct: a struct where each sub-field is a key -% -% output: -% val: if key exists, val=optstruct.key; otherwise val=default -% -% license: -% BSD 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) && isfield(opt,key)) - val=getfield(opt,key); -end - diff --git a/src/paradigma/ppg/glob_functions/jsonlab/loadjson.m b/src/paradigma/ppg/glob_functions/jsonlab/loadjson.m deleted file mode 100644 index 45166380..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/loadjson.m +++ /dev/null @@ -1,566 +0,0 @@ -function data = loadjson(fname,varargin) -% -% data=loadjson(fname,opt) -% or -% data=loadjson(fname,'param1',value1,'param2',value2,...) -% -% parse a JSON (JavaScript Object Notation) file or string -% -% authors:Qianqian Fang (fangq nmr.mgh.harvard.edu) -% created on 2011/09/09, including previous works from -% -% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713 -% created on 2009/11/02 -% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393 -% created on 2009/03/22 -% Joel Feenstra: -% http://www.mathworks.com/matlabcentral/fileexchange/20565 -% created on 2008/07/03 -% -% $Id: loadjson.m 460 2015-01-03 00:30:45Z fangq $ -% -% input: -% fname: input file name, if fname contains "{}" or "[]", fname -% will be interpreted as a JSON string -% opt: a struct to store parsing options, opt can be replaced by -% a list of ('param',value) pairs - the param string is equivallent -% to a field in opt. opt can have the following -% fields (first in [.|.] is the default) -% -% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat -% for each element of the JSON data, and group -% arrays based on the cell2mat rules. -% opt.FastArrayParser [1|0 or integer]: if set to 1, use a -% speed-optimized array parser when loading an -% array object. The fast array parser may -% collapse block arrays into a single large -% array similar to rules defined in cell2mat; 0 to -% use a legacy parser; if set to a larger-than-1 -% value, this option will specify the minimum -% dimension to enable the fast array parser. For -% example, if the input is a 3D array, setting -% FastArrayParser to 1 will return a 3D array; -% setting to 2 will return a cell array of 2D -% arrays; setting to 3 will return to a 2D cell -% array of 1D vectors; setting to 4 will return a -% 3D cell array. -% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar. -% -% output: -% dat: a cell array, where {...} blocks are converted into cell arrays, -% and [...] are converted to arrays -% -% examples: -% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}') -% dat=loadjson(['examples' filesep 'example1.json']) -% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1) -% -% license: -% BSD 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 - -if(regexp(fname,'[\{\}\]\[]','once')) - string=fname; -elseif(exist(fname,'file')) - fid = fopen(fname,'rb'); - string = fread(fid,inf,'uint8=>char')'; - fclose(fid); -else - error('input file does not exist'); -end - -pos = 1; len = length(string); inStr = string; -isoct=exist('OCTAVE_VERSION','builtin'); -arraytoken=find(inStr=='[' | inStr==']' | inStr=='"'); -jstr=regexprep(inStr,'\\\\',' '); -escquote=regexp(jstr,'\\"'); -arraytoken=sort([arraytoken escquote]); - -% String delimiters and escape chars identified to improve speed: -esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]'); -index_esc = 1; len_esc = length(esc); - -opt=varargin2struct(varargin{:}); - -if(jsonopt('ShowProgress',0,opt)==1) - opt.progressbar_=waitbar(0,'loading ...'); -end -jsoncount=1; -while pos <= len - switch(next_char) - case '{' - data{jsoncount} = parse_object(opt); - case '[' - data{jsoncount} = parse_array(opt); - otherwise - error_pos('Outer level structure must be an object or an array'); - end - jsoncount=jsoncount+1; -end % while - -jsoncount=length(data); -if(jsoncount==1 && iscell(data)) - data=data{1}; -end - -if(~isempty(data)) - if(isstruct(data)) % data can be a struct array - data=jstruct2array(data); - elseif(iscell(data)) - data=jcell2array(data); - end -end -if(isfield(opt,'progressbar_')) - close(opt.progressbar_); -end - -%% -function newdata=jcell2array(data) -len=length(data); -newdata=data; -for i=1:len - if(isstruct(data{i})) - newdata{i}=jstruct2array(data{i}); - elseif(iscell(data{i})) - newdata{i}=jcell2array(data{i}); - end -end - -%%------------------------------------------------------------------------- -function newdata=jstruct2array(data) -fn=fieldnames(data); -newdata=data; -len=length(data); -for i=1:length(fn) % depth-first - for j=1:len - if(isstruct(getfield(data(j),fn{i}))) - newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); - end - end -end -if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) - newdata=cell(len,1); - for j=1:len - ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); - iscpx=0; - if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) - if(data(j).x0x5F_ArrayIsComplex_) - iscpx=1; - end - end - if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) - if(data(j).x0x5F_ArrayIsSparse_) - if(~isempty(strmatch('x0x5F_ArraySize_',fn))) - dim=data(j).x0x5F_ArraySize_; - if(iscpx && size(ndata,2)==4-any(dim==1)) - ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); - end - if isempty(ndata) - % All-zeros sparse - ndata=sparse(dim(1),prod(dim(2:end))); - elseif dim(1)==1 - % Sparse row vector - ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); - elseif dim(2)==1 - % Sparse column vector - ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); - else - % Generic sparse array. - ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); - end - else - if(iscpx && size(ndata,2)==4) - ndata(:,3)=complex(ndata(:,3),ndata(:,4)); - end - ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); - end - end - elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) - if(iscpx && size(ndata,2)==2) - ndata=complex(ndata(:,1),ndata(:,2)); - end - ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); - end - newdata{j}=ndata; - end - if(len==1) - newdata=newdata{1}; - end -end - -%%------------------------------------------------------------------------- -function object = parse_object(varargin) - parse_char('{'); - object = []; - if next_char ~= '}' - while 1 - str = parseStr(varargin{:}); - if isempty(str) - error_pos('Name of value at position %d cannot be empty'); - end - parse_char(':'); - val = parse_value(varargin{:}); - eval( sprintf( 'object.%s = val;', valid_field(str) ) ); - if next_char == '}' - break; - end - parse_char(','); - end - end - parse_char('}'); - -%%------------------------------------------------------------------------- - -function object = parse_array(varargin) % JSON array is written in row-major order -global pos inStr isoct - parse_char('['); - object = cell(0, 1); - dim2=[]; - arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:}); - pbar=jsonopt('progressbar_',-1,varargin{:}); - - if next_char ~= ']' - if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:})) - [endpos, e1l, e1r, maxlevel]=matching_bracket(inStr,pos); - arraystr=['[' inStr(pos:endpos)]; - arraystr=regexprep(arraystr,'"_NaN_"','NaN'); - arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf'); - arraystr(arraystr==sprintf('\n'))=[]; - arraystr(arraystr==sprintf('\r'))=[]; - %arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed - if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D - astr=inStr((e1l+1):(e1r-1)); - astr=regexprep(astr,'"_NaN_"','NaN'); - astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf'); - astr(astr==sprintf('\n'))=[]; - astr(astr==sprintf('\r'))=[]; - astr(astr==' ')=''; - if(isempty(find(astr=='[', 1))) % array is 2D - dim2=length(sscanf(astr,'%f,',[1 inf])); - end - else % array is 1D - astr=arraystr(2:end-1); - astr(astr==' ')=''; - [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]); - if(nextidx>=length(astr)-1) - object=obj; - pos=endpos; - parse_char(']'); - return; - end - end - if(~isempty(dim2)) - astr=arraystr; - astr(astr=='[')=''; - astr(astr==']')=''; - astr(astr==' ')=''; - [obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf); - if(nextidx>=length(astr)-1) - object=reshape(obj,dim2,numel(obj)/dim2)'; - pos=endpos; - parse_char(']'); - if(pbar>0) - waitbar(pos/length(inStr),pbar,'loading ...'); - end - return; - end - end - arraystr=regexprep(arraystr,'\]\s*,','];'); - else - arraystr='['; - end - try - if(isoct && regexp(arraystr,'"','once')) - error('Octave eval can produce empty cells for JSON-like input'); - end - object=eval(arraystr); - pos=endpos; - catch - while 1 - newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1); - val = parse_value(newopt); - object{end+1} = val; - if next_char == ']' - break; - end - parse_char(','); - end - end - end - if(jsonopt('SimplifyCell',0,varargin{:})==1) - try - oldobj=object; - object=cell2mat(object')'; - if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) - object=oldobj; - elseif(size(object,1)>1 && ndims(object)==2) - object=object'; - end - catch - end - end - parse_char(']'); - - if(pbar>0) - waitbar(pos/length(inStr),pbar,'loading ...'); - end -%%------------------------------------------------------------------------- - -function parse_char(c) - global pos inStr len - skip_whitespace; - if pos > len || inStr(pos) ~= c - error_pos(sprintf('Expected %c at position %%d', c)); - else - pos = pos + 1; - skip_whitespace; - end - -%%------------------------------------------------------------------------- - -function c = next_char - global pos inStr len - skip_whitespace; - if pos > len - c = []; - else - c = inStr(pos); - end - -%%------------------------------------------------------------------------- - -function skip_whitespace - global pos inStr len - while pos <= len && isspace(inStr(pos)) - pos = pos + 1; - end - -%%------------------------------------------------------------------------- -function str = parseStr(varargin) - global pos inStr len esc index_esc len_esc - % len, ns = length(inStr), keyboard - if inStr(pos) ~= '"' - error_pos('String starting with " expected at position %d'); - else - pos = pos + 1; - end - str = ''; - while pos <= len - while index_esc <= len_esc && esc(index_esc) < pos - index_esc = index_esc + 1; - end - if index_esc > len_esc - str = [str inStr(pos:len)]; - pos = len + 1; - break; - else - str = [str inStr(pos:esc(index_esc)-1)]; - pos = esc(index_esc); - end - nstr = length(str); switch inStr(pos) - case '"' - pos = pos + 1; - if(~isempty(str)) - if(strcmp(str,'_Inf_')) - str=Inf; - elseif(strcmp(str,'-_Inf_')) - str=-Inf; - elseif(strcmp(str,'_NaN_')) - str=NaN; - end - end - return; - case '\' - if pos+1 > len - error_pos('End of file reached right after escape character'); - end - pos = pos + 1; - switch inStr(pos) - case {'"' '\' '/'} - str(nstr+1) = inStr(pos); - pos = pos + 1; - case {'b' 'f' 'n' 'r' 't'} - str(nstr+1) = sprintf(['\' inStr(pos)]); - pos = pos + 1; - case 'u' - if pos+4 > len - error_pos('End of file reached in escaped unicode character'); - end - str(nstr+(1:6)) = inStr(pos-1:pos+4); - pos = pos + 5; - end - otherwise % should never happen - str(nstr+1) = inStr(pos), keyboard - pos = pos + 1; - end - end - error_pos('End of file while expecting end of inStr'); - -%%------------------------------------------------------------------------- - -function num = parse_number(varargin) - global pos inStr len isoct - currstr=inStr(pos:end); - numstr=0; - if(isoct~=0) - numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end'); - [num, one] = sscanf(currstr, '%f', 1); - delta=numstr+1; - else - [num, one, err, delta] = sscanf(currstr, '%f', 1); - if ~isempty(err) - error_pos('Error reading number at position %d'); - end - end - pos = pos + delta-1; - -%%------------------------------------------------------------------------- - -function val = parse_value(varargin) - global pos inStr len - true = 1; false = 0; - - pbar=jsonopt('progressbar_',-1,varargin{:}); - if(pbar>0) - waitbar(pos/len,pbar,'loading ...'); - end - - switch(inStr(pos)) - case '"' - val = parseStr(varargin{:}); - return; - case '[' - val = parse_array(varargin{:}); - return; - case '{' - val = parse_object(varargin{:}); - if isstruct(val) - if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) - val=jstruct2array(val); - end - elseif isempty(val) - val = struct; - end - return; - case {'-','0','1','2','3','4','5','6','7','8','9'} - val = parse_number(varargin{:}); - return; - case 't' - if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true') - val = true; - pos = pos + 4; - return; - end - case 'f' - if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false') - val = false; - pos = pos + 5; - return; - end - case 'n' - if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null') - val = []; - pos = pos + 4; - return; - end - end - error_pos('Value expected at position %d'); -%%------------------------------------------------------------------------- - -function error_pos(msg) - global pos inStr len - poShow = max(min([pos-15 pos-1 pos pos+20],len),1); - if poShow(3) == poShow(2) - poShow(3:4) = poShow(2)+[0 -1]; % display nothing after - end - msg = [sprintf(msg, pos) ': ' ... - inStr(poShow(1):poShow(2)) '' 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/src/paradigma/ppg/glob_functions/jsonlab/loadubjson.m b/src/paradigma/ppg/glob_functions/jsonlab/loadubjson.m deleted file mode 100644 index b645517c..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/loadubjson.m +++ /dev/null @@ -1,528 +0,0 @@ -function data = loadubjson(fname,varargin) -% -% data=loadubjson(fname,opt) -% or -% data=loadubjson(fname,'param1',value1,'param2',value2,...) -% -% parse a JSON (JavaScript Object Notation) file or string -% -% authors:Qianqian Fang (fangq nmr.mgh.harvard.edu) -% created on 2013/08/01 -% -% $Id: loadubjson.m 460 2015-01-03 00:30:45Z fangq $ -% -% input: -% fname: input file name, if fname contains "{}" or "[]", fname -% will be interpreted as a UBJSON string -% opt: a struct to store parsing options, opt can be replaced by -% a list of ('param',value) pairs - the param string is equivallent -% to a field in opt. opt can have the following -% fields (first in [.|.] is the default) -% -% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat -% for each element of the JSON data, and group -% arrays based on the cell2mat rules. -% opt.IntEndian [B|L]: specify the endianness of the integer fields -% in the UBJSON input data. B - Big-Endian format for -% integers (as required in the UBJSON specification); -% L - input integer fields are in Little-Endian order. -% -% output: -% dat: a cell array, where {...} blocks are converted into cell arrays, -% and [...] are converted to arrays -% -% examples: -% obj=struct('string','value','array',[1 2 3]); -% ubjdata=saveubjson('obj',obj); -% dat=loadubjson(ubjdata) -% dat=loadubjson(['examples' filesep 'example1.ubj']) -% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1) -% -% license: -% BSD 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(varargin{:}); -fileendian=upper(jsonopt('IntEndian','B',opt)); -[os,maxelem,systemendian]=computer; - -jsoncount=1; -while pos <= len - switch(next_char) - case '{' - data{jsoncount} = parse_object(opt); - case '[' - data{jsoncount} = parse_array(opt); - otherwise - error_pos('Outer level structure must be an object or an array'); - end - jsoncount=jsoncount+1; -end % while - -jsoncount=length(data); -if(jsoncount==1 && iscell(data)) - data=data{1}; -end - -if(~isempty(data)) - if(isstruct(data)) % data can be a struct array - data=jstruct2array(data); - elseif(iscell(data)) - data=jcell2array(data); - end -end - - -%% -function newdata=parse_collection(id,data,obj) - -if(jsoncount>0 && exist('data','var')) - if(~iscell(data)) - newdata=cell(1); - newdata{1}=data; - data=newdata; - end -end - -%% -function newdata=jcell2array(data) -len=length(data); -newdata=data; -for i=1:len - if(isstruct(data{i})) - newdata{i}=jstruct2array(data{i}); - elseif(iscell(data{i})) - newdata{i}=jcell2array(data{i}); - end -end - -%%------------------------------------------------------------------------- -function newdata=jstruct2array(data) -fn=fieldnames(data); -newdata=data; -len=length(data); -for i=1:length(fn) % depth-first - for j=1:len - if(isstruct(getfield(data(j),fn{i}))) - newdata(j)=setfield(newdata(j),fn{i},jstruct2array(getfield(data(j),fn{i}))); - end - end -end -if(~isempty(strmatch('x0x5F_ArrayType_',fn)) && ~isempty(strmatch('x0x5F_ArrayData_',fn))) - newdata=cell(len,1); - for j=1:len - ndata=cast(data(j).x0x5F_ArrayData_,data(j).x0x5F_ArrayType_); - iscpx=0; - if(~isempty(strmatch('x0x5F_ArrayIsComplex_',fn))) - if(data(j).x0x5F_ArrayIsComplex_) - iscpx=1; - end - end - if(~isempty(strmatch('x0x5F_ArrayIsSparse_',fn))) - if(data(j).x0x5F_ArrayIsSparse_) - if(~isempty(strmatch('x0x5F_ArraySize_',fn))) - dim=double(data(j).x0x5F_ArraySize_); - if(iscpx && size(ndata,2)==4-any(dim==1)) - ndata(:,end-1)=complex(ndata(:,end-1),ndata(:,end)); - end - if isempty(ndata) - % All-zeros sparse - ndata=sparse(dim(1),prod(dim(2:end))); - elseif dim(1)==1 - % Sparse row vector - ndata=sparse(1,ndata(:,1),ndata(:,2),dim(1),prod(dim(2:end))); - elseif dim(2)==1 - % Sparse column vector - ndata=sparse(ndata(:,1),1,ndata(:,2),dim(1),prod(dim(2:end))); - else - % Generic sparse array. - ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3),dim(1),prod(dim(2:end))); - end - else - if(iscpx && size(ndata,2)==4) - ndata(:,3)=complex(ndata(:,3),ndata(:,4)); - end - ndata=sparse(ndata(:,1),ndata(:,2),ndata(:,3)); - end - end - elseif(~isempty(strmatch('x0x5F_ArraySize_',fn))) - if(iscpx && size(ndata,2)==2) - ndata=complex(ndata(:,1),ndata(:,2)); - end - ndata=reshape(ndata(:),data(j).x0x5F_ArraySize_); - end - newdata{j}=ndata; - end - if(len==1) - newdata=newdata{1}; - end -end - -%%------------------------------------------------------------------------- -function object = parse_object(varargin) - parse_char('{'); - object = []; - type=''; - count=-1; - if(next_char == '$') - type=inStr(pos+1); % TODO - pos=pos+2; - end - if(next_char == '#') - pos=pos+1; - count=double(parse_number()); - end - if next_char ~= '}' - num=0; - while 1 - str = parseStr(varargin{:}); - if isempty(str) - error_pos('Name of value at position %d cannot be empty'); - end - %parse_char(':'); - val = parse_value(varargin{:}); - num=num+1; - eval( sprintf( 'object.%s = val;', valid_field(str) ) ); - if next_char == '}' || (count>=0 && num>=count) - break; - end - %parse_char(','); - end - end - if(count==-1) - parse_char('}'); - end - -%%------------------------------------------------------------------------- -function [cid,len]=elem_info(type) -id=strfind('iUIlLdD',type); -dataclass={'int8','uint8','int16','int32','int64','single','double'}; -bytelen=[1,1,2,4,8,4,8]; -if(id>0) - cid=dataclass{id}; - len=bytelen(id); -else - error_pos('unsupported type at position %d'); -end -%%------------------------------------------------------------------------- - - -function [data adv]=parse_block(type,count,varargin) -global pos inStr isoct fileendian systemendian -[cid,len]=elem_info(type); -datastr=inStr(pos:pos+len*count-1); -if(isoct) - newdata=int8(datastr); -else - newdata=uint8(datastr); -end -id=strfind('iUIlLdD',type); -if(id<=5 && fileendian~=systemendian) - newdata=swapbytes(typecast(newdata,cid)); -end -data=typecast(newdata,cid); -adv=double(len*count); - -%%------------------------------------------------------------------------- - - -function object = parse_array(varargin) % JSON array is written in row-major order -global pos inStr isoct - parse_char('['); - object = cell(0, 1); - dim=[]; - type=''; - count=-1; - if(next_char == '$') - type=inStr(pos+1); - pos=pos+2; - end - if(next_char == '#') - pos=pos+1; - if(next_char=='[') - dim=parse_array(varargin{:}); - count=prod(double(dim)); - else - count=double(parse_number()); - end - end - if(~isempty(type)) - if(count>=0) - [object adv]=parse_block(type,count,varargin{:}); - if(~isempty(dim)) - object=reshape(object,dim); - end - pos=pos+adv; - return; - else - endpos=matching_bracket(inStr,pos); - [cid,len]=elem_info(type); - count=(endpos-pos)/len; - [object adv]=parse_block(type,count,varargin{:}); - pos=pos+adv; - parse_char(']'); - return; - end - end - if next_char ~= ']' - while 1 - val = parse_value(varargin{:}); - object{end+1} = val; - if next_char == ']' - break; - end - %parse_char(','); - end - end - if(jsonopt('SimplifyCell',0,varargin{:})==1) - try - oldobj=object; - object=cell2mat(object')'; - if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0) - object=oldobj; - elseif(size(object,1)>1 && ndims(object)==2) - object=object'; - end - catch - end - end - if(count==-1) - parse_char(']'); - end - -%%------------------------------------------------------------------------- - -function parse_char(c) - global pos inStr len - skip_whitespace; - if pos > len || inStr(pos) ~= c - error_pos(sprintf('Expected %c at position %%d', c)); - else - pos = pos + 1; - skip_whitespace; - end - -%%------------------------------------------------------------------------- - -function c = next_char - global pos inStr len - skip_whitespace; - if pos > len - c = []; - else - c = inStr(pos); - end - -%%------------------------------------------------------------------------- - -function skip_whitespace - global pos inStr len - while pos <= len && isspace(inStr(pos)) - pos = pos + 1; - end - -%%------------------------------------------------------------------------- -function str = parseStr(varargin) - global pos inStr esc index_esc len_esc - % len, ns = length(inStr), keyboard - type=inStr(pos); - if type ~= 'S' && type ~= 'C' && type ~= 'H' - error_pos('String starting with S expected at position %d'); - else - pos = pos + 1; - end - if(type == 'C') - str=inStr(pos); - pos=pos+1; - return; - end - bytelen=double(parse_number()); - if(length(inStr)>=pos+bytelen-1) - str=inStr(pos:pos+bytelen-1); - pos=pos+bytelen; - else - error_pos('End of file while expecting end of inStr'); - end - -%%------------------------------------------------------------------------- - -function num = parse_number(varargin) - global pos inStr len isoct fileendian systemendian - id=strfind('iUIlLdD',inStr(pos)); - if(isempty(id)) - error_pos('expecting a number at position %d'); - end - type={'int8','uint8','int16','int32','int64','single','double'}; - bytelen=[1,1,2,4,8,4,8]; - datastr=inStr(pos+1:pos+bytelen(id)); - if(isoct) - newdata=int8(datastr); - else - newdata=uint8(datastr); - end - if(id<=5 && fileendian~=systemendian) - newdata=swapbytes(typecast(newdata,type{id})); - end - num=typecast(newdata,type{id}); - pos = pos + bytelen(id)+1; - -%%------------------------------------------------------------------------- - -function val = parse_value(varargin) - global pos inStr len - true = 1; false = 0; - - switch(inStr(pos)) - case {'S','C','H'} - val = parseStr(varargin{:}); - return; - case '[' - val = parse_array(varargin{:}); - return; - case '{' - val = parse_object(varargin{:}); - if isstruct(val) - if(~isempty(strmatch('x0x5F_ArrayType_',fieldnames(val), 'exact'))) - val=jstruct2array(val); - end - elseif isempty(val) - val = struct; - end - return; - case {'i','U','I','l','L','d','D'} - val = parse_number(varargin{:}); - return; - case 'T' - val = true; - pos = pos + 1; - return; - case 'F' - val = false; - pos = pos + 1; - return; - case {'Z','N'} - val = []; - pos = pos + 1; - return; - end - error_pos('Value expected at position %d'); -%%------------------------------------------------------------------------- - -function error_pos(msg) - global pos inStr len - poShow = max(min([pos-15 pos-1 pos pos+20],len),1); - if poShow(3) == poShow(2) - poShow(3:4) = poShow(2)+[0 -1]; % display nothing after - end - msg = [sprintf(msg, pos) ': ' ... - inStr(poShow(1):poShow(2)) '' 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/src/paradigma/ppg/glob_functions/jsonlab/mergestruct.m b/src/paradigma/ppg/glob_functions/jsonlab/mergestruct.m deleted file mode 100644 index ce344ad2..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/mergestruct.m +++ /dev/null @@ -1,33 +0,0 @@ -function s=mergestruct(s1,s2) -% -% s=mergestruct(s1,s2) -% -% merge two struct objects into one -% -% authors:Qianqian Fang (fangq nmr.mgh.harvard.edu) -% date: 2012/12/22 -% -% input: -% s1,s2: a struct object, s1 and s2 can not be arrays -% -% output: -% s: the merged struct object. fields in s1 and s2 will be combined in s. -% -% license: -% BSD 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/src/paradigma/ppg/glob_functions/jsonlab/savejson.m b/src/paradigma/ppg/glob_functions/jsonlab/savejson.m deleted file mode 100644 index a86e9ac9..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/savejson.m +++ /dev/null @@ -1,475 +0,0 @@ -function json=savejson(rootname,obj,varargin) -% -% json=savejson(rootname,obj,filename) -% or -% json=savejson(rootname,obj,opt) -% json=savejson(rootname,obj,'param1',value1,'param2',value2,...) -% -% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript -% Object Notation) string -% -% author: Qianqian Fang (fangq nmr.mgh.harvard.edu) -% created on 2011/09/09 -% -% $Id: savejson.m 460 2015-01-03 00:30:45Z fangq $ -% -% input: -% rootname: the name of the root-object, when set to '', the root name -% is ignored, however, when opt.ForceRootName is set to 1 (see below), -% the MATLAB variable name will be used as the root name. -% obj: a MATLAB object (array, cell, cell array, struct, struct array). -% filename: a string for the file name to save the output JSON data. -% opt: a struct for additional options, ignore to use default values. -% opt can have the following fields (first in [.|.] is the default) -% -% opt.FileName [''|string]: a file name to save the output JSON data -% opt.FloatFormat ['%.10g'|string]: format to show each numeric element -% of a 1D/2D array; -% opt.ArrayIndent [1|0]: if 1, output explicit data array with -% precedent indentation; if 0, no indentation -% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D -% array in JSON array format; if sets to 1, an -% array will be shown as a struct with fields -% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for -% sparse arrays, the non-zero elements will be -% saved to _ArrayData_ field in triplet-format i.e. -% (ix,iy,val) and "_ArrayIsSparse_" will be added -% with a value of 1; for a complex array, the -% _ArrayData_ array will include two columns -% (4 for sparse) to record the real and imaginary -% parts, and also "_ArrayIsComplex_":1 is added. -% opt.ParseLogical [0|1]: if this is set to 1, logical array elem -% will use true/false rather than 1/0. -% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single -% numerical element will be shown without a square -% bracket, unless it is the root object; if 0, square -% brackets are forced for any numerical arrays. -% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson -% will use the name of the passed obj variable as the -% root object name; if obj is an expression and -% does not have a name, 'root' will be used; if this -% is set to 0 and rootname is empty, the root level -% will be merged down to the lower level. -% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern -% to represent +/-Inf. The matched pattern is '([-+]*)Inf' -% and $1 represents the sign. For those who want to use -% 1e999 to represent Inf, they can set opt.Inf to '$11e999' -% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern -% to represent NaN -% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), -% for example, if opt.JSONP='foo', the JSON data is -% wrapped inside a function call as 'foo(...);' -% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson -% back to the string form -% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode. -% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs) -% -% opt can be replaced by a list of ('param',value) pairs. The param -% string is equivallent to a field in opt and is case sensitive. -% output: -% json: a string in the JSON format (see http://json.org) -% -% examples: -% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... -% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... -% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... -% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... -% 'MeshCreator','FangQ','MeshTitle','T6 Cube',... -% 'SpecialData',[nan, inf, -inf]); -% savejson('jmesh',jsonmesh) -% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g') -% -% license: -% BSD 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(varargin{:}); -end -opt.IsOctave=exist('OCTAVE_VERSION','builtin'); -rootisarray=0; -rootlevel=1; -forceroot=jsonopt('ForceRootName',0,opt); -if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) - rootisarray=1; - rootlevel=0; -else - if(isempty(rootname)) - rootname=varname; - end -end -if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) - rootname='root'; -end - -whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); -if(jsonopt('Compact',0,opt)==1) - whitespaces=struct('tab','','newline','','sep',','); -end -if(~isfield(opt,'whitespaces_')) - opt.whitespaces_=whitespaces; -end - -nl=whitespaces.newline; - -json=obj2json(rootname,obj,rootlevel,opt); -if(rootisarray) - json=sprintf('%s%s',json,nl); -else - json=sprintf('{%s%s%s}\n',nl,json,nl); -end - -jsonp=jsonopt('JSONP','',opt); -if(~isempty(jsonp)) - json=sprintf('%s(%s);%s',jsonp,json,nl); -end - -% save to a file if FileName is set, suggested by Patrick Rapin -if(~isempty(jsonopt('FileName','',opt))) - if(jsonopt('SaveBinary',0,opt)==1) - fid = fopen(opt.FileName, 'wb'); - fwrite(fid,json); - else - fid = fopen(opt.FileName, 'wt'); - fwrite(fid,json,'char'); - end - fclose(fid); -end - -%%------------------------------------------------------------------------- -function txt=obj2json(name,item,level,varargin) - -if(iscell(item)) - txt=cell2json(name,item,level,varargin{:}); -elseif(isstruct(item)) - txt=struct2json(name,item,level,varargin{:}); -elseif(ischar(item)) - txt=str2json(name,item,level,varargin{:}); -else - txt=mat2json(name,item,level,varargin{:}); -end - -%%------------------------------------------------------------------------- -function txt=cell2json(name,item,level,varargin) -txt=''; -if(~iscell(item)) - error('input is not a cell'); -end - -dim=size(item); -if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now - item=reshape(item,dim(1),numel(item)/dim(1)); - dim=size(item); -end -len=numel(item); -ws=jsonopt('whitespaces_',struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')),varargin{:}); -padding0=repmat(ws.tab,1,level); -padding2=repmat(ws.tab,1,level+1); -nl=ws.newline; -if(len>1) - if(~isempty(name)) - txt=sprintf('%s"%s": [%s',padding0, checkname(name,varargin{:}),nl); name=''; - else - txt=sprintf('%s[%s',padding0,nl); - end -elseif(len==0) - if(~isempty(name)) - txt=sprintf('%s"%s": []',padding0, checkname(name,varargin{:})); name=''; - else - txt=sprintf('%s[]',padding0); - end -end -for j=1:dim(2) - if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end - for i=1:dim(1) - txt=sprintf('%s%s',txt,obj2json(name,item{i,j},level+(dim(1)>1)+1,varargin{:})); - if(i1) txt=sprintf('%s%s%s]',txt,nl,padding2); end - if(j1) txt=sprintf('%s%s%s]',txt,nl,padding0); end - -%%------------------------------------------------------------------------- -function txt=struct2json(name,item,level,varargin) -txt=''; -if(~isstruct(item)) - error('input is not a struct'); -end -dim=size(item); -if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now - item=reshape(item,dim(1),numel(item)/dim(1)); - dim=size(item); -end -len=numel(item); -ws=struct('tab',sprintf('\t'),'newline',sprintf('\n')); -ws=jsonopt('whitespaces_',ws,varargin{:}); -padding0=repmat(ws.tab,1,level); -padding2=repmat(ws.tab,1,level+1); -padding1=repmat(ws.tab,1,level+(dim(1)>1)+(len>1)); -nl=ws.newline; - -if(~isempty(name)) - if(len>1) txt=sprintf('%s"%s": [%s',padding0,checkname(name,varargin{:}),nl); end -else - if(len>1) txt=sprintf('%s[%s',padding0,nl); end -end -for j=1:dim(2) - if(dim(1)>1) txt=sprintf('%s%s[%s',txt,padding2,nl); end - for i=1:dim(1) - names = fieldnames(item(i,j)); - if(~isempty(name) && len==1) - txt=sprintf('%s%s"%s": {%s',txt,padding1, checkname(name,varargin{:}),nl); - else - txt=sprintf('%s%s{%s',txt,padding1,nl); - end - if(~isempty(names)) - for e=1:length(names) - txt=sprintf('%s%s',txt,obj2json(names{e},getfield(item(i,j),... - names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})); - if(e1) txt=sprintf('%s%s%s]',txt,nl,padding2); end - if(j1) txt=sprintf('%s%s%s]',txt,nl,padding0); end - -%%------------------------------------------------------------------------- -function txt=str2json(name,item,level,varargin) -txt=''; -if(~ischar(item)) - error('input is not a string'); -end -item=reshape(item, max(size(item),[1 0])); -len=size(item,1); -ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); -ws=jsonopt('whitespaces_',ws,varargin{:}); -padding1=repmat(ws.tab,1,level); -padding0=repmat(ws.tab,1,level+1); -nl=ws.newline; -sep=ws.sep; - -if(~isempty(name)) - if(len>1) txt=sprintf('%s"%s": [%s',padding1,checkname(name,varargin{:}),nl); end -else - if(len>1) txt=sprintf('%s[%s',padding1,nl); end -end -isoct=jsonopt('IsOctave',0,varargin{:}); -for e=1:len - if(isoct) - val=regexprep(item(e,:),'\\','\\'); - val=regexprep(val,'"','\"'); - val=regexprep(val,'^"','\"'); - else - val=regexprep(item(e,:),'\\','\\\\'); - val=regexprep(val,'"','\\"'); - val=regexprep(val,'^"','\\"'); - end - val=escapejsonstring(val); - if(len==1) - obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"']; - if(isempty(name)) obj=['"',val,'"']; end - txt=sprintf('%s%s%s%s',txt,padding1,obj); - else - txt=sprintf('%s%s%s%s',txt,padding0,['"',val,'"']); - end - if(e==len) sep=''; end - txt=sprintf('%s%s',txt,sep); -end -if(len>1) txt=sprintf('%s%s%s%s',txt,nl,padding1,']'); end - -%%------------------------------------------------------------------------- -function txt=mat2json(name,item,level,varargin) -if(~isnumeric(item) && ~islogical(item)) - error('input is not an array'); -end -ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); -ws=jsonopt('whitespaces_',ws,varargin{:}); -padding1=repmat(ws.tab,1,level); -padding0=repmat(ws.tab,1,level+1); -nl=ws.newline; -sep=ws.sep; - -if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... - isempty(item) ||jsonopt('ArrayToStruct',0,varargin{:})) - if(isempty(name)) - txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... - padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); - else - txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',... - padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl); - end -else - if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1 && level>0) - numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']',''); - else - numtxt=matdata2json(item,level+1,varargin{:}); - end - if(isempty(name)) - txt=sprintf('%s%s',padding1,numtxt); - else - if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) - txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); - else - txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt); - end - end - return; -end -dataformat='%s%s%s%s%s'; - -if(issparse(item)) - [ix,iy]=find(item); - data=full(item(find(item))); - if(~isreal(item)) - data=[real(data(:)),imag(data(:))]; - if(size(item,1)==1) - % Kludge to have data's 'transposedness' match item's. - % (Necessary for complex row vector handling below.) - data=data'; - end - txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); - end - txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep); - if(size(item,1)==1) - % Row vector, store only column indices. - txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... - matdata2json([iy(:),data'],level+2,varargin{:}), nl); - elseif(size(item,2)==1) - % Column vector, store only row indices. - txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... - matdata2json([ix,data],level+2,varargin{:}), nl); - else - % General case, store row and column indices. - txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... - matdata2json([ix,iy,data],level+2,varargin{:}), nl); - end -else - if(isreal(item)) - txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... - matdata2json(item(:)',level+2,varargin{:}), nl); - else - txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep); - txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',... - matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl); - end -end -txt=sprintf('%s%s%s',txt,padding1,'}'); - -%%------------------------------------------------------------------------- -function txt=matdata2json(mat,level,varargin) - -ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n')); -ws=jsonopt('whitespaces_',ws,varargin{:}); -tab=ws.tab; -nl=ws.newline; - -if(size(mat,1)==1) - pre=''; - post=''; - level=level-1; -else - pre=sprintf('[%s',nl); - post=sprintf('%s%s]',nl,repmat(tab,1,level-1)); -end - -if(isempty(mat)) - txt='null'; - return; -end -floatformat=jsonopt('FloatFormat','%.10g',varargin{:}); -%if(numel(mat)>1) - formatstr=['[' repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf('],%s',nl)]]; -%else -% formatstr=[repmat([floatformat ','],1,size(mat,2)-1) [floatformat sprintf(',\n')]]; -%end - -if(nargin>=2 && size(mat,1)>1 && jsonopt('ArrayIndent',1,varargin{:})==1) - formatstr=[repmat(tab,1,level) formatstr]; -end - -txt=sprintf(formatstr,mat'); -txt(end-length(nl):end)=[]; -if(islogical(mat) && jsonopt('ParseLogical',0,varargin{:})==1) - txt=regexprep(txt,'1','true'); - txt=regexprep(txt,'0','false'); -end -%txt=regexprep(mat2str(mat),'\s+',','); -%txt=regexprep(txt,';',sprintf('],\n[')); -% if(nargin>=2 && size(mat,1)>1) -% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); -% end -txt=[pre txt post]; -if(any(isinf(mat(:)))) - txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); -end -if(any(isnan(mat(:)))) - txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); -end - -%%------------------------------------------------------------------------- -function newname=checkname(name,varargin) -isunpack=jsonopt('UnpackHex',1,varargin{:}); -newname=name; -if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) - return -end -if(isunpack) - isoct=jsonopt('IsOctave',0,varargin{:}); - if(~isoct) - newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); - else - pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); - pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); - if(isempty(pos)) return; end - str0=name; - pos0=[0 pend(:)' length(name)]; - newname=''; - for i=1:length(pos) - newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; - end - if(pos(end)~=length(name)) - newname=[newname str0(pos0(end-1)+1:pos0(end))]; - end - end -end - -%%------------------------------------------------------------------------- -function newstr=escapejsonstring(str) -newstr=str; -isoct=exist('OCTAVE_VERSION','builtin'); -if(isoct) - vv=sscanf(OCTAVE_VERSION,'%f'); - if(vv(1)>=3.8) isoct=0; end -end -if(isoct) - escapechars={'\a','\f','\n','\r','\t','\v'}; - for i=1:length(escapechars); - newstr=regexprep(newstr,escapechars{i},escapechars{i}); - end -else - escapechars={'\a','\b','\f','\n','\r','\t','\v'}; - for i=1:length(escapechars); - newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\')); - end -end diff --git a/src/paradigma/ppg/glob_functions/jsonlab/saveubjson.m b/src/paradigma/ppg/glob_functions/jsonlab/saveubjson.m deleted file mode 100644 index ab47c70f..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/saveubjson.m +++ /dev/null @@ -1,504 +0,0 @@ -function json=saveubjson(rootname,obj,varargin) -% -% json=saveubjson(rootname,obj,filename) -% or -% json=saveubjson(rootname,obj,opt) -% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...) -% -% convert a MATLAB object (cell, struct or array) into a Universal -% Binary JSON (UBJSON) binary string -% -% author: Qianqian Fang (fangq nmr.mgh.harvard.edu) -% created on 2013/08/17 -% -% $Id: saveubjson.m 460 2015-01-03 00:30:45Z fangq $ -% -% input: -% rootname: the name of the root-object, when set to '', the root name -% is ignored, however, when opt.ForceRootName is set to 1 (see below), -% the MATLAB variable name will be used as the root name. -% obj: a MATLAB object (array, cell, cell array, struct, struct array) -% filename: a string for the file name to save the output UBJSON data -% opt: a struct for additional options, ignore to use default values. -% opt can have the following fields (first in [.|.] is the default) -% -% opt.FileName [''|string]: a file name to save the output JSON data -% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D -% array in JSON array format; if sets to 1, an -% array will be shown as a struct with fields -% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for -% sparse arrays, the non-zero elements will be -% saved to _ArrayData_ field in triplet-format i.e. -% (ix,iy,val) and "_ArrayIsSparse_" will be added -% with a value of 1; for a complex array, the -% _ArrayData_ array will include two columns -% (4 for sparse) to record the real and imaginary -% parts, and also "_ArrayIsComplex_":1 is added. -% opt.ParseLogical [1|0]: if this is set to 1, logical array elem -% will use true/false rather than 1/0. -% opt.NoRowBracket [1|0]: if this is set to 1, arrays with a single -% numerical element will be shown without a square -% bracket, unless it is the root object; if 0, square -% brackets are forced for any numerical arrays. -% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson -% will use the name of the passed obj variable as the -% root object name; if obj is an expression and -% does not have a name, 'root' will be used; if this -% is set to 0 and rootname is empty, the root level -% will be merged down to the lower level. -% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding), -% for example, if opt.JSON='foo', the JSON data is -% wrapped inside a function call as 'foo(...);' -% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson -% back to the string form -% -% opt can be replaced by a list of ('param',value) pairs. The param -% string is equivallent to a field in opt and is case sensitive. -% output: -% json: a binary string in the UBJSON format (see http://ubjson.org) -% -% examples: -% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],... -% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],... -% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;... -% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],... -% 'MeshCreator','FangQ','MeshTitle','T6 Cube',... -% 'SpecialData',[nan, inf, -inf]); -% saveubjson('jsonmesh',jsonmesh) -% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj') -% -% license: -% BSD 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(varargin{:}); -end -opt.IsOctave=exist('OCTAVE_VERSION','builtin'); -rootisarray=0; -rootlevel=1; -forceroot=jsonopt('ForceRootName',0,opt); -if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || iscell(obj)) && isempty(rootname) && forceroot==0) - rootisarray=1; - rootlevel=0; -else - if(isempty(rootname)) - rootname=varname; - end -end -if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot) - rootname='root'; -end -json=obj2ubjson(rootname,obj,rootlevel,opt); -if(~rootisarray) - json=['{' json '}']; -end - -jsonp=jsonopt('JSONP','',opt); -if(~isempty(jsonp)) - json=[jsonp '(' json ')']; -end - -% save to a file if FileName is set, suggested by Patrick Rapin -if(~isempty(jsonopt('FileName','',opt))) - fid = fopen(opt.FileName, 'wb'); - fwrite(fid,json); - fclose(fid); -end - -%%------------------------------------------------------------------------- -function txt=obj2ubjson(name,item,level,varargin) - -if(iscell(item)) - txt=cell2ubjson(name,item,level,varargin{:}); -elseif(isstruct(item)) - txt=struct2ubjson(name,item,level,varargin{:}); -elseif(ischar(item)) - txt=str2ubjson(name,item,level,varargin{:}); -else - txt=mat2ubjson(name,item,level,varargin{:}); -end - -%%------------------------------------------------------------------------- -function txt=cell2ubjson(name,item,level,varargin) -txt=''; -if(~iscell(item)) - error('input is not a cell'); -end - -dim=size(item); -if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now - item=reshape(item,dim(1),numel(item)/dim(1)); - dim=size(item); -end -len=numel(item); % let's handle 1D cell first -if(len>1) - if(~isempty(name)) - txt=[S_(checkname(name,varargin{:})) '[']; name=''; - else - txt='['; - end -elseif(len==0) - if(~isempty(name)) - txt=[S_(checkname(name,varargin{:})) 'Z']; name=''; - else - txt='Z'; - end -end -for j=1:dim(2) - if(dim(1)>1) txt=[txt '[']; end - for i=1:dim(1) - txt=[txt obj2ubjson(name,item{i,j},level+(len>1),varargin{:})]; - end - if(dim(1)>1) txt=[txt ']']; end -end -if(len>1) txt=[txt ']']; end - -%%------------------------------------------------------------------------- -function txt=struct2ubjson(name,item,level,varargin) -txt=''; -if(~isstruct(item)) - error('input is not a struct'); -end -dim=size(item); -if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now - item=reshape(item,dim(1),numel(item)/dim(1)); - dim=size(item); -end -len=numel(item); - -if(~isempty(name)) - if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end -else - if(len>1) txt='['; end -end -for j=1:dim(2) - if(dim(1)>1) txt=[txt '[']; end - for i=1:dim(1) - names = fieldnames(item(i,j)); - if(~isempty(name) && len==1) - txt=[txt S_(checkname(name,varargin{:})) '{']; - else - txt=[txt '{']; - end - if(~isempty(names)) - for e=1:length(names) - txt=[txt obj2ubjson(names{e},getfield(item(i,j),... - names{e}),level+(dim(1)>1)+1+(len>1),varargin{:})]; - end - end - txt=[txt '}']; - end - if(dim(1)>1) txt=[txt ']']; end -end -if(len>1) txt=[txt ']']; end - -%%------------------------------------------------------------------------- -function txt=str2ubjson(name,item,level,varargin) -txt=''; -if(~ischar(item)) - error('input is not a string'); -end -item=reshape(item, max(size(item),[1 0])); -len=size(item,1); - -if(~isempty(name)) - if(len>1) txt=[S_(checkname(name,varargin{:})) '[']; end -else - if(len>1) txt='['; end -end -isoct=jsonopt('IsOctave',0,varargin{:}); -for e=1:len - val=item(e,:); - if(len==1) - obj=['' S_(checkname(name,varargin{:})) '' '',S_(val),'']; - if(isempty(name)) obj=['',S_(val),'']; end - txt=[txt,'',obj]; - else - txt=[txt,'',['',S_(val),'']]; - end -end -if(len>1) txt=[txt ']']; end - -%%------------------------------------------------------------------------- -function txt=mat2ubjson(name,item,level,varargin) -if(~isnumeric(item) && ~islogical(item)) - error('input is not an array'); -end - -if(length(size(item))>2 || issparse(item) || ~isreal(item) || ... - isempty(item) || jsonopt('ArrayToStruct',0,varargin{:})) - cid=I_(uint32(max(size(item)))); - if(isempty(name)) - txt=['{' S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1)) ]; - else - if(isempty(item)) - txt=[S_(checkname(name,varargin{:})),'Z']; - return; - else - txt=[S_(checkname(name,varargin{:})),'{',S_('_ArrayType_'),S_(class(item)),S_('_ArraySize_'),I_a(size(item),cid(1))]; - end - end -else - if(isempty(name)) - txt=matdata2ubjson(item,level+1,varargin{:}); - else - if(numel(item)==1 && jsonopt('NoRowBracket',1,varargin{:})==1) - numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']',''); - txt=[S_(checkname(name,varargin{:})) numtxt]; - else - txt=[S_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})]; - end - end - return; -end -if(issparse(item)) - [ix,iy]=find(item); - data=full(item(find(item))); - if(~isreal(item)) - data=[real(data(:)),imag(data(:))]; - if(size(item,1)==1) - % Kludge to have data's 'transposedness' match item's. - % (Necessary for complex row vector handling below.) - data=data'; - end - txt=[txt,S_('_ArrayIsComplex_'),'T']; - end - txt=[txt,S_('_ArrayIsSparse_'),'T']; - if(size(item,1)==1) - % Row vector, store only column indices. - txt=[txt,S_('_ArrayData_'),... - matdata2ubjson([iy(:),data'],level+2,varargin{:})]; - elseif(size(item,2)==1) - % Column vector, store only row indices. - txt=[txt,S_('_ArrayData_'),... - matdata2ubjson([ix,data],level+2,varargin{:})]; - else - % General case, store row and column indices. - txt=[txt,S_('_ArrayData_'),... - matdata2ubjson([ix,iy,data],level+2,varargin{:})]; - end -else - if(isreal(item)) - txt=[txt,S_('_ArrayData_'),... - matdata2ubjson(item(:)',level+2,varargin{:})]; - else - txt=[txt,S_('_ArrayIsComplex_'),'T']; - txt=[txt,S_('_ArrayData_'),... - matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})]; - end -end -txt=[txt,'}']; - -%%------------------------------------------------------------------------- -function txt=matdata2ubjson(mat,level,varargin) -if(isempty(mat)) - txt='Z'; - return; -end -if(size(mat,1)==1) - level=level-1; -end -type=''; -hasnegtive=(mat<0); -if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0))) - if(isempty(hasnegtive)) - if(max(mat(:))<=2^8) - type='U'; - end - end - if(isempty(type)) - % todo - need to consider negative ones separately - id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]); - if(isempty(find(id))) - error('high-precision data is not yet supported'); - end - key='iIlL'; - type=key(find(id)); - end - txt=[I_a(mat(:),type,size(mat))]; -elseif(islogical(mat)) - logicalval='FT'; - if(numel(mat)==1) - txt=logicalval(mat+1); - else - txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')]; - end -else - if(numel(mat)==1) - txt=['[' D_(mat) ']']; - else - txt=D_a(mat(:),'D',size(mat)); - end -end - -%txt=regexprep(mat2str(mat),'\s+',','); -%txt=regexprep(txt,';',sprintf('],[')); -% if(nargin>=2 && size(mat,1)>1) -% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']); -% end -if(any(isinf(mat(:)))) - txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:})); -end -if(any(isnan(mat(:)))) - txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:})); -end - -%%------------------------------------------------------------------------- -function newname=checkname(name,varargin) -isunpack=jsonopt('UnpackHex',1,varargin{:}); -newname=name; -if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once'))) - return -end -if(isunpack) - isoct=jsonopt('IsOctave',0,varargin{:}); - if(~isoct) - newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}'); - else - pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start'); - pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end'); - if(isempty(pos)) return; end - str0=name; - pos0=[0 pend(:)' length(name)]; - newname=''; - for i=1:length(pos) - newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))]; - end - if(pos(end)~=length(name)) - newname=[newname str0(pos0(end-1)+1:pos0(end))]; - end - end -end -%%------------------------------------------------------------------------- -function val=S_(str) -if(length(str)==1) - val=['C' str]; -else - val=['S' I_(int32(length(str))) str]; -end -%%------------------------------------------------------------------------- -function val=I_(num) -if(~isinteger(num)) - error('input is not an integer'); -end -if(num>=0 && num<255) - val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')]; - return; -end -key='iIlL'; -cid={'int8','int16','int32','int64'}; -for i=1:4 - if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1))) - val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')]; - return; - end -end -error('unsupported integer'); - -%%------------------------------------------------------------------------- -function val=D_(num) -if(~isfloat(num)) - error('input is not a float'); -end - -if(isa(num,'single')) - val=['d' data2byte(num,'uint8')]; -else - val=['D' data2byte(num,'uint8')]; -end -%%------------------------------------------------------------------------- -function data=I_a(num,type,dim,format) -id=find(ismember('iUIlL',type)); - -if(id==0) - error('unsupported integer array'); -end - -% based on UBJSON specs, all integer types are stored in big endian format - -if(id==1) - data=data2byte(swapbytes(int8(num)),'uint8'); - blen=1; -elseif(id==2) - data=data2byte(swapbytes(uint8(num)),'uint8'); - blen=1; -elseif(id==3) - data=data2byte(swapbytes(int16(num)),'uint8'); - blen=2; -elseif(id==4) - data=data2byte(swapbytes(int32(num)),'uint8'); - blen=4; -elseif(id==5) - data=data2byte(swapbytes(int64(num)),'uint8'); - blen=8; -end - -if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) - format='opt'; -end -if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) - if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) - cid=I_(uint32(max(dim))); - data=['$' type '#' I_a(dim,cid(1)) data(:)']; - else - data=['$' type '#' I_(int32(numel(data)/blen)) data(:)']; - end - data=['[' data(:)']; -else - data=reshape(data,blen,numel(data)/blen); - data(2:blen+1,:)=data; - data(1,:)=type; - data=data(:)'; - data=['[' data(:)' ']']; -end -%%------------------------------------------------------------------------- -function data=D_a(num,type,dim,format) -id=find(ismember('dD',type)); - -if(id==0) - error('unsupported float array'); -end - -if(id==1) - data=data2byte(single(num),'uint8'); -elseif(id==2) - data=data2byte(double(num),'uint8'); -end - -if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2)) - format='opt'; -end -if((nargin<4 || strcmp(format,'opt')) && numel(num)>1) - if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2)))) - cid=I_(uint32(max(dim))); - data=['$' type '#' I_a(dim,cid(1)) data(:)']; - else - data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)']; - end - data=['[' data]; -else - data=reshape(data,(id*4),length(data)/(id*4)); - data(2:(id*4+1),:)=data; - data(1,:)=type; - data=data(:)'; - data=['[' data(:)' ']']; -end -%%------------------------------------------------------------------------- -function bytes=data2byte(varargin) -bytes=typecast(varargin{:}); -bytes=bytes(:)'; diff --git a/src/paradigma/ppg/glob_functions/jsonlab/varargin2struct.m b/src/paradigma/ppg/glob_functions/jsonlab/varargin2struct.m deleted file mode 100644 index 43c27af4..00000000 --- a/src/paradigma/ppg/glob_functions/jsonlab/varargin2struct.m +++ /dev/null @@ -1,40 +0,0 @@ -function opt=varargin2struct(varargin) -% -% opt=varargin2struct('param1',value1,'param2',value2,...) -% or -% opt=varargin2struct(...,optstruct,...) -% -% convert a series of input parameters into a structure -% -% authors:Qianqian Fang (fangq nmr.mgh.harvard.edu) -% date: 2012/12/22 -% -% input: -% 'param', value: the input parameters should be pairs of a string and a value -% optstruct: if a parameter is a struct, the fields will be merged to the output struct -% -% output: -% opt: a struct where opt.param1=value1, opt.param2=value2 ... -% -% license: -% BSD 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 then based on ppg_prob alone! -end - -epoch_length = 6; % in seconds -overlap = 5; % in seconds - -% Number of samples in epoch -samples_per_epoch = epoch_length * fs; - -% Calculate number of samples to shift for each epoch -samples_shift = (epoch_length - overlap) * fs; -n_samples = (length(ppg_prob) + overlap) * fs; -data_prob = zeros(n_samples,1); - -prob_array = ppg_prob; -imu_array = imu_label; - -for i = 1:n_samples - start_idx = ceil((i-(samples_per_epoch-samples_shift))/fs); %start_idx for the non starting and ending epochs is equal to ceil((data idx - n_overlap)/fs) - end_idx = ceil(i/fs); - - %%-----Correct for first and last 6s epochs (those have less than 6 epochs to calculate labels and prob)-----%% - if start_idx < 1 - start_idx = 1; % The first 5 epochs indices start at 1 - elseif end_idx>length(prob_array) - end_idx = length(prob_array); % The last 5 epochs indices end at the last label - end - - prob = prob_array(start_idx:end_idx); - label_imu = imu_array(start_idx:end_idx); - data_prob(i) = mean(prob); - data_label_imu(i) = int8(mean(label_imu) >= 0.5); % Perform majority voting -end - -data_prob(data_label_imu==0) = 0; % Set prob to zero if majority voting of IMU is 0 - -end \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/synchronization.m b/src/paradigma/ppg/glob_functions/synchronization.m deleted file mode 100644 index 46560685..00000000 --- a/src/paradigma/ppg/glob_functions/synchronization.m +++ /dev/null @@ -1,76 +0,0 @@ -function [segment_ppg_total, segment_imu_total] = synchronization(ppg_meta, imu_meta) -% K.I. Veldkamp, PhD student AI4P, 29-02-24 -% This function checks data availability between PPG and IMU and returns -% the synchronized indices - -% Convert start and end times to datetime objects -ppg_start_time = datetime({ppg_meta.start_iso8601}', 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'Format', 'yyyy-MM-dd''T''HH:mm:ss', 'TimeZone', 'UTC'); -imu_start_time = datetime({imu_meta.start_iso8601}', 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'Format', 'yyyy-MM-dd''T''HH:mm:ss', 'TimeZone', 'UTC'); -ppg_end_time = datetime({ppg_meta.end_iso8601}', 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'Format', 'yyyy-MM-dd''T''HH:mm:ss', 'TimeZone', 'UTC'); -imu_end_time = datetime({imu_meta.end_iso8601}', 'InputFormat', 'yyyy-MM-dd''T''HH:mm:ssZ', 'Format', 'yyyy-MM-dd''T''HH:mm:ss', 'TimeZone', 'UTC'); - -% Create a time vector covering the entire range -time_vector_total = datetime(min([imu_start_time; ppg_start_time]), 'Format', 'yyyy-MM-dd HH:mm:ss'):seconds(1):datetime(max([imu_end_time; ppg_end_time]), 'Format', 'yyyy-MM-dd HH:mm:ss'); - -% Initialize variables -data_presence_ppg = zeros(size(time_vector_total)); -data_presence_ppg_idx = zeros(size(time_vector_total)); -data_presence_imu = zeros(size(time_vector_total)); -data_presence_imu_idx = zeros(size(time_vector_total)); - -% Mark the segments of PPG data with 1 -for i = 1:length(ppg_start_time) - indices = time_vector_total >= ppg_start_time(i) & time_vector_total < ppg_end_time(i); - data_presence_ppg(indices) = 1; - data_presence_ppg_idx(indices) = i; -end - -% Mark the segments of IMU data with 1 -for i = 1:length(imu_start_time) - indices = time_vector_total >= imu_start_time(i) & time_vector_total < imu_end_time(i); - data_presence_imu(indices) = 1; - data_presence_imu_idx(indices) = i; -end - -% Find the indices where both PPG and IMU data are present -corr_indices = find(data_presence_ppg == 1 & data_presence_imu == 1); - -% Find the start and end indices of each segment -corr_start_end = []; -start_idx = corr_indices(1); -for i = 2:length(corr_indices) - if corr_indices(i) - corr_indices(i-1) > 1 - end_idx = corr_indices(i-1); - corr_start_end = [corr_start_end; start_idx, end_idx]; - start_idx = corr_indices(i); - end -end - -% Add the last segment -if ~isempty(corr_indices) - corr_start_end = [corr_start_end; start_idx, corr_indices(end)]; -end - -% Extract the synchronized indices for each segment -segment_ppg_total = []; -segment_imu_total = []; -for i = 1:size(corr_start_end,1) - start_idx = corr_start_end(i,1); - end_idx = corr_start_end(i,2); - segment_ppg = unique(data_presence_ppg_idx(start_idx:end_idx))'; - segment_imu = unique(data_presence_imu_idx(start_idx:end_idx))'; - if length(segment_ppg) > 1 & length(segment_imu) == 1 - segment_ppg_total = [segment_ppg_total; segment_ppg]; - segment_imu_total = [segment_imu_total; segment_imu*ones(length(segment_ppg),1)]; - elseif length(segment_ppg) == 1 & length(segment_imu) > 1 - segment_ppg_total = [segment_ppg_total; segment_ppg*ones(length(segment_imu),1)]; - segment_imu_total = [segment_imu_total; segment_imu]; - elseif length(segment_ppg) == length(segment_imu) - segment_ppg_total = [segment_ppg_total; segment_ppg]; - segment_imu_total = [segment_imu_total; segment_imu]; - else - continue - end -end - -end \ No newline at end of file diff --git a/src/paradigma/ppg/glob_functions/tsdf_scan_meta.m b/src/paradigma/ppg/glob_functions/tsdf_scan_meta.m deleted file mode 100644 index ff4eed77..00000000 --- a/src/paradigma/ppg/glob_functions/tsdf_scan_meta.m +++ /dev/null @@ -1,22 +0,0 @@ -function tsdf = tsdf_scan_meta(tsdf_data_full_path) -% K.I. Veldkamp, PhD student AI4P, 29-02-24 -% For each given TSDB directory, transcribe TSDF metadata contents to SQL -% table --> function specific for toolbox data structure -tsdf = []; -irow = 1; - -meta_list = dir(fullfile(tsdf_data_full_path, '*_meta.json')); -meta_filenames = {meta_list.name}; - -jsonobj = {}; -for n = 1:length(meta_filenames) - tsdb_meta_fullpath = fullfile(tsdf_data_full_path, meta_filenames{n}); - jsonstr = fileread(tsdb_meta_fullpath); - jsonobj{n} = loadjson(jsonstr); - tsdf(irow).tsdf_meta_fullpath = tsdb_meta_fullpath; - tsdf(irow).subject_id = jsonobj{n}.subject_id; - tsdf(irow).start_iso8601 = jsonobj{n}.start_iso8601; - tsdf(irow).end_iso8601 = jsonobj{n}.end_iso8601; - irow = irow + 1; -end - diff --git a/src/paradigma/ppg/hr_functions/Long_TFD_JOT.m b/src/paradigma/ppg/hr_functions/Long_TFD_JOT.m deleted file mode 100644 index e55d080c..00000000 --- a/src/paradigma/ppg/hr_functions/Long_TFD_JOT.m +++ /dev/null @@ -1,38 +0,0 @@ -%% Implementation using the toolbox of J. O'Toole - -% Only the essential code is used. The function nonsep_gdtfd is code from -% the toolbox of J. O'Toole: Copyright © 2014, John M. O Toole, University College Cork. All rights reserved. -function HR_smooth_tfd = Long_TFD_JOT(rel_ppg_tfd, MA, fs, kern_type, kern_params) - -tfd = nonsep_gdtfd(rel_ppg_tfd, kern_type, kern_params); % for now the wigner ville distribution but one could also use the smoothed pseudo WVD --> returns matrix of size NxN - -if MA.value == 1 - input = tfd'; - tfd = filtfilt(MA.FC,1,input); - tfd = tfd.'; -end - -%%----- Get time and frequency axis for tfd-----%% -[~,M]=size(tfd); -Ntime=size(tfd,1); - -ntime=1:Ntime; ntime=ntime./fs-1/fs; % time array -ntime=round(ntime, 10); % to overcome floating point inconsistencies -Mh=ceil(M); -k=linspace(0,0.5,Mh); -k=k.*fs; % frequency array - -%%---Estimate HR using same approach as for given tfd----%% -[~, k_idx] = max(tfd, [], 1); - - -count = 0; - -for i = 2:2:length(rel_ppg_tfd)/fs-4 % starting at 2 and ending at length -4 to discard the first and last 2 sec of the WVD which are influenced by boundary effects - count = count + 1; - rel_wvd_idx = ntime>=i & ntime then based on ppg_prob alone! - end - - edge_add = 4; % adding an additional 4 sec (2 s to both sides) to overcome boundary effects/discontinuities of the WVD, in SPWVD this effect is already diminished due to a double kernel function - epoch_length = tfd_length + edge_add; - segment_length = (length(rel_ppg_tfd)-edge_add*fs)/fs; % substract the 4 added sec to obtain the original segment length - - if segment_length > epoch_length - n_segments = floor(segment_length/tfd_length); %% Dit moet aangepast worden!! - else - n_segments = 1; % for HR segments which are shorter than 30 s due to uneven start and end of the segment which can make the segment 28 s if 1 s is substracted - end - - ppg_segments = cell(n_segments,1); - - for i = 1:n_segments % Split segments in 30 s PPG epochs - - if i ~= n_segments - ppg_segments{i} = rel_ppg_tfd(1 + (i-1)*tfd_length*fs: (i*tfd_length+edge_add)*fs); - - else - - ppg_segments{i} = rel_ppg_tfd(1 + (i-1)*tfd_length*fs:end); - - end - - end - - HR_smooth_tfd = []; - - for j = 1:n_segments % Calculate the HR - ppg = ppg_segments{j}; - HR_tfd = Long_TFD_JOT(ppg, MA, fs, kern_type, kern_params); - HR_smooth_tfd = [HR_smooth_tfd; HR_tfd]; - end - \ No newline at end of file diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/.gitignore b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/.gitignore deleted file mode 100644 index 6b4d9904..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -todo_list.org -full_TFDs/full_gdtfd_testing_version.m -notes_decimated_GDTFD_algorithms.org -docs_pdf_readme/ diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/CHANGELOG.md b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/CHANGELOG.md deleted file mode 100644 index 08c603ff..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/CHANGELOG.md +++ /dev/null @@ -1,23 +0,0 @@ -# Change Log -All notable changes to this project will be documented in this file. Project started -2014-04-22 but this log started 2017-05-30, after version 0.2.3. More details can be found -in the git logs. - - -## unreleased -### Changed -- implemented modified-B distribution in 'nonsep' section, - e.g. tf=full_tfd(x,'nonsep',{'mb',0.01}); but is better to use lag-independent version, - i.e. tf=full_tfd(x,'LI,{length(x)-1,'cosh',0.01}); -### Removed -### Fixed -- input argument (Ntime) when calling LI kernel from full_tfd.m (was incorrectly passing - Nfreq) -- bug fix in `gen_lag_kern.m` and `gen_Doppler_kern.m` for windows `gauss`, `cosh`, `tukey` as -default value was 0; now use Matlab will use default value -- missing `shiftWin` function (centres window) in `gen_lag_kern.m` and -`gen_Doppler_kern.m` (only used if 5 parameters in window cell); now added -### Added -- this CHANGELOG.md! -- windows: `blackmanharris`, `chebwin`, and `nuttall` (in `get_window.m`) - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/LICENCE.md b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/LICENCE.md deleted file mode 100644 index 7cc20295..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/LICENCE.md +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2014, John M. O' Toole, University College Cork -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - 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. - - Neither the name of the University College Cork nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/README.md b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/README.md deleted file mode 100644 index 2a841e4b..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/README.md +++ /dev/null @@ -1,251 +0,0 @@ -# Fast and Memory-Efficient Algorithms for Quadratic Time–Frequency Distributions - -A collection of M-files to compute time–frequency distributions from the quadratic class -[[1] and [2]](#references). Memory and computational load is limited by controlling the level of over-sampling for the TFD. Oversampling in the TFD is proportional to signal length and bandwidth of the Doppler–lag kernel. Algorithms are optimised to four kernel types: nonseparable, separable, lag-independent, and Doppler-independent kernels. - -Also included are algorithms to compute decimated, or sub-sampled, TFDs. Again, these -algorithms are specific to the four kernel types but compute approximate TFDs by a process -of decimatation. - -Requires Matlab or Octave (programming environments). - -Latest version available at [memeff_TFDs homepage](http://otoolej.github.io/code/memeff_TFDs/). - - -# Contents -- [quick start](#quick-start) -- [description](#description) -- [files](#files) -- [computational load](#computational-load) -- [requirements](#requirements) -- [test computer setup](#test-computer-setup) -- [licence](#licence) -- [references](#references) -- [contact](#contact) - - -# quick start -First, add paths using the `load_curdir` function: -```matlab - >> load_curdir; -``` - -# description - -There are two sets of TFD algorithms: one set computes oversampled TFDs and the other -set computes decimated (sub-sampled or undersampled) TFDs. The first set, for computing -oversampled TFDs, has four algorithms for specific kernel types, namely the -- non-separable kernel, -- separable kernel, -- Doppler-independent (DI) kernel, -- and lag-independent (LI) kernel. - -The function to generate these oversampled TFDs is `full_tfd.m`. The following -examples, using a test signal, illustrates usage: - -```matlab - % generate test signal: - N=512; - x=gen_LFM(N,0.1,0.3) + gen_LFM(N,0.4,0.04); - - % nonseparable kernel (Choi-Williams kernel): - tf=full_tfd(x,'nonsep',{'cw',10}); - figure(1); clf; vtfd(tf,x); - - % separable kernel: - tf=full_tfd(x,'sep',{{51,'hann'},{101,'hann'}},256,256); - figure(2); clf; vtfd(tf,x); - - % Doppler-independent kernel: - tf=full_tfd(x,'DI',{101,'hann'},[],256); - figure(3); clf; vtfd(tf,x); - - % lag-independent kernel: - tf=full_tfd(x,'LI',{51,'hann'},256,[]); - figure(4); clf; vtfd(tf,x); -``` -![Examples of oversampled TFDs](pics/full_TFDs_examples.png) -Type `help full_tfd` for more details. - -Likewise, the algorithms for decimated TFDs are specific to the four kernel types. The -function `dec_tfd` computes the decimated TFDs, as the following examples show: - -```matlab - N=1024; Ntime=64; Nfreq=128; - a=2; b=2; - ni=[100:2:900]; ki=[150:2:850]; - - x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); - - % non-separable kernel: - c=dec_tfd(x,'nonsep',{'cw',100},N,N,a*4,b*4); - figure(1); clf; vtfd(c,x); - - % separable kernel: - c=dec_tfd(x,'sep',{{51,'hann'},{101,'hann'}},Ntime,Nfreq,a,b); - figure(2); clf; vtfd(c,x); - - % Doppler-independent kernel: - c=dec_tfd(x,'DI',{101,'hann'},N,Nfreq,ni,b); - figure(3); clf; vtfd(c,x,1,ni); - - % lag-independent kernel: - c=dec_tfd(x,'LI',{51,'hann'},Ntime,N,a,ki); - figure(4); clf; vtfd(c,x,1,[],ki./(N*2)); -``` -![Examples of decimated TFDs](pics/decimated_TFDs_examples.png) - -Type `help dec_tfd` for more details on this function. - - -# files -All Matlab files (.m files) have a description and an example in the header. To read this -header, type `help ` in Matlab. Directory structure is as follows: -``` -├── common # directory: files to generate kernel functions -├── decimated_TFDs # directory: files to generate decimated TFD for the 4 kernel types -├── dec_tfd.m # file: compute decimated TFDs -├── full_tfd.m # file: compute oversampled TFDs -├── full_TFDs # directory: files to generate oversampled TFD for the 4 kernel types -├── LICENCE.md # file: licence file -├── load_curdir.m # file: adds paths for matlab/octave -├── README.md # file: this README file -└── utils # directory: miscellaneous files -``` - - -# computational load - -The computational load is measured in terms of the number of FFTs required to compute the -TFD. Memory load is measured as the total memory required to compute and store the -TFD. The real-valued signal (i.e. input signal) is of length N. - -Computational load for the oversampled TFDs (using `full_tfd.m`) is as follows for the -four kernel types: - -| kernel-type | computational load | memory (real-valued points) | -|---------------|------------------------------|-----------------------------| -| non-separable | 3N²/2 log₂ N | N² | -| LI | NNtime/2 log₂ Ntime | Ntime × N | -| DI | NNfreq/2 log₂ Nfreq | N × Nfreq | -| separable | Pₕ(N log₂N +Ntime log₂Ntime) | Ntime × Nfreq | -| | + NtimeNfreq/2 log₂ Nfreq | | - -assuming the FFT of length-N signal requires Nlog₂N computations and using the notation: - -| symbol | explanation | -|--------|-------------------------------------------------------------| -| N | length of signal | -| Ntime | length of TFD in time direction | -| Nfreq | length of TFD in frequency direction | -| Pₕ | Pₕ = P/2, where P is the length of the lag window | - -And for the decimated TFDs (using `dec_tfd.m`): - -| kernel-type | computational load | memory (real-valued points) | grid | -|---------------|------------------------------|-----------------------------|----------| -| non-separable | N²/2 log₂ N + LJ/2 log₂ J | L × J | ρ[an,bn] | -| LI | VLtime/2 log₂ Ltime | Ltime × V | ρ[an,kᵢ] | -| DI | UJfreq/2 log₂ Jfreq | U × Jfreq | ρ[nᵢ,bk] | -| separable | JfreqN/2 log₂N | Ltime × Jfreq | ρ[an,bn] | -| | + LtimeJfreq log₂ LtimeJfreq | | | - -using the extra notation: - -| symbol | explanation | -|--------|-------------------------------------------------------------| -| U | length of sequence nᵢ {nᵢ for 1<=i<=U}, U<=N and 0<=nᵢ<=N-1 | -| V | length of sequence kᵢ {kᵢ for 1<=i<=V}, V<=N and 0<=kᵢ<=N-1 | -| J | N/b, b is decimation integer in frequency direction | -| L | N/a, a is decimation integer in time direction | -| Jfreq | Nfreq/b, b is decimation integer in frequency direction | -| Ltime | Ntime/a, a is decimation integer in time direction | - - -# requirements -Either Matlab (R2012 or newer, -[Mathworks website](http://www.mathworks.co.uk/products/matlab/)) or Octave (v3.6 or -newer, [Octave website](http://www.gnu.org/software/octave/index.html), with the -'octave-signal' add-on package). - - -# test computer setup -- hardware: Intel(R) Xeon(R) CPU E5-1603 0 @ 2.80GHz; 8GB memory. -- operating system: Ubuntu GNU/Linux x86_64 distribution (Trusty Tahr, 14.04), with Linux - kernel 3.13.0-27-generic -- software: Octave 3.8.1 (using Gnuplot 4.6 patchlevel 4), with 'octave-signal' toolbox - and Matlab (R2009b, R2012a, and R2013a) - ---- - -# licence - -``` -Copyright (c) 2014, John M. O' Toole, University College Cork -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - 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. - - Neither the name of the University College Cork nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. -``` - - -# references - -1. J.M. O' Toole and B. Boashash, “Memory Efficient Algorithms for Quadratic TFDs”, - Chapter 6.6; in Time–Frequency Signal Processing and Analysis: A - Comprenhensive Reference, Second Edition, Academic Press, pp. 374–385, 2016 (ISBN: 9780123984999). - -2. J.M. O' Toole and B. Boashash, "Fast and memory-efficient algorithms for computing - quadratic time–frequency distributions", Applied and Computational Harmonic Analysis, - vol. 35, no. 2, pp. 350–358, 2013. - -3. J.M. Oʼ Toole, M. Mesbah, and B. Boashash, “Improved discrete definition of quadratic - time–frequency distributions,” IEEE Transactions on Signal Processing, vol. 58, - Feb. 2010, pp. 906-911. - -4. J.M. O' Toole, M. Mesbah, and B. Boashash, "A New Discrete Analytic Signal for Reducing - Aliasing in the Discrete Wigner-Ville Distribution", IEEE Transactions on Signal - Processing, vol. 56, no. 11, pp. 5427-5434, Nov. 2008. - -5. J.M. Oʼ Toole, M. Mesbah, and B. Boashash, “Algorithms for discrete quadratic - time–frequency distributions,” WSEAS Transactions on Signal Processing, vol. 4, - May. 2008, pp. 320-329. - - ---- - -# contact - -John M. O' Toole - -Neonatal Brain Research Group, -Irish Centre for Maternal and Child Health Research [(INFANT)](https://www.infantcentre.ie/), -Department of Paediatrics and Child Health, -Cork University Hospital, -University College Cork, -Ireland - -- email: jotoole -AT- ucc DOT ie - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/README.pdf b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/README.pdf deleted file mode 100644 index 10dfaed6..00000000 Binary files a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/README.pdf and /dev/null differ diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_Doppler_kern.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_Doppler_kern.m deleted file mode 100644 index f4c37143..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_Doppler_kern.m +++ /dev/null @@ -1,142 +0,0 @@ -%------------------------------------------------------------------------------- -% gen_Doppler_kern: smoothing window for Doppler-kernel G1[l]; checks paramaters -% -% Syntax: [G1,Q,Qh_floor,Ntime]=gen_Doppler_kern(win_params,N,Ntime) -% -% Input: -% win_params - cell of {win_length,win_type,[win_param],[Doppler_or_time]} -% e.g. {11,'hamm',0,1} -% the parameter 'Doppler_or_time' is either: -% 0 = to define window in the time-domain -% 1 = to define window in the Doppler-domain (default) -% N - length of signal -% Ntime - number of sample points in the time direction -% -% Ouput: -% G1 - Doppler function G_1(1/(QT)) -% Q - length of G1 -% Ntime - returns Ntime as it may be adjusted from input -% -% See also: GEN_LAG_KERN, GEN_DOPPLER_LAG_KERN, GET_WINDOW, PADWIN -% -% Example: -% G1=gen_Doppler_kern({111,'cosh',0.1,1},128,512); -% plot(real(G1)); -% -% -% IF window is defined in doppler domain: -% window function G_1(l/NT) is length Q -% OR if window is defined in time domain: -% window function g_1(nT) is length-Q, and then zero-padded -% to the doppler domain where G_1(l/NT) is length N -% ENDIF - -% John M. O' Toole, University College Cork -% Started: 16-04-2014 -% -% last update: Time-stamp: <2021-08-24 17:42:57 (otoolej)> -%------------------------------------------------------------------------------- -function [G1,Q,Ntime,G1_pad]=gen_Doppler_kern(win_params,N,Ntime) -if(nargin<3 || isempty(Ntime)), Ntime=[]; end - - -DBplot=0; - - -%--------------------------------------------------------------------- -% 1. make sure parameters are ok -%--------------------------------------------------------------------- -Q=win_params{1}; -% window length can not be greater than N: -if(Q>N) - warning('length of g2 too long: chopping down length N'); - Q=N; -end -% force window length to be odd-value: -if(Q/2==fix(Q/2)) - Q=Q-1; - warning(['Forcing Q to be odd. Q is now Q=',num2str(Q)]); -end -Qh_floor=floor(Q/2); - - -l=length(win_params); -if( l<2 ) - error('Need at least two window parameters'); -end -if(isempty(Ntime)), Ntime=Q+1; end - -if(Ntime<(Q+1)) - warning('Ntime is too short: increasing length to (Q+1)'); - Ntime=Q+1; -end - -% force Ntime to be even -if(rem(Ntime,2)), - Ntime=Ntime+1; - warning(['Forcing Ntime to be even. Ntime is now Ntime=',num2str(Ntime)]); -end - - - -%--------------------------------------------------------------------- -% 2. call function to generate window -%--------------------------------------------------------------------- -win_type=win_params{2}; -if( l>=3 ) win_extra_param=win_params{3}; else, win_extra_param=[]; end -if( l>3 ) win_dft_param=win_params{4}; else, win_dft_param=1; end - - -% if define in Doppler domain: -if(win_dft_param==1) - G1=get_window(Q,win_type,win_extra_param); - G1=G1(:); - - G1_pad=padWin(G1,Ntime); - - -else - % or defining window in the time-domain: - g1=get_window(Q,win_type,win_extra_param,0); - g1=padWin(g1,N); - G1_length=N; - - G1=real( fft(g1) ); - G1=G1./G1(1); - Ntime=N; Q=N; -end - - -%--------------------------------------------------------------------- -% 3. [OPTIONAL] post-process window -%--------------------------------------------------------------------- -% a. if normalizing window: -if(length(win_params)>4) - if(strcmpi(win_params{5},'y')==1) - G1=G1./sum(G1); - end -end - -% b. if (time) reversing window -if(length(win_params)>5 ) - G1=shiftWin(G1); - G1_pad=shiftWin(G1_pad); -end - - -if(DBplot) - figure(20); clf; hold all; - if(exist('G1_pad','var')) - subplot(211); plot(G1_pad); - end - subplot(212); plot(real(G1)); -end - - - - -function w=shiftWin(w) -%--------------------------------------------------------------------- -% shift window to centre -%--------------------------------------------------------------------- -w=circshift(w(:),ceil(length(w)/2)); diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_Doppler_lag_kern.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_Doppler_lag_kern.m deleted file mode 100644 index a6571061..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_Doppler_lag_kern.m +++ /dev/null @@ -1,314 +0,0 @@ -%------------------------------------------------------------------------------- -% gen_Doppler_lag_kern: Doppler--lag kernel (for GDTFD definition) -% -% Syntax: kern=gen_Doppler_lag_kern(kern_type,kern_params,N) -% -% Input: -% kern_type = { 'wvd' | 'swvd' | 'pwvd' | 'sep' | 'cw' | 'mb'} -% wvd - kernel for Wigner-Ville distribution -% swvd - kernel for smoothed Wigner-Ville distribution -% (lag-independent kernel) -% pwvd - kernel for pseudo Wigner-Ville distribution -% (Doppler-independent kernel) -% sep - kernel for separable kernel (combintation of SWVD and PWVD) -% cw - kernel for Choi-Williams distribution -% mb - kernel for Modified-B distribution -% -% kern_params = cell of kernel parameters: -% wvd - {} -% swvd - {win_length,win_type,[win_param],[Doppler_or_time]} -% e.g. {11,'hamm',0,1} -% the parameter Doppler_or_time is either -% 0 = to define window in the time-domain -% 1 = to define window in the Doppler-domain -% pwvd - {win_length,win_type,[win_param]} -% e.g. {200,'cosh',0.1} -% sep - { {win1_length,win1_type,[win1_param]}, -% {win2_length,win2_type,[win2_param]} -% where win1 is the Doppler window and win2 is the lag window. -% e.g. { {11,'hamm'}, {200,'cosh',0.1} } -% cw - {sigma_parameter} -% mb - {beta_parameter} in the range 1 -%------------------------------------------------------------------------------- -function g=gen_Doppler_lag_kern(kern_type,kern_params,N,lag_index,G1) -if(nargin<3), error('need 3 input arguments'); end -if(nargin<4 || isempty(lag_index)), lag_index=[]; end -if(nargin<5 || isempty(G1)), G1=[]; end - - - -DBplot=0; - -lag_sample=2; -doppler_sample=1/N; - -if(isempty(lag_index)) - lag_index=1:N; - g=zeros(N); -else - g=zeros(N,1:length(lag_index)); -end - - - -if(~iscell(kern_params)) - tmp_params{1}=kern_params; - kern_params=tmp_params; -end - -g=get_kern(g,lag_index,kern_type,kern_params,doppler_sample,lag_sample,N,G1); - - -% All kernels are real valued. -g=real(g); - -if(DBplot) - figure(1); clf; - if(length(lag_index)==1) - plot( g ); - else - mesh( fftshift(g) ); - end - xlabel('lag'); ylabel('Doppler'); - title('Separable kernel'); -end - - - - -function g=get_kern(g,lag_index,kernel_type,kernel_params,doppler_sample_rate, ... - lag_sample_rate,N,G1) -%--------------------------------------------------------------------- -% generate the kernels for a given sample rate -%--------------------------------------------------------------------- -if(nargin<8 || isempty(G1)), G1=[]; end - -[Nd,Nl]=size(g); -l=length(kernel_params); - - -switch kernel_type - - case {'wvd'} - g(:,:)=1; - - - %--------------------------------------------------------------------- - % Smoothed Wigner-Ville (Lag Independent (LI) kernel) - % g(l/NT,mT) = W(l/NT) - %--------------------------------------------------------------------- - case 'swvd' - - if( l<2 ) - error('Need at least two window parameters for SWVD'); - end - win_length=kernel_params{1}; - win_type=kernel_params{2}; - win_param=0; win_param2=1; - if( l>=3 ) win_param=kernel_params{3}; end - if( l>=4 ) win_param2=kernel_params{4}; end - - - G1=get_window(win_length,win_type,win_param); - G1=padWin(G1,Nd); - - - % Define window in the time-domain (this is the usual practice): - % But could also define in the doppler-domain. - if( win_param2==0 ) - G1=fft(G1); - G1=G1./G1(1); - end - - if( isreal_fn(ifft(G1))==0 ) - warning('Window function g1(t) is NOT real valued.'); - end - - for m=1:Nl - g(:,m) = G1; - end - - - %--------------------------------------------------------------------- - % Pseudo-Wigner-Ville (Doppler Independent (DI) kernel) - % g(l/NT,mT) = g2(mT) - %--------------------------------------------------------------------- - case 'pwvd' - - if( l<2 ) - error('Need at least two window parameters for PWVD'); - end - P=kernel_params{1}; - win_type=kernel_params{2}; - win_param=0; win_param2=0; - if( l>2 ) win_param=kernel_params{3}; end - if( l>3 ) win_param2=kernel_params{4}; end - - g2=get_window(P,win_type,win_param,win_param2); - - g2=padWin(g2(:),N); - g2=g2(lag_index); - - if( Nd==Nl && isreal_fn(fft(g2))==0 ) - warning('Window function G2(f) is NOT real valued.'); - end - - for l=0:Nd-1 - g(l+1,:)=g2; - end - - %--------------------------------------------------------------------- - % Seperable Kernel - % - % g(l/NT,mT) = G1(l/NT)g2(mT) - % - %--------------------------------------------------------------------- - case { 'sep', 'sep-full' } - - if(l<2) - error('Need at least two windows parameters.'); - end - - g1=get_kern(g,lag_index,'swvd',kernel_params{1},doppler_sample_rate,lag_sample_rate,N); - g2=get_kern(g,lag_index,'pwvd',kernel_params{2},doppler_sample_rate,lag_sample_rate,N); - g=g1.*g2; - - - %--------------------------------------------------------------------- - % Choi-Williams - % - % g(l/NT,mT) = exp( -(2 pi m l/N)^2/ sigma ) - % - %--------------------------------------------------------------------- - case {'cw', 'choi-williams', 'choi-will'} - - if(l>=1) - sigma=kernel_params{1}; - else - sigma=11; - end - Ndh=ceil(Nd/2); - Nlh=ceil(Nl/2); - - - % if just at one-lag index: - if(length(lag_index)==1) - g(1)=1; - m=lag_index-1; - if(m==(N-1)) - g(:)=0; - elseif(m==0) - g(:)=1; - else - if(m>ceil(N/2)) m=N-m; end - - const = ((2*pi)^2)/sigma; - u=1:Ndh-1; - u1=u.*doppler_sample_rate; m1=m*lag_sample_rate; - - g(u+1) = exp( -const.*(u1.*m1).^2 ).'; - g(Nd-u+1)=g(u+1); - end - - % or for the whole thing: - else - g(1,1:Nl)=1; g(1:Nd,1)=1; - - const = ((2*pi)^2)/sigma; - u=1:Ndh-1; - for m=1:Nlh-1 - - u1=u.*doppler_sample_rate; m1=m*lag_sample_rate; - g(u+1,m+1)=exp( -const.*(u1.*m1).^2 ).'; - - g(Nd-u+1,m+1)=g(u+1,m+1); - g(u+1,Nl-m+1)=g(u+1,m+1); - g(Nd-u+1,Nl-m+1)=g(u+1,m+1); - end - end - - %--------------------------------------------------------------------- - % Product kernel (sometimes called a RID kernel) - % - % g(l/NT,2mT)=H(l2m/N) - %--------------------------------------------------------------------- - case { 'prod', 'RID', 'product' } - - % NOT WORKING: -% $$$ if(length(lag_index)==1) -% $$$ m=lag_index; -% $$$ -% $$$ g(1)=1; -% $$$ if(m==N) -% $$$ g(:)=0; -% $$$ else -% $$$ if(m>ceil(N/2)) m=N-m; end -% $$$ -% $$$ u=1:floor(Nd/2); -% $$$ im=mod(u*m,length(G1)); -% $$$ -% $$$ g(u+1)=G1(im+1); -% $$$ g(Nd-u+1)=g(u+1); -% $$$ end -% $$$ else -% $$$ keyboard; -% $$$ if(isempty(G1)) -% $$$ [d,d2,d3,G1]=gen_Doppler_kern(kernel_params,N,N); -% $$$ end -% $$$ Ndh=ceil(Nd/2); Nlh=ceil(Nl/2); -% $$$ g=zeros(Nd,Nl); -% $$$ -% $$$ g(1,1:Nl)=G1(1); g(1:Nd,1)=G1(1); -% $$$ -% $$$ u=1:Ndh-1; -% $$$ for m=1:Nlh-1 -% $$$ g(u+1,m+1)=G1( mod(u.*m,N)+1 ); -% $$$ -% $$$ % $$$ g(Nd-u+1,m+1)=g(u+1,m+1); -% $$$ % $$$ g(u+1,Nl-m+1)=g(u+1,m+1); -% $$$ % $$$ g(Nd-u+1,Nl-m+1)=g(u+1,m+1); -% $$$ end -% $$$ -% $$$ end - - - %--------------------------------------------------------------------- - % Modified-B (a specific SWVD or LAG INDEPENDENT kernel) - % - % G(nT,mT) = cosh^{-2*beta}(n) (defined in time--lag domain) - %--------------------------------------------------------------------- - case { 'mb', 'modified-b' } - - G1=get_kern(g,lag_index,'swvd',{N-1,'cosh',kernel_params{1}}, ... - doppler_sample_rate,lag_sample_rate,N); - - for m=1:Nl - g(:,m) = G1; - end - - - otherwise - error(['Unknown kernel type: ' kernel_type]); - -end - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_lag_kern.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_lag_kern.m deleted file mode 100644 index 00b201de..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/common/gen_lag_kern.m +++ /dev/null @@ -1,123 +0,0 @@ -%------------------------------------------------------------------------------- -% gen_lag_kern: smoothing window for Lag-kernel g2[m]; provides some checking of -% the parameters -% -% Syntax: [g2,P,Ph_floor,Nfreq]=gen_lag_kern(win_params,N,Nfreq) -% -% -% Input: -% win_params - cell of {win_length,win_type,[win_param],[lag_or_freq]} -% e.g. {11,'hamm',0,1} -% the parameter lag_or_freq is either: -% 0 = to define window in the lag-domain -% 1 = to define window in the frequency-domain -% N - lenght of signal -% Nfreq - number of sample points in the frequency direction -% -% Output: -% g2 - lag kernel g_2(2mT) -% P - length of g2 (as may have changed) -% Ph_floor - floor(P/2) -% Nfreq - Nfreq (as may have changed) -% -% See also: GEN_DOPPLER_KERN, GEN_DOPPLER_LAG_KERN, GET_WINDOW, PADWIN -% -% Example: -% g2=get_lag_kernel({61,'hann'},128,512); -% - -% John M. O' Toole, University College Cork -% Started: 16-04-2014 -% -% last update: Time-stamp: <2021-08-24 17:42:46 (otoolej)> -%------------------------------------------------------------------------------- -function [g2,P,Ph_floor,Nfreq]=gen_lag_kern(win_params,N,Nfreq) -if(nargin<3 || isempty(Nfreq)), Nfreq=[]; end - - -DBplot=0; - - -%--------------------------------------------------------------------- -% 1. make sure parameters are ok -%--------------------------------------------------------------------- -P=win_params{1}; -% window length can not be greater than N: -if(P>N) - warning('length of g2 too long: chopping down length N'); - P=N; -end -% force window length to be odd-value: -if(P/2==fix(P/2)) - P=P-1; - warning(['Forcing P to be odd. P is now P=',num2str(P)]); -end -Ph_floor=floor(P/2); - - -l=length(win_params); -if( l<2 ) - error('Need at least two window parameters'); -end - -if(isempty(Nfreq)), Nfreq=P+1; end - -if(Nfreq<(P+1)) - warning('Nfreq is too short: increasing length to (P+1)'); - Nfreq=P+1; -end - -if(rem(Nfreq,2)) - Ntime=Ntime+1; - warning(['Forcing Ntime to be even. Ntime is now Ntime=',num2str(Ntime)]); -end - - -%--------------------------------------------------------------------- -% 2. call function to generate window -%--------------------------------------------------------------------- -win_type=win_params{2}; -if( l>=3 ) win_extra_param=win_params{3}; else, win_extra_param=[]; end -if( l>3 ) win_dft_param=win_params{4}; else, win_dft_param=0; end - - -g2=get_window(P,win_type,win_extra_param,win_dft_param); -g2=g2(:); - -g2_pad=padWin(g2,Nfreq); - - -%--------------------------------------------------------------------- -% 3. [OPTIONAL] post-process window -%--------------------------------------------------------------------- -% a. if normalizing window: -if(length(win_params)>4) - if(strcmpi(win_params{5},'y')==1) - g2=g2./sum(g2); - end -end - -% b. if (time) reversing window -if(length(win_params)>5 ) - g2=shiftWin(g2); - g2_pad=shiftWin(g2_pad); -end - - -if(DBplot) - figure(20); clf; hold all; - subplot(211); plot(g2_pad); - subplot(212); plot(g2); -end - - -function w=shiftWin(w) -%--------------------------------------------------------------------- -% shift window to centre -%--------------------------------------------------------------------- -w=circshift(w(:),ceil(length(w)/2)); - - - - - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/dec_tfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/dec_tfd.m deleted file mode 100644 index f12f5c16..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/dec_tfd.m +++ /dev/null @@ -1,154 +0,0 @@ -%------------------------------------------------------------------------------- -% dec_tfd: Generate decimated (or sub-sampled) time-frequency distributions -% -% Syntax: tf=dec_tfd(x,kern_type,kern_params,Ntime,Nfreq,time_dec,freq_dec) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% kern_type = kernel type, either nonseparable, separable, Doppler-independent -% (DI) or lag-independent (LI): { 'nonsep' | 'sep' | 'DI' | 'LI' } -% -% kern_params = kernel parameters; different depending on kernel type -% -% if nonseparable kernel, then form: { kern_name, kern_param} -% e.g. tf=full_tfd( x, 'nonsep', { 'cw', 100 } ); -% -% if Doppler-independent kernel, then of the form: -% { window_length, window_type, [window_parameter (optional)] } -% e.g. tf=full_tfd( x, 'DI', {101,'hann'} ); -% -% if lag-independent kernel, then of the form: -% { window_length, window_type, [window_parameter (optional)] } -% e.g. tf=full_tfd( x, 'LI', {101,'cosh',0.01} ); -% -% if separable kernel, then of the form: { doppler_window, lag_window } -% where doppler_window is of the form: { window_length, window_type, -% [window_parameter (optional)] }; same format for lag window -% e.g. tf=full_tfd( x, 'sep', { {101, 'cosh', 0.05}, {101,'hann'} } ); -% -% Ntime = over-sampling in the time direction; only applicable for separable -% and lag-independent kernels -% -% Nfreq = over-sampling in the frequency direction; only applicable for separable -% and Doppler-independent kernels -% -% time_dec = decimation factor in the time domain; for the Doppler-independent kernel -% this value can be either a vector or a scalar; for all other kernel types this -% value is an integer scalar a. -% -% freq_dec = decimation factor in the frequency domain; for the lag-independent kernel -% this value can be either a vector or a scalar; for all other kernel types this -% value is an integer scalar b. -% -% Outputs: -% tf - time-frequency distribution of size (a/N) x (b/N) (non-separable kernel), -% or (a/Ntime) x (b/Nfreq) (separable kernel), -% or U x (b/Nfreq) (Doppler-independent kernel, U is length of time_dec vector), -% or (a/Ntime) x V (lag-independent kernel, V is length of freq_dec vector) -% -% See also: DEC_NONSEP_GDTFD, DEC_SEP_GDTFD, DEC_LI_GDTFD, DEC_DI_GDTFD -% -% Example: -% N=1024; Ntime=64; Nfreq=128; -% a=2; b=2; -% ni=[100:2:900]; ki=[150:2:850]; -% -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% % non-separable kernel: -% c=dec_tfd(x,'nonsep',{'cw',100},N,N,a*4,b*4); -% figure(1); clf; vtfd(c,x); -% -% % separable kernel: -% c=dec_tfd(x,'sep',{{51,'hann'},{101,'hann'}},Ntime,Nfreq,a,b); -% figure(2); clf; vtfd(c,x); -% -% % Doppler-independent kernel: -% c=dec_tfd(x,'DI',{101,'hann'},N,Nfreq,ni,b); -% figure(3); clf; vtfd(c,x,1,ni); -% -% % lag-independent kernel: -% c=dec_tfd(x,'LI',{51,'hann'},Ntime,N,a,ki); -% figure(4); clf; vtfd(c,x,1,[],ki./(N*2)); - -% John M. O' Toole, University College Cork -% Started: 23-07-2014 -% -% last update: Time-stamp: <2019-06-05 17:05:19 (otoolej)> -%------------------------------------------------------------------------------- -function tf=dec_tfd(x,kern_type,kern_params,Ntime,Nfreq,time_dec,freq_dec) -if(nargin<2 || isempty(kern_type)), kern_type='sep'; end -if(nargin<3 || isempty(kern_params)), kern_params={{51,'hann'},{101,'hann'}}; end -if(nargin<4 || isempty(time_dec)), time_dec=[]; end -if(nargin<5 || isempty(freq_dec)), freq_dec=[]; end -if(nargin<6 || isempty(Ntime)), Ntime=[]; end -if(nargin<7 || isempty(Nfreq)), Nfreq=[]; end - - -% set to 1 if want to see how much memory is used: -DBmem=0; - - -kern_type=lower(kern_type); -switch kern_type - case { 'nonsep', 'ns', 'nonseparable', 'non-separable', 'non-sep' } - %--------------------------------------------------------------------- - % 1. Non-separable kernel; Doppler-lag form: g[l,m] - %--------------------------------------------------------------------- - nonsep_params=[]; - if(~iscell(kern_params)) - nonsep_name=kern_params; - else - nonsep_name=kern_params{1}; - if(length(kern_params)>1) - nonsep_params=kern_params{2}; - end - end - - tf=dec_nonsep_gdtfd(x,nonsep_name,nonsep_params,time_dec,freq_dec); - - - case { 'sep', 'separable' } - %--------------------------------------------------------------------- - % 2. separable kernel; Doppler-lag form: G1[l]g2[m] - %--------------------------------------------------------------------- - if(~iscell(kern_params) | (iscell(kern_params) & length(kern_params)<2) ) - error(['separable kernel parameters should be of the form: ' ... - '{ {dopp_win_length,dopp_win_name}, {lag_win_length,lag_win_name} }']); - end - - tf=dec_sep_gdtfd(x,kern_params{1},kern_params{2},time_dec,freq_dec,Ntime,Nfreq); - - - case { 'di', 'doppler-independent', 'dopp.-indep', 'dopp-indep', 'pwvd', 'p-wvd' } - %--------------------------------------------------------------------- - % 3. Doppler-independent kernel: Doppler-lag form: g2[m] - %--------------------------------------------------------------------- - if(~iscell(kern_params)) - error(['Doppler-independent kernel parameters should be of the form: ' ... - '{win_length,win_name}']); - end - - tf=dec_di_gdtfd(x,kern_params,time_dec,freq_dec,Nfreq); - - - case { 'li', 'lag-independent', 'lag-indep', 'swvd', 's-wvd' } - %--------------------------------------------------------------------- - % 4. Lag-independent kernel: Doppler-lag form: G1[l] - %--------------------------------------------------------------------- - if(~iscell(kern_params)) - error(['lag-independent kernel parameters should be of the form: ' ... - '{win_length,win_name}']); - end - - tf=dec_li_gdtfd(x,kern_params,time_dec,freq_dec,Ntime); - - otherwise - warning('kern_type should be either: nonsep, sep, DI, or LI'); - tf=[]; -end - - -if(DBmem), s=whos; fprintf('total memory used: mem=%s\n',disp_bytes(sum([s.bytes]))); end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_di_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_di_gdtfd.m deleted file mode 100644 index 2332e143..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_di_gdtfd.m +++ /dev/null @@ -1,194 +0,0 @@ -%------------------------------------------------------------------------------- -% dec_di_gdtfd: decimated Doppler-independent kernel TFD ρ[nᵢ,bk], where b is an -% integer value and nᵢ is the set nᵢ ={ nᵢ | 1≤i≤U }, with 0≤nᵢ≤N-1 -% -% Syntax: tfd=dec_di_gdtfd(x,lag_win_params,time_dec,freq_dec,Nfreq) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% lag_win_params = lag window parameters in cell form: -% {win_length,win_type,win_param,lag_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] lag_or_not is either 0 (define window in the lag -% domain, which is the default) or 0 (define window the frequency domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% time_dec = decimation factor a in the time domain; a/Ntime is integer -% freq_dec = decimation factor b in the frequency domain; b/Nfreq is integer -% -% Nfreq = frequency oversampling value; must be greater than length of lag window -% -% See also: DI_GDTFD, GET_ANALYTIC_SIGNAL, GEN_LAG_KERN, FFT -% -% Outputs: -% tfd = U x (b/Nfreq) time–frequency distribution -% -% Example: -% N=1024; Nfreq=128; ni=[100:4:900]; b=2; -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% c=dec_di_gdtfd(x,{101,'hann'},ni,b,Nfreq); -% vtfd(c,x,1,ni); - - -% John M. O' Toole, University College Cork -% Started: 23-04-2014 -% -% last update: Time-stamp: <2014-07-23 16:22:59 (otoolej)> -%------------------------------------------------------------------------------- -function tfd=dec_di_gdtfd(x,lag_win_params,time_dec,freq_dec,Nfreq) -if(nargin<2 || isempty(lag_win_params)), lag_win_params={101,'hamm'}; end -if(nargin<3 || isempty(time_dec)), time_dec=[]; end -if(nargin<4 || isempty(freq_dec)), freq_dec=1; end -if(nargin<5 || isempty(Nfreq)), Nfreq=[]; end - -DBplot=0; -DBmem=0; -DBtest=0; -DBtime=0; -DBverbose=0; - - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. generate time--lag signal function (for positive-lag values only) -%--------------------------------------------------------------------- -[g2,P,Ph_floor,Nfreq]=gen_lag_kern(lag_win_params,N,Nfreq); -Nh=ceil(Nfreq/2); -Ph=ceil(P/2); - - -% check decimation parameters and return as sequence: -if(length(freq_dec)>1) - error('Frequency decimation parameter should be scalar'); -end -[n_seq,U]=check_dec_params_seq(time_dec,N,'time',0); -[k_seq,J,freq_dec]=check_dec_params_seq(freq_dec,Nfreq,'frequency',1); -Jh=ceil(J/2); J_extend=2*Jh+2; - - -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=zeros(U,J_extend); -if(J~=Nfreq) - m_real=1:Jh+1; m_imag=(J_extend-Jh):(J_extend); -else - m_real=1:Ph; m_imag=(J-Ph+1):J; -end - - - -m=0:(Ph-1); mb=1:(Ph-1); -for in=1:U - n=n_seq(in); - inp=mod(n+m,N2); inn=mod(n-m,N2); - - if(J~=Nfreq) - % need to fold signal function (for decimation in frequency-direction): - K_time_slice=zeros(1,Nfreq); - K_time_slice(m+1)=g2(m+1).*z(inp+1).*conj( z(inn+1) ); - K_time_slice(Nfreq-mb+1)=conj(K_time_slice(mb+1)); - - R_fold=fold_vector_half(K_time_slice,J,Jh,freq_dec); - else - % or if not then do as usual: - K_time_slice(m+1)=g2(m+1).*z(inp+1).*conj( z(inn+1) ); - - R_fold=K_time_slice; - end - - tfd(in,m_real)=real( R_fold ); - tfd(in,m_imag)=imag( R_fold ); -end - -if(DBmem), s=whos; fprintf('K: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -%------------------------------------------------------------------------- -% 3. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -if(J~=Nfreq) - m=0:Jh; mb=1:(Jh-1); -else - m=0:(Ph-1); mb=1:(Ph-1); -end - - -for n=0:2:(U-2) - R_even_half=complex(tfd(n+1,m_real),tfd(n+1,m_imag)); - R_odd_half =complex(tfd(n+2,m_real),tfd(n+2,m_imag)); - - R_tslice_even=zeros(1,J); R_tslice_odd=zeros(1,J); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_odd(m+1) =R_odd_half(m+1); - R_tslice_even(J-mb+1)=conj( R_even_half(mb+1) ); - R_tslice_odd(J-mb+1) =conj( R_odd_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(n+1,1:J)=real(tfd_time_slice); - tfd(n+2,1:J)=imag(tfd_time_slice); -end - -% one extra FFT if U is odd: -if(rem(U,2)) - R_even_half=complex(tfd(U,m_real),tfd(U,m_imag)); - R_tslice_even=zeros(1,J); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_even(J-mb+1)=conj( R_even_half(mb+1) ); - tfd_time_slice=fft( R_tslice_even ); - - tfd(U,1:J)=real(tfd_time_slice); -end -tfd=tfd(:,1:J); - -if(DBmem), s=whos; fprintf('end: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -scale_factor=1/Nfreq; -tfd=tfd.*scale_factor; - -if(DBtime), dispVars( toc(time_start) ); end - - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,'pwvd',{P,lag_win_params{2:end}}); - if(DBtime), dispVars( toc(time_start) ); end - - if(Nfreq==N) - dispEE(tfd_test(n_seq+1,k_seq+1),tfd); - else - b=N/Nfreq; - if( b==floor(b) ) - dispEE(tfd_test(n_seq+1,(b.*k_seq)+1),tfd./b); - end - end - -end -if(DBverbose) - fprintf('size=%dx%d; max=%g; total energ:%d\n', size(tfd,1), size(tfd,2), max(tfd(:)), ... - sum(tfd(:))); -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); - - figure(9); clf; hold all; - subplot(211); hold all; plot(sum(tfd')'); plot( abs(z(1:N)).^2 ); - subplot(212); hold all; plot(sum(tfd')' - abs(z(n_seq+1)).^2 ); -end - - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_li_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_li_gdtfd.m deleted file mode 100644 index c7c9d405..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_li_gdtfd.m +++ /dev/null @@ -1,200 +0,0 @@ -%------------------------------------------------------------------------------- -% dec_li_gdtfd: decimated lag-independent kernel TFD ρ[an,kᵢ], where a is an integer -% value and kᵢ is the set kᵢ ={ kᵢ | 1≤i≤V }, with 0≤kᵢ≤N-1 -% -% Syntax: tfd=dec_li_gdtfd(x,dopp_win_params,time_dec,freq_dec,Ntime) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% dopp_win_params = Doppler window parameters in cell form: -% {win_length,win_type,win_param,Doppler_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] Doppler_or_not is either 1 (define window in the Doppler -% domain, which is the default) or 0 (define window in the time domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% time_dec = decimation factor a in the time domain; a/Ntime is integer -% freq_dec = decimation factor b in the frequency domain; b/Nfreq is integer -% -% Ntime = time oversampling value; must be greater than length of Doppler window -% -% Outputs: -% tfd = (a/Ntime) x V time–frequency distribution -% -% See also: LI_GDTFD, GET_ANALYTIC_SIGNAL, GEN_DOPPLER_KERN, FFT -% -% Example: -% N=1024; Ntime=64; a=2; ki=[150:4:850]; -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% c=dec_li_gdtfd(x,{51,'hann'},a,ki,Ntime); -% vtfd(c,x,1,[],ki./(N*2)); - -% John M. O' Toole, University College Cork -% Started: 23-04-2014 -% -% last update: Time-stamp: <2014-07-23 16:19:59 (otoolej)> -%------------------------------------------------------------------------------- -function tfd=dec_li_gdtfd(x,dopp_win_params,time_dec,freq_dec,Ntime) -if(nargin<2 || isempty(dopp_win_params)), dopp_win_params={51,'hann'}; end -if(nargin<3 || isempty(time_dec)), time_dec=1; end -if(nargin<4 || isempty(freq_dec)), freq_dec=1; end -if(nargin<5 || isempty(Ntime)), Ntime=[]; end - - -DBplot=0; -DBmem=0; -DBtest=0; -DBtime=0; -DBverbose=0; - - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. generate time--lag signal function (for positive-lag values only) -%--------------------------------------------------------------------- -[G1,Q,Ntime]=gen_Doppler_kern(dopp_win_params,N,Ntime); -Qh=ceil(Q/2); - - -% check decimation parameters and return as sequence: -if(length(time_dec)>1) - error('Frequency decimation parameter should be scalar'); -end -[n_seq,L,time_dec]=check_dec_params_seq(time_dec,Ntime,'time',1); -[k_seq,V]=check_dec_params_seq(freq_dec,N,'frequency',0); -Lh=ceil(L/2); L_extend=2*Lh+2; - - -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=zeros(L_extend,V); -if(L~=Ntime) - l_real=1:(Lh+1); l_imag=(L_extend-Lh):L_extend; -else - l_real=1:Qh; l_imag=(L-Qh+1):L; -end - - -Z=fft(z); -l=0:(Qh-1); lb=1:(Qh-1); -for ik=1:V - k=k_seq(ik); - inp=mod(k+l,N2); inn=mod(k-l,N2); - inpN=mod(k+l+N,N2); innN=mod(k-l-N,N2); - - if(L~=Ntime) - K_doppler_slice=zeros(1,Ntime); - K_doppler_slice(l+1)=G1(l+1).*( Z(inp+1).*conj( Z(inn+1) ) + ... - Z(inpN+1).*conj( Z(innN+1) ) ); - K_doppler_slice(Ntime-lb+1)=conj( K_doppler_slice(lb+1) ); - - R_fold=fold_vector_half(K_doppler_slice./2,L,Lh,time_dec); - else - - K_doppler_slice=G1(l+1).*( Z(inp+1).*conj( Z(inn+1) ) + ... - Z(inpN+1).*conj( Z(innN+1) ) ); - - R_fold=K_doppler_slice; - end - - tfd(l_real,ik)=real( R_fold ); - tfd(l_imag,ik)=imag( R_fold ); -end - - -if(DBmem), s=whos; fprintf('K: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - - -%------------------------------------------------------------------------- -% 3. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -if(L~=Ntime) - l=0:Lh; lb=1:(Lh-1); -else - l=0:(Qh-1); lb=1:(Qh-1); -end - -for k=0:2:(V-2) - R_even_half=complex(tfd(l_real,k+1),tfd(l_imag,k+1)); - R_odd_half =complex(tfd(l_real,k+2),tfd(l_imag,k+2)); - - R_tslice_even=zeros(L,1); R_tslice_odd=zeros(L,1); - R_tslice_even(l+1)=R_even_half(l+1); - R_tslice_odd(l+1) =R_odd_half(l+1); - R_tslice_even(L-lb+1)=conj( R_even_half(lb+1) ); - R_tslice_odd(L-lb+1) =conj( R_odd_half(lb+1) ); - - tfd_freq_slice=ifft( R_tslice_even+j.*R_tslice_odd ); - - tfd(1:L,k+1)=real(tfd_freq_slice); - tfd(1:L,k+2)=imag(tfd_freq_slice); -end - -% one extra FFT if V is odd -if(rem(V,2)) - R_even_half=complex(tfd(l_real,V),tfd(l_imag,V)); - - R_tslice_even=zeros(L,1); - R_tslice_even(l+1)=R_even_half(l+1); - R_tslice_even(L-lb+1)=conj( R_even_half(lb+1) ); - - tfd_freq_slice=ifft( R_tslice_even ); - - tfd(1:L,V)=real(tfd_freq_slice); -end -tfd=tfd(1:L,:); - -if(DBmem), s=whos; fprintf('tfd (end): mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -if(time_dec==1) - scale_factor=1/(2*N); -else - scale_factor=1/(N*time_dec); -end -tfd=tfd.*scale_factor; - -if(DBtime), dispVars( ['time: ' num2str(toc(time_start))] ); end - - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,'swvd',{Q,dopp_win_params{2:end}}); - if(DBtime), dispVars( ['testing time: ' num2str(toc(time_start))] ); end - if(Ntime==N) - dispEE(tfd_test(n_seq+1,k_seq+1),tfd); - else - a=N/Ntime; - if( a==floor(a) ) - dispEE(tfd_test((a.*n_seq)+1,k_seq+1),tfd./a); - end - end -end -if(DBverbose) - fprintf('size=%dx%d; max=%g; total energ:%d\n', size(tfd,1), size(tfd,2), max(tfd(:)), ... - sum(tfd(:))); -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); - - figure(9); clf; hold all; - Z=fft(z); - subplot(211); hold all; plot(sum(tfd)); plot( abs(Z(1:N)).^2./(2*N) ); - subplot(212); hold all; plot(sum(tfd)' - abs(Z(k_seq+1)).^2./(2*N) ); -end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_nonsep_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_nonsep_gdtfd.m deleted file mode 100644 index da41ecea..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_nonsep_gdtfd.m +++ /dev/null @@ -1,229 +0,0 @@ -%------------------------------------------------------------------------------- -% dec_nonsep_gdtfd: decimated TFD with non-separable kernel ρ[an,bk], where a,b are -% integer values -% -% -% Syntax: tfd=dec_nonsep_gdtfd(x,kern_type,kern_params,time_dec,freq_dec) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% kern_type = { 'wvd' | 'swvd' | 'pwvd' | 'sep' | 'cw' | 'mb' } -% wvd - Wigner-Ville distribution -% swvd - Smoothed Wigner-Ville distribution -% (lag-independent kernel) -% pwvd - Pseudo Wigner-Ville distribution -% (Doppler-independent kernel) -% sep - Separable-kernel distribution -% (combintation of SWVD and PWVD) -% mb - Modified-B distribution -% cw - Choi-Williams distribution -% -% kern_params = cell of kernel parameters: -% wvd - {} -% swvd - {win_length,win_type,[win_param]} -% e.g. {11,'hamm'} -% pwvd - {win_length,win_type,[win_param]} -% e.g. {200,'cosh',0.1} -% sep - { {win1_length,win1_type,[win1_param]}, -% {win2_length,win2_type,[win2_param]} } -% where win1 is the doppler window and win2 is the -% lag window, e.g. { {11,'hamm'}, {200,'cosh',0.1} } -% mb - {beta_parameter} in the range 1 -%------------------------------------------------------------------------------- -function tfd=dec_nonsep_gdtfd(x,kern_type,kern_params,time_dec,freq_dec) -if(nargin<2 || isempty(kern_type)), kern_type='cw'; end -if(nargin<3 || isempty(kern_params)), kern_params=10; end -if(nargin<4 || isempty(time_dec)), time_dec=1; end -if(nargin<5 || isempty(freq_dec)), freq_dec=1; end - - -DBplot=0; -DBmem=0; -DBtest=0; -DBtime=0; -DBverbose=0; - - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - -% if product-kernel then generate window now: -G1=get_prod_kernel(kern_type,kern_params,N); - - -%--------------------------------------------------------------------- -% 2. check decimation parameters -%--------------------------------------------------------------------- -if(length(time_dec)>1 || length(freq_dec)>1) - error('Frequency and time decimation parameters should be scalar'); -end -[n_seq,L,time_dec]=check_dec_params_seq(time_dec,N,'time',1); -[k_seq,J,freq_dec]=check_dec_params_seq(freq_dec,N,'frequency',1); -Jh=ceil(J/2); J_extend=2*Jh+2; - -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -tfd=zeros(L,J_extend); -m_real=1:Jh+1; m_imag=(J_extend-Jh):(J_extend); - -if(DBmem), s=whos; fprintf('declare TFD: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -%--------------------------------------------------------------------- -% 3. generate time--lag signal function (for positive-lag values only) -%--------------------------------------------------------------------- -n=0:N-1; mb=1:Jh-1; -for m=0:Jh - - %------------------------------------ - % Fold in the lag direction - %------------------------------------ - af_lag_slice=zeros(N,1); - for p=0:freq_dec-1 - mmod=(p*J+m); - g_lag_slice=gen_Doppler_lag_kern(kern_type,kern_params,N,mmod+1); - - if(mmod<=Nh) - inp=mod(n+mmod,N2); inn=mod(n-mmod,N2); - K_lag_slice=z(inp+1).*conj(z(inn+1)); - else - inp=mod(n+N-mmod,N2); inn=mod(n-N+mmod,N2); - K_lag_slice=conj(z(inp+1)).*z(inn+1); - end - - af_lag_slice=af_lag_slice + fft(K_lag_slice).*g_lag_slice; - end - - %------------------------------------ - % Fold in the Doppler direction - %------------------------------------ - af_lag_fold=fold_vector_full(af_lag_slice,L,time_dec); - - %------------------------------------ - % DFT the lag slice to the time--lag - % domain. - %------------------------------------ - R_lag_slice=ifft(af_lag_fold); - tfd(:,m_real(m+1))=real(R_lag_slice); - tfd(:,m_imag(m+1))=imag(R_lag_slice); -end - - -if(DBmem), s=whos; fprintf('R: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -%------------------------------------------------------------------------- -% 4. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -m=0:Jh; mb=1:(Jh-1); -for n=0:2:(L-2) - R_even_half=complex(tfd(n+1,m_real),tfd(n+1,m_imag)); - R_odd_half =complex(tfd(n+2,m_real),tfd(n+2,m_imag)); - - R_tslice_even=zeros(J,1); R_tslice_odd=zeros(J,1); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_odd(m+1) =R_odd_half(m+1); - R_tslice_even(J-mb+1)=conj( R_even_half(mb+1) ); - R_tslice_odd(J-mb+1) =conj( R_odd_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(n+1,1:J)=real(tfd_time_slice); - tfd(n+2,1:J)=imag(tfd_time_slice); -end - - -% one extra FFT if L is odd: -if(rem(L,2)) - R_even_half=complex(tfd(L,m_real),tfd(L,m_imag)); - - R_tslice_even=zeros(J,1); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_even(J-mb+1)=conj( R_even_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(L,1:J)=real(tfd_time_slice); -end - -tfd=tfd(:,1:J); - -if(DBmem), s=whos; fprintf('end: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -scale_factor=1/N; -tfd=tfd.*scale_factor; - -if(DBtime), dispVars( toc(time_start) ); end - - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,kern_type,kern_params); - if(DBtime), dispVars( toc(time_start) ); end - - dispEE(tfd_test(n_seq+1,k_seq+1),tfd); -end -if(DBverbose) - fprintf('size=%dx%d; max=%g; total energ:%d\n', size(tfd,1), size(tfd,2), max(tfd(:)), ... - sum(tfd(:))); -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); - - figure(9); clf; hold all; - subplot(211); hold all; plot(sum(tfd')'); plot( abs(z(1:N)).^2 ); - subplot(212); hold all; plot(sum(tfd')' - abs(z(n_seq+1)).^2 ); - - figure(10); clf; hold all; - Z=fft(z); - subplot(211); hold all; plot(sum(tfd)); plot( abs(Z(1:N)).^2./(2*N) ); - subplot(212); hold all; plot(sum(tfd)' - abs(Z(k_seq+1)).^2./(2*N) ); -end - - - -function G1=get_prod_kernel(tfd_type,tfd_params,N) -%--------------------------------------------------------------------- -% Generate window for product-kernel -%--------------------------------------------------------------------- - -if( strcmp(tfd_type,'RID')==1 || strcmp(tfd_type,'prod')==1 || ... - strcmp(tfd_type,'product')==1 ) - -% $$$ % oversample the window: -% $$$ L_dopp=N*N2; - - G1=gen_Doppler_kern(tfd_params,N); - G1=real(G1); -else - G1=[]; -end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_sep_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_sep_gdtfd.m deleted file mode 100644 index 99fb4ed8..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/decimated_TFDs/dec_sep_gdtfd.m +++ /dev/null @@ -1,241 +0,0 @@ -%------------------------------------------------------------------------------- -% dec_sep_gdtfd: Decimated TFD with separable kernel of the form g[l,m]=G1[l]g2[m]. For -% efficient implement define windows G1[l] and g2[m] as band-limited functions. -% -% TFD is decimated with integer factors a,b as ρ[an,bk] -% -% Syntax: tfd=dec_sep_gdtfd(x,dopp_win_params,lag_win_params,time_dec,freq_dec,Ntime,Nfreq) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% dopp_win_params = Doppler window parameters in cell form: -% {win_length,win_type,win_param,Doppler_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] Doppler_or_not is either 1 (define window in the Doppler -% domain, which is the default) or 0 (define window in the time domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% lag_win_params = lag window parameters in cell form: -% {win_length,win_type,win_param,lag_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] lag_or_not is either 0 (define window in the lag -% domain, which is the default) or 1 (define window the frequency domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% time_dec = decimation factor a in the time domain; a/Ntime is integer -% freq_dec = decimation factor b in the frequency domain; b/Nfreq is integer -% -% Nfreq = frequency oversampling value; must be greater than length of lag window -% Ntime = time oversampling value; must be greater than length of Doppler window -% -% Outputs: -% tfd = (a/Ntime) x (b/Nfreq) time–frequency distribution -% -% See also: SEP_GDTFD, GET_ANALYTIC_SIGNAL, GEN_LAG_KERN, GEN_DOPPLER_KERN, FFT -% -% Example: -% N=1024; Ntime=64; Nfreq=128; a=1; b=2; -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% c=dec_sep_gdtfd(x,{51,'hann'},{101,'hann'},a,b,Ntime,Nfreq); -% vtfd(c,x); - -% John M. O' Toole, University College Cork -% Started: 24-04-2014 -% -% last update: Time-stamp: <2014-07-23 15:25:51 (otoolej)> -%------------------------------------------------------------------------------- -function tfd=dec_sep_gdtfd(x,dopp_win_params,lag_win_params,time_dec,freq_dec,Ntime, ... - Nfreq) -if(nargin<2 || isempty(dopp_win_params)), dopp_win_params={51,'hann'}; end -if(nargin<3 || isempty(lag_win_params)), lag_win_params={151,'hann'}; end -if(nargin<4 || isempty(time_dec)), time_dec=1; end -if(nargin<5 || isempty(freq_dec)), freq_dec=1; end -if(nargin<6 || isempty(Ntime)), Ntime=[]; end -if(nargin<7 || isempty(Nfreq)), Nfreq=[]; end - -DBplot=0; -DBmem=0; -DBtest=0; -DBtime=0; -DBverbose=0; - - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. generate kernel windows and check decimation parameters -%--------------------------------------------------------------------- -[G1,Q,Ntime]=gen_Doppler_kern(dopp_win_params,N,Ntime); -Qh=ceil(Q/2); - -[g2,P,Ph_floor,Nfreq]=gen_lag_kern(lag_win_params,N,Nfreq); -Nh=ceil(Nfreq/2); Ph=ceil(P/2); - - -% check decimation parameters and return as sequence: -if(length(time_dec)>1 || length(freq_dec)>1) - error('Frequency and time decimation parameters should be scalar'); -end -[n_seq,L,time_dec]=check_dec_params_seq(time_dec,Ntime,'time',1); -[k_seq,J,freq_dec]=check_dec_params_seq(freq_dec,Nfreq,'frequency',1); -Jh=ceil(J/2); J_extend=2*Jh+2; P_extend=2*Ph+2; - -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -tfd=zeros(L,J_extend); -m_real=1:(Jh+1); m_imag=(J_extend-Jh):(J_extend); - -if(DBverbose), - dispVars(N,Ntime,Nfreq,L,J,Jh,J_extend,P,Ph,Q,Qh,P_extend); - dispVars(length(m_real),length(m_imag),m_real(end),m_imag(1)); -end - -if(DBmem), s=whos; fprintf('declare TFD: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -%--------------------------------------------------------------------- -% 2. generate time--lag signal function (for positive-lag values only) -%--------------------------------------------------------------------- -l=0:(Qh-1); lb=1:(Qh-1); -n=0:N-1; -for m=0:Jh - - %------------------------------------------------------------------------- - % a) Form lag-slice of windowed time-lag function and then fold in - % the lag direction. - %------------------------------------------------------------------------- - R_lag_slice=zeros(N,1); - for p=0:freq_dec-1 - mmod=p.*J+m; - - if(mmod<=Ph) - inp=mod(n+mmod,N2); inn=mod(n-mmod,N2); - i1=mod(n+mmod,N2); i2=mod(n-mmod,N2); - - R_lag_slice=R_lag_slice+z(inp+1).*conj(z(inn+1)).*g2(mmod+1); - elseif(mmod>Nfreq-Ph) - inp=mod(n+Nfreq-mmod,N2); inn=mod(n-Nfreq+mmod,N2); - - R_lag_slice=R_lag_slice+conj(z(inp+1)).*z(inn+1).*g2(P-Nfreq+mmod+1); - end - end - - - %------------------------------------------------------------------------- - % b) DFT to the Doppler--lag domain.. - %------------------------------------------------------------------------- - R_lag_slice=fft(R_lag_slice); - - %------------------------------------------------------------------------- - % c) Multiply by Doppler window G1 - %------------------------------------------------------------------------- - r_lag_slice=zeros(Ntime,1); - r_lag_slice(l+1)=R_lag_slice(l+1).*G1(l+1); - r_lag_slice(Ntime-lb+1)=R_lag_slice(N-lb+1).*G1(Q-lb+1); - - %------------------------------------------------------------------------- - % d) Fold in the Doppler direction - %------------------------------------------------------------------------- - r_lag_fold=fold_vector_full(r_lag_slice,L,time_dec); - - %------------------------------------------------------------------------- - % e) DFT the lag slice to the time--lag domain - %------------------------------------------------------------------------- - r_lag_fold=ifft(r_lag_fold); - - tfd(:,m_real(m+1))=real(r_lag_fold); - tfd(:,m_imag(m+1))=imag(r_lag_fold); -end - - -if(DBmem), s=whos; fprintf('R: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -%------------------------------------------------------------------------- -% 4. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -m=0:Jh; mb=1:(Jh-1); -for n=0:2:(L-2) - R_even_half=complex(tfd(n+1,m_real),tfd(n+1,m_imag)); - R_odd_half =complex(tfd(n+2,m_real),tfd(n+2,m_imag)); - - R_tslice_even=zeros(J,1); R_tslice_odd=zeros(J,1); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_odd(m+1) =R_odd_half(m+1); - R_tslice_even(J-mb+1)=conj( R_even_half(mb+1) ); - R_tslice_odd(J-mb+1) =conj( R_odd_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(n+1,1:J)=real(tfd_time_slice); - tfd(n+2,1:J)=imag(tfd_time_slice); -end - -% one extra FFT if L is odd: -if(rem(L,2)) - R_even_half=complex(tfd(L,m_real),tfd(L,m_imag)); - - R_tslice_even=zeros(J,1); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_even(J-mb+1)=conj( R_even_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(L,1:J)=real(tfd_time_slice); -end - -tfd=tfd(:,1:J); - -if(DBmem), s=whos; fprintf('end: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -scale_factor=1/Nfreq; -tfd=tfd.*scale_factor; - -if(DBtime), dispVars( toc(time_start) ); end - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,'sep',{dopp_win_params,lag_win_params}); - if(DBtime), dispVars( toc(time_start) ); end - - a=N/Ntime; b=N/Nfreq; - if( a==floor(a) && b==floor(b) ) - dispEE(tfd_test( (a.*n_seq)+1,(b.*k_seq)+1),tfd./(a*b)); - end - -% $$$ figure(100); clf; hold all; -% $$$ k=10; plot(tfd_test(n_seq+1,k_seq(k)+1)); plot(tfd(:,k+1)); -% $$$ keyboard; -end -if(DBverbose) - fprintf('size=%dx%d; max=%g; total energ:%d\n', size(tfd,1), size(tfd,2), max(tfd(:)), ... - sum(tfd(:))); -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); - -% $$$ figure(9); clf; hold all; -% $$$ subplot(211); hold all; plot(sum(tfd')'); plot( abs(z(1:N)).^2 ); -% $$$ subplot(212); hold all; plot(sum(tfd')' - abs(z(n_seq+1)).^2 ); -% $$$ -% $$$ figure(10); clf; hold all; -% $$$ Z=fft(z); -% $$$ subplot(211); hold all; plot(sum(tfd)); plot( abs(Z(1:N)).^2./(2*N) ); -% $$$ subplot(212); hold all; plot(sum(tfd)' - abs(Z(k_seq+1)).^2./(2*N) ); -end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/di_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/di_gdtfd.m deleted file mode 100644 index c9b21876..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/di_gdtfd.m +++ /dev/null @@ -1,157 +0,0 @@ -%------------------------------------------------------------------------------- -% di_gdtfd: TFD with Doppler-independent (DI) kernel g[l,m]=g₂[m] -% -% Syntax: tfd=di_gdtfd(x,lag_win_params,Nfreq) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% lag_win_params = lag window parameters in cell form: -% {win_length,win_type,win_param,lag_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] lag_or_not is either 0 (define window in the lag -% domain, which is the default) or 0 (define window the frequency domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% Nfreq = frequency oversampling value; must be greater than length of lag window -% -% Outputs: -% tfd = N x Nfreq time-frequency distribution -% -% See also: DEC_DI_GDTFD, GET_ANALYTIC_SIGNAL, GEN_LAG_KERN, FFT -% -% Example: -% N=512; Ntime=256; Nfreq=256; -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% c=di_gdtfd(x,{51,'hann'},Nfreq); -% vtfd(c,x); - -% John M. O' Toole, University College Cork -% Started: 16-04-2014 -% -% last update: Time-stamp: <2014-07-23 16:31:30 (otoolej)> -%------------------------------------------------------------------------------- -function tfd=di_gdtfd(x,lag_win_params,Nfreq) -if(nargin<2 || isempty(lag_win_params)), lag_win_params={101,'hamm'}; end -if(nargin<3 || isempty(Nfreq)), Nfreq=[]; end - - -DBplot=0; -DBmem=0; -DBcompare=0; -DBtest=0; -DBtime=0; - - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. generate time--lag signal function (for positive-lag values only) -%--------------------------------------------------------------------- -[g2,P,Ph_floor,Nfreq]=gen_lag_kern(lag_win_params,N,Nfreq); -Nh=ceil(Nfreq/2); -Ph=ceil(P/2); - -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=zeros(N,Nfreq); -m_real=1:Ph; m_imag=(Nfreq-Ph+1):Nfreq; - -m=0:(Ph-1); -for n=0:N-1 - inp=mod(n+m,N2); inn=mod(n-m,N2); - K_time_slice=g2(m+1).*z(inp+1).*conj( z(inn+1) ); - - tfd(n+1,m_real)=real( K_time_slice ); - tfd(n+1,m_imag)=imag( K_time_slice ); -end - - -if(DBcompare) - K=zeros(N,Nh); - for n=0:N-1 - inp=mod(n+m,N2); inn=mod(n-m,N2); - K(n+1,m+1)=g2(m+1).*z(inp+1).*conj( z(inn+1) ); - end - Ktest=complex(tfd(:,m_real),tfd(:,m_imag)); - dispEE(Ktest,K(:,m+1)); -end -if(DBmem), s=whos; fprintf('K: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -%------------------------------------------------------------------------- -% 3. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -m=0:(Ph-1); mb=1:(Ph-1); -for n=0:2:N-2 - R_even_half=complex(tfd(n+1,m_real),tfd(n+1,m_imag)); - R_odd_half =complex(tfd(n+2,m_real),tfd(n+2,m_imag)); - - R_tslice_even=zeros(1,Nfreq); R_tslice_odd=zeros(1,Nfreq); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_odd(m+1) =R_odd_half(m+1); - R_tslice_even(Nfreq-mb+1)=conj( R_even_half(mb+1) ); - R_tslice_odd(Nfreq-mb+1) =conj( R_odd_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(n+1,:)=real(tfd_time_slice); - tfd(n+2,:)=imag(tfd_time_slice); -end - -if(DBmem), s=whos; fprintf('tfd: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -if(DBcompare) - Rfull=zeros(N,Nfreq); - Rfull(:,m+1)=K(:,m+1); - Rfull(:,Nfreq-mb+1)=conj( Rfull(:,mb+1) ); - - tfd_test=fft( Rfull.' ).'; - dispEE(tfd_test,tfd); -end - - -if(DBmem), s=whos; fprintf('end: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -scale_factor=1/Nfreq; -tfd=tfd.*scale_factor; - - -if(DBtime), dispVars( toc(time_start) ); end - - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,'pwvd',{P,lag_win_params{2:end}}); - if(DBtime), dispVars( toc(time_start) ); end - if(Nfreq==N) - dispEE(tfd_test,tfd); - else - b=N/Nfreq; - if( b==floor(b) ) - dispEE(tfd_test(:,1:b:end),tfd./b); - end - end -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); - - figure(9); clf; hold all; - subplot(211); hold all; plot(sum(tfd')'); plot( abs(z(1:N)).^2 ); - subplot(212); hold all; plot(sum(tfd')' - abs(z(1:N)).^2 ); -end - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/li_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/li_gdtfd.m deleted file mode 100644 index 05589744..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/li_gdtfd.m +++ /dev/null @@ -1,190 +0,0 @@ -%------------------------------------------------------------------------------- -% li_gdtfd: TFD with lag-independent (LI) kernel g[l,m]=G₁[l] -% -% Syntax: tfd=li_gdtfd(x,dopp_win_params,Ntime) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% dopp_win_params = Doppler window parameters in cell form: -% {win_length,win_type,win_param,Doppler_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] Doppler_or_not is either 1 (define window in the Doppler -% domain, which is the default) or 0 (define window the time domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% Ntime = time oversampling value; must be greater than length of Doppler window -% -% Outputs: -% tfd = Ntime x N time-frequency distribution -% -% See also: DEC_LI_GDTFD, GET_ANALYTIC_SIGNAL, GEN_DOPPLER_KERN, FFT -% -% Example: -% N=10000; Ntime=256; -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% c=li_gdtfd(x,{51,'hamm'},Ntime); -% vtfd(c,x); -% -% Example: -% -% - -% John M. O' Toole, University College Cork -% Started: 16-04-2014 -% -% last update: Time-stamp: <2014-07-23 15:28:16 (otoolej)> -%------------------------------------------------------------------------------- -function [tfd,G1]=li_gdtfd(x,dopp_win_params,Ntime) -if(nargin<2 || isempty(dopp_win_params)), dopp_win_params={11,'hamm',0,1}; end -if(nargin<3 || isempty(Ntime)), Ntime=[]; end - - -DBplot=0; -DBmem=0; -DBcompare=0; -DBtest=0; -DBtime=0; - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. generate Doppler--frequency signal function -% (for positive-Doppler values only) -%--------------------------------------------------------------------- -[G1,Q,Ntime]=gen_Doppler_kern(dopp_win_params,N,Ntime); -Nh=ceil(Ntime/2); -Qh=ceil(Q/2); - -Z=fft(z); -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=zeros(Ntime,N); -l_real=1:Qh; l_imag=(Ntime-Qh+1):Ntime; - - -l=0:(Qh-1); -for k=0:N-1 - inp=mod(k+l,N2); inn=mod(k-l,N2); - inpN=mod(k+l+N,N2); innN=mod(k-l-N,N2); - K_doppler_slice=G1(l+1).*( Z(inp+1).*conj( Z(inn+1) ) + ... - Z(inpN+1).*conj( Z(innN+1) ) ); - - tfd(l_real,k+1)=real( K_doppler_slice )./2; - tfd(l_imag,k+1)=imag( K_doppler_slice )./2; -end - - -% $$$ Ktesting=zeros(N,ceil(N/2)+1); m=0:(ceil(N/2)); -% $$$ for n=0:N-1 -% $$$ inp=mod(n+m,N2); inn=mod(n-m,N2); -% $$$ Ktesting(n+1,m+1)=z(inp+1).*conj( z(inn+1) ); -% $$$ end -% $$$ Kfull=zeros(N); mb=1:(ceil(N/2)-1); -% $$$ Kfull(:,m+1)=Ktesting(:,m+1); -% $$$ Kfull(:,N-mb+1)=conj( Ktesting(:,mb+1) ); -% $$$ -% $$$ Ktest=complex(tfd(l_real,:),tfd(l_imag,:)); -% $$$ kk=fft(fft(Kfull.').'); -% $$$ kk=kk(l+1,:).*2; -% $$$ dispVars(size(kk),size(Ktest)); -% $$$ dispEE(Ktest,kk); -% $$$ figure(10); clf; vtfd(abs(Ktest)); -% $$$ figure(11); clf; vtfd(abs(Ktest-kk)); - -if(DBcompare) - K=zeros(Nh,N); - for k=0:N-1 - inp=mod(k+l,N2); inn=mod(k-l,N2); - inpN=mod(k+l+N,N2); innN=mod(k-l-N,N2); - K(l+1,k+1)=G1(l+1).*( Z(inp+1).*conj( Z(inn+1) ) + ... - Z(inpN+1).*conj( Z(innN+1) ) ); - end - Ktest=complex(tfd(l_real,:),tfd(l_imag,:)); - dispEE(Ktest,K(l+1,:)); -end -if(DBmem), s=whos; fprintf('K: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - - - -%------------------------------------------------------------------------- -% 3. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -l=0:(Qh-1); lb=1:(Qh-1); -for k=0:2:N-2 - R_even_half=complex(tfd(l_real,k+1),tfd(l_imag,k+1)); - R_odd_half =complex(tfd(l_real,k+2),tfd(l_imag,k+2)); - - R_tslice_even=zeros(Ntime,1); R_tslice_odd=zeros(Ntime,1); - R_tslice_even(l+1)=R_even_half(l+1); - R_tslice_odd(l+1) =R_odd_half(l+1); - R_tslice_even(Ntime-lb+1)=conj( R_even_half(lb+1) ); - R_tslice_odd(Ntime-lb+1) =conj( R_odd_half(lb+1) ); - - tfd_time_slice=ifft( R_tslice_even+j.*R_tslice_odd ); - - tfd(:,k+1)=real(tfd_time_slice); - tfd(:,k+2)=imag(tfd_time_slice); -end - -if(DBmem), s=whos; fprintf('tfd: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - - -if(DBcompare) - Rfull=zeros(Ntime,N); - Rfull(l+1,:)=K(l+1,:); - Rfull(Ntime-lb+1,:)=conj( Rfull(lb+1,:) ); - - tfd_test=ifft( Rfull ); - dispEE(tfd_test,tfd); -end - - -if(DBmem), s=whos; fprintf('end: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -scale_factor=1/N; -tfd=tfd.*scale_factor; - -if(DBtime), dispVars( toc(time_start) ); end - - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,'swvd',dopp_win_params); - if(DBtime), dispVars( toc(time_start) ); end - if(Ntime==N) - dispEE(tfd_test,tfd); - else - a=N/Ntime; - if( a==floor(a) ) - dispEE(tfd_test(1:a:end,:),tfd./a); - end - end -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); - - figure(9); clf; hold all; - Z=fft(z); - subplot(211); hold all; plot(sum(tfd)); plot( abs(Z(1:N)).^2./(2*N) ); - subplot(212); hold all; plot(sum(tfd)' - abs(Z(1:N)).^2./(2*N) ); -end - - - - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/nonsep_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/nonsep_gdtfd.m deleted file mode 100644 index a5471dd5..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/nonsep_gdtfd.m +++ /dev/null @@ -1,196 +0,0 @@ -%------------------------------------------------------------------------------- -% nonsep_gdtfd: Time-frequency distribution (quadratic class) with non-separable kernel -% -% Syntax: [tfd,g]=nonsep_gdtfd(x,kern_type,kern_params) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% kern_type = { 'wvd' | 'swvd' | 'pwvd' | 'sep' | 'cw' | 'mb' } -% wvd - Wigner-Ville distribution -% swvd - Smoothed Wigner-Ville distribution -% (lag-independent kernel) -% pwvd - Pseudo Wigner-Ville distribution -% (Doppler-independent kernel) -% sep - Separable-kernel distribution -% (combintation of SWVD and PWVD) -% mb - Modified-B distribution -% cw - Choi-Williams distribution -% -% kern_params = cell of kernel parameters: -% wvd - {} -% swvd - {win_length,win_type,[win_param]} -% e.g. {11,'hamm'} -% pwvd - {win_length,win_type,[win_param]} -% e.g. {200,'cosh',0.1 -% sep - { {win1_length,win1_type,[win1_param]}, -% {win2_length,win2_type,[win2_param]} -% where win1 is the doppler window and win2 is the -% lag window, e.g. { {11,'hamm'}, {200,'cosh',0.1} } -% mb - {beta_parameter} in the range 1 -%------------------------------------------------------------------------------- -function tfd=nonsep_gdtfd(x,kern_type,kern_params) -if(nargin<2 || isempty(kern_type)), kern_type='cw'; end -if(nargin<3 || isempty(kern_params)), kern_params=10; end - - -DBplot=0; -DBmem=0; -DBcompare=0; -DBtest=0; -DBtime=0; - - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. generate time--lag signal function (for positive-lag values only) -%--------------------------------------------------------------------- -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=zeros(N,N); -m_real=1:Nh; m_imag=(Nh+1):N; - -m=0:(Nh-1); -for n=0:N-1 - inp=mod(n+m,N2); inn=mod(n-m,N2); - K_time_slice=z(inp+1).*conj( z(inn+1) ); - - tfd(n+1,m_real)=real( K_time_slice ); - tfd(n+1,m_imag)=imag( K_time_slice ); -end - -if(DBcompare) - for n=0:N-1 - inp=mod(n+m,N2); inn=mod(n-m,N2); - K(n+1,m+1)=z(inp+1).*conj( z(inn+1) ); - end - Ktest=complex(tfd(:,m_real),tfd(:,m_imag)); - dispEE(Ktest,K); -end - - -if(DBmem), s=whos; fprintf('K: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -% $$$ if(strcmp(kern_type,'wvd')) -% $$$ for n=0:2:N-2 -% $$$ -% $$$ tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); -% $$$ -% $$$ tfd(n+1,:)=real(tfd_time_slice); -% $$$ tfd(n+2,:)=imag(tfd_time_slice); -% $$$ end -% $$$ -% $$$ -% $$$ dispVars('here'); -% $$$ return; -% $$$ end - - -%------------------------------------------------------------------------- -% 3. multiply kernel and signal function in the Doppler-lag domain -%------------------------------------------------------------------------- -for m=0:Nh-1 - g_lag_slice=gen_Doppler_lag_kern(kern_type,kern_params,N,m+1); - - R_lag_slice=ifft( fft( complex(tfd(:,m_real(m+1)),tfd(:,m_imag(m+1))) ).*g_lag_slice ); - - - tfd(:,m_real(m+1))=real( R_lag_slice ); - tfd(:,m_imag(m+1))=imag( R_lag_slice ); -end - -if(DBcompare) - g=gen_Doppler_lag_kern(kern_type,kern_params,N); - R=ifft( fft(K).*g(:,1:Nh) ); - Rtest=complex(tfd(:,m_real),tfd(:,m_imag)); - dispEE(Rtest,R); - clear g; -end - - -if(DBmem), s=whos; fprintf('R: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - - - -%------------------------------------------------------------------------- -% 4. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -m=0:(Nh-1); mb=1:(Nh-1); -for n=0:2:N-2 - R_even_half=complex(tfd(n+1,m_real),tfd(n+1,m_imag)); - R_odd_half =complex(tfd(n+2,m_real),tfd(n+2,m_imag)); - - R_tslice_even=zeros(1,N); R_tslice_odd=zeros(1,N); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_odd(m+1) =R_odd_half(m+1); - R_tslice_even(N-mb+1)=conj( R_even_half(mb+1) ); - R_tslice_odd(N-mb+1) =conj( R_odd_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(n+1,:)=real(tfd_time_slice); - tfd(n+2,:)=imag(tfd_time_slice); -end - -if(DBmem), s=whos; fprintf('tfd: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -if(DBcompare) - Rfull=zeros(N); - Rfull(:,m+1)=R; - Rfull(:,N-mb+1)=conj( Rfull(:,mb+1) ); - - tfd_test=fft( Rfull.' ).'; - dispEE(tfd_test,tfd); -end - -if(DBmem), s=whos; fprintf('end: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=tfd./N; - - -if(DBtime), dispVars( toc(time_start) ); end - -if(DBtest) - if(DBtime), time_start=tic; end - tfd_test=full_gdtfd_testing_version(x,kern_type,kern_params); - if(DBtime), dispVars( toc(time_start) ); end - dispEE(tfd_test,tfd); -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); -end - -tfd = tfd'; - - - - - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/sep_gdtfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/sep_gdtfd.m deleted file mode 100644 index 6999f19f..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_TFDs/sep_gdtfd.m +++ /dev/null @@ -1,199 +0,0 @@ -%------------------------------------------------------------------------------- -% sep_gdtfd: Time--frequency distribution (quadratic class) with separable kernel of -% the form g[l,m]=G₁[l]g₂[m] -% -% Syntax: tfd=sep_gdtfd(x,dopp_win_params,lag_win_params,Ntime,Nfreq) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% dopp_win_params = Doppler window parameters in cell form: -% {win_length,win_type,win_param,Doppler_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] Doppler_or_not is either 1 (define window in the Doppler -% domain, which is the default) or 0 (define window the time domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% lag_win_params = lag window parameters in cell form: -% {win_length,win_type,win_param,lag_or_not} where -% - win_length is the sample length of the window -% - win_type is the type of window -% - [optional] win_param is the parameter of the window -% - [optional] lag_or_not is either 0 (define window in the lag -% domain, which is the default) or 0 (define window the frequency domain) -% e.g. {121, 'hamm'}; {121, 'tukey', 0.2}; {127,'cosh',0.01,0} -% -% Nfreq = frequency oversampling value; must be greater than length of lag window -% Ntime = time oversampling value; must be greater than length of Doppler window -% -% Outputs: -% tfd = Ntime x Nfreq time-frequency distribution -% -% See also: DEC_SEP_GDTFD, GET_ANALYTIC_SIGNAL, GEN_LAG_KERN, GEN_DOPPLER_KERN, FFT -% -% Example: -% N=10000; Ntime=256; Nfreq=256; -% x=gen_LFM(N,0.1,0.3)+gen_LFM(N,0.4,0.1); -% -% c=sep_gdtfd(x,{51,'hann'},{171,'hann'},Ntime,Nfreq); -% vtfd(c,x); - - -% John M. O' Toole, University College Cork -% Started: 16-04-2014 -% -% last update: Time-stamp: <2019-02-19 15:12:35 (otoolej)> -%------------------------------------------------------------------------------- -function tfd=sep_gdtfd(x,dopp_win_params,lag_win_params,Ntime,Nfreq) -if(nargin<4 || isempty(Ntime)), Ntime=[]; end -if(nargin<5 || isempty(Nfreq)), Nfreq=[]; end - -DBplot=0; -DBmem=0; -DBcompare=0; -DBtest=0; -DBtime=0; - -if(DBtime), time_start=tic; end -%--------------------------------------------------------------------- -% 1. convert real-valued signal to analytic signal of length 2N -%--------------------------------------------------------------------- -[z,N2,N,Nh]=get_analytic_signal(x); - - -%--------------------------------------------------------------------- -% 2. compute lag and Doppler windows -%--------------------------------------------------------------------- -[g2,P,Ph_floor,Nfreq]=gen_lag_kern(lag_win_params,N,Nfreq); -Nh_freq=ceil(Nfreq/2); -Ph=ceil(P/2); -[G1,Q,Ntime,G1_pad]=gen_Doppler_kern(dopp_win_params,N,Ntime); -Nh_time=ceil(Ntime/2); -Qh=ceil(Q/2); - - -%--------------------------------------------------------------------- -% 3. convolve signal function with kernel (multiplication in the -% Doppler--lag domain). Do this in stages to minimise memory -%--------------------------------------------------------------------- -if(DBmem), s=whos; fprintf('start: mem=%s\n',disp_bytes(sum([s.bytes]))); end -tfd=zeros(Ntime,Nfreq); - -if(DBmem), s=whos; fprintf('tfd declare: mem=%s\n',disp_bytes(sum([s.bytes]))); end - -n=0:N-1; l=0:(Qh-1); lb=1:(Qh-1); -for m=0:(Ph-1); - inp=mod(n+m,N2); inn=mod(n-m,N2); - K_lag_slice=g2(m+1).*z(inp+1).*conj( z(inn+1) ); - - K_lag_slice=fft(K_lag_slice); - - R_lag_slice=zeros(Ntime,1); - R_lag_slice(l+1)=K_lag_slice(l+1).*G1(l+1); - R_lag_slice(Ntime-lb+1)=K_lag_slice(N-lb+1).*G1(Q-lb+1); - - R_lag_slice=ifft(R_lag_slice); - - tfd(:,m+1)=real( R_lag_slice ); - tfd(:,m+Nh_freq+1)=imag( R_lag_slice ); -end - -if(DBmem), s=whos; fprintf('R: mem=%s\n',disp_bytes(sum([s.bytes]))); end - - - -if(DBcompare) - K=zeros(N,Nh_freq); - m=0:(Ph-1); - for n=0:N-1 - inp=mod(n+m,N2); inn=mod(n-m,N2); - K(n+1,m+1)=g2(m+1).*z(inp+1).*conj( z(inn+1) ); - end - af=fft(K); - - R=zeros(Ntime,Nh_freq); - for m=0:Ph-1 - R(l+1,m+1)=af(l+1,m+1).*G1(l+1); - R(Ntime-lb+1,m+1)=af(N-lb+1,m+1).*G1(Q-lb+1); - - R(:,m+1)=ifft(R(:,m+1)); - end - Rtest=complex(tfd(:,1:Nh_freq),tfd(:,(Nh_freq+1):end)); - dispEE(R,Rtest); - clear Rtest K af; -end - - -%------------------------------------------------------------------------- -% 4. Expand R for positive and negative lag values and DFT back to -% time--frequency domain -%------------------------------------------------------------------------- -m=0:(Ph-1); mb=1:(Ph-1); -k_real=1:Nh_freq; k_imag=(Nh_freq+1):Nfreq; - -for n=0:2:Ntime-2 - R_even_half=complex(tfd(n+1,k_real),tfd(n+1,k_imag)); - R_odd_half =complex(tfd(n+2,k_real),tfd(n+2,k_imag)); - - R_tslice_even=zeros(1,Nfreq); R_tslice_odd=zeros(1,Nfreq); - R_tslice_even(m+1)=R_even_half(m+1); - R_tslice_odd(m+1) =R_odd_half(m+1); - R_tslice_even(Nfreq-mb+1)=conj( R_even_half(mb+1) ); - R_tslice_odd(Nfreq-mb+1) =conj( R_odd_half(mb+1) ); - - tfd_time_slice=fft( R_tslice_even+j.*R_tslice_odd ); - - tfd(n+1,:)=real(tfd_time_slice); - tfd(n+2,:)=imag(tfd_time_slice); -end - -if(DBmem), s=whos; fprintf('tfd (end): mem=%s\n',disp_bytes(sum([s.bytes]))); end - - -if(DBcompare) - Rfull=zeros(Ntime,Nfreq); - Rfull(:,m+1)=R(:,m+1); - Rfull(:,Nfreq-mb+1)=conj( Rfull(:,mb+1) ); - - tfd_test=fft( Rfull.' ).'; - dispEE(tfd_test,tfd); - clear R test_test; -end - -scale_factor=1/Nfreq; -tfd=tfd.*scale_factor; - - -%--------------------------------------------------------------------- -% END; testing and plotting -%--------------------------------------------------------------------- -if(DBtime), dispVars( toc(time_start) ); end - -if(DBtest) % && Ntime==N && Nfreq==N) - if(DBtime) - dispVars( toc(time_start) ); - time_start=tic; - end - tfd_test=full_gdtfd_testing_version(x,'sep',{dopp_win_params,lag_win_params}); - - if(DBtime), dispVars( toc(time_start) ); end - -% $$$ dispVars( sum(tfd_test(:)), sum(tfd(:)) ); - if(Ntime==N && Nfreq==N) - dispEE(tfd_test,tfd); - else - a=N/Ntime; b=N/Nfreq; - if( a==floor(a) && b==floor(b) ) - dispEE(tfd_test(1:a:end,1:b:end),tfd./(a*b)); - end - end -end -if(DBplot) - figure(1); clf; - vtfd(tfd,real(x(1:N))); -end - - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_tfd.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_tfd.m deleted file mode 100644 index a03d0ddc..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/full_tfd.m +++ /dev/null @@ -1,144 +0,0 @@ -%------------------------------------------------------------------------------- -% full_tfd: -% -% Syntax: tf=full_tfd(x,kern_type,kern_params,Ntime,Nfreq) -% -% Inputs: -% x = input signal (either real-valued signal of length-N or -% complex-valued analytic signal of length-2N) -% -% kern_type = kernel type, either nonseparable, separable, Doppler-independent -% (DI) or lag-independent (LI): { 'nonsep' | 'sep' | 'DI' | 'LI' } -% -% kern_params = kernel parameters; different depending on kernel type -% -% if nonseparable kernel, then form: { kern_name, kern_param} -% e.g. tf=full_tfd( x, 'nonsep', { 'cw', 100 } ); -% -% if Doppler-independent kernel, then of the form: -% { window_length, window_type, [window_parameter (optional)] } -% e.g. tf=full_tfd( x, 'DI', {101,'hann'} ); -% -% if lag-independent kernel, then of the form: -% { window_length, window_type, [window_parameter (optional)] } -% e.g. tf=full_tfd( x, 'LI', {101,'cosh',0.01} ); -% -% if separable kernel, then of the form: { doppler_window, lag_window } -% where doppler_window is of the form: { window_length, window_type, -% [window_parameter (optional)] }; same format for lag window -% e.g. tf=full_tfd( x, 'sep', { {101, 'cosh', 0.05}, {101,'hann'} } ); -% -% Ntime = over-sampling in the time direction; only applicable for separable -% and lag-independent kernels -% -% Nfreq = over-sampling in the frequency direction; only applicable for separable -% and Doppler-independent kernels -% -% Outputs: -% tf = time-frequency distribution of size N x N (nonseparable kernel), -% or Ntime x N (lag-independent kernel), -% or N x Nfreq (Doppler-independent kernel), -% or Ntime x Nfreq (separable kernel) -% -% See also: NONSEP_GDTFD, SEP_GDTFD, LI_GDTFD, DI_GDTFD -% -% Examples: -% N=512; -% x=gen_LFM(N,0.1,0.3) + gen_LFM(N,0.4,0.04); -% -% % nonseparable kernel (Choi-Williams kernel): -% tf=full_tfd(x,'nonsep',{'cw',10}); -% figure(1); clf; vtfd(tf,x); -% -% % separable kernel: -% tf=full_tfd(x,'sep',{{51,'hann'},{101,'hann'}},256,256); -% figure(2); clf; vtfd(tf,x); -% -% % Doppler-independent kernel: -% tf=full_tfd(x,'DI',{101,'hann'},256,[]); -% figure(3); clf; vtfd(tf,x); -% -% % lag-independent kernel: -% tf=full_tfd(x,'LI',{51,'hann'},[],256); -% figure(4); clf; vtfd(tf,x); - - - -% John M. O' Toole, University College Cork -% Started: 11-06-2014 -% -% last update: Time-stamp: <2017-05-30 10:00:46 (otoolej)> -%------------------------------------------------------------------------------- -function tf=full_tfd(x,kern_type,kern_params,Ntime,Nfreq) -if(nargin<2 || isempty(kern_type)), kern_type='sep'; end -if(nargin<3 || isempty(kern_params)), kern_params={{51,'hann'},{101,'hann'}}; end -if(nargin<4 || isempty(Ntime)), Ntime=[]; end -if(nargin<5 || isempty(Nfreq)), Nfreq=[]; end - - -% set to 1 if want to see how much memory is used: -DBmem=1; - - -kern_type=lower(kern_type); -switch kern_type - case { 'nonsep', 'ns', 'nonseparable', 'non-separable', 'non-sep' } - %--------------------------------------------------------------------- - % 1. Non-separable kernel; Doppler-lag form: g[l,m] - %--------------------------------------------------------------------- - nonsep_params=[]; - if(~iscell(kern_params)) - nonsep_name=kern_params; - else - nonsep_name=kern_params{1}; - if(length(kern_params)>1) - nonsep_params=kern_params{2}; - end - end - - tf=nonsep_gdtfd(x,nonsep_name,nonsep_params); - - - case { 'sep', 'separable' } - %--------------------------------------------------------------------- - % 2. separable kernel; Doppler-lag form: G1[l]g2[m] - %--------------------------------------------------------------------- - if(~iscell(kern_params) | (iscell(kern_params) & length(kern_params)<2) ) - error(['separable kernel parameters should be of the form: ' ... - '{ {dopp_win_length,dopp_win_name}, {lag_win_length,lag_win_name} }']); - end - - tf=sep_gdtfd(x,kern_params{1},kern_params{2},Ntime,Nfreq); - - - case { 'di', 'doppler-independent', 'dopp.-indep', 'dopp-indep', 'pwvd', 'p-wvd' } - %--------------------------------------------------------------------- - % 3. Doppler-independent kernel: Doppler-lag form: g2[m] - %--------------------------------------------------------------------- - if(~iscell(kern_params)) - error(['Doppler-independent kernel parameters should be of the form: ' ... - '{win_length,win_name}']); - end - - - tf=di_gdtfd(x,kern_params,Nfreq); - - - case { 'li', 'lag-independent', 'lag-indep', 'swvd', 's-wvd' } - %--------------------------------------------------------------------- - % 4. Lag-independent kernel: Doppler-lag form: G1[l] - %--------------------------------------------------------------------- - if(~iscell(kern_params)) - error(['lag-independent kernel parameters should be of the form: ' ... - '{win_length,win_name}']); - end - - tf=li_gdtfd(x,kern_params,Ntime); - - otherwise - warning('kern_type should be either: nonsep, sep, DI, or LI'); - tf=[]; -end - - -if(DBmem), s=whos; fprintf('total memory used: mem=%s\n',disp_bytes(sum([s.bytes]))); end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/load_curdir.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/load_curdir.m deleted file mode 100644 index df0fc316..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/load_curdir.m +++ /dev/null @@ -1,13 +0,0 @@ - -% what directory is this file in? -cur_full_path=mfilename('fullpath'); -cur_fname=mfilename(); -i=findstr(cur_full_path,cur_fname); -cur_dir=cur_full_path(1:(i-1)); - -% add the paths: -addpath( genpath(cur_dir) ); - - -clear cur_full_path cur_fname cur_dir; - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/pics/decimated_TFDs_examples.png b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/pics/decimated_TFDs_examples.png deleted file mode 100644 index 6d7ddf49..00000000 Binary files a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/pics/decimated_TFDs_examples.png and /dev/null differ diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/pics/full_TFDs_examples.png b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/pics/full_TFDs_examples.png deleted file mode 100644 index 0c74d629..00000000 Binary files a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/pics/full_TFDs_examples.png and /dev/null differ diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/check_dec_params_seq.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/check_dec_params_seq.m deleted file mode 100644 index 3e453e53..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/check_dec_params_seq.m +++ /dev/null @@ -1,79 +0,0 @@ -%------------------------------------------------------------------------------- -% check_dec_params_seq: Check and return arbitrary set from {k_1,k_2,...,k_J} samples -% could be for n (time) sample points also. -% -% Syntax: k=check_dec_params_seq(dec_param,N,time_freq_str) -% -% Inputs: -% dec_param,N,time_freq_str - -% -% Outputs: -% k - -% -% Example: -% -% - -% John M. O' Toole, University College Cork -% Started: 23-04-2014 -% -% last update: Time-stamp: <2014-04-23 15:36:55 (otoolej)> -%------------------------------------------------------------------------------- -function [k,Nfreq,dec_param]=check_dec_params_seq(dec_param,N,time_freq_str,check_param) -if(nargin<3 || isempty(time_freq_str)), time_freq_str='Frequency'; end -if(nargin<4 || isempty(check_param)), check_param=1; end - - - -%--------------------------------------------------------------------- -% 0. check if parameters are ok: -%--------------------------------------------------------------------- -dec_param=unique(dec_param); - -if(~all(dec_param==fix(dec_param))) - error([time_freq_str ' decimation parameters must be integers.']); -end -if(any(dec_param>=N) || any(dec_param<0)) - error([time_freq_str ' decimation values need to within 0<=k<=N-1']); -end - - -%--------------------------------------------------------------------- -% 1. set parameters: -%--------------------------------------------------------------------- -if(length(dec_param)==1) - % decimation parameter is not a sequence: - if(check_param) - dec_param=check_dec_value(dec_param,N,time_freq_str); - end - k=0:dec_param:N-1; - -elseif(length(dec_param)>1) - k=dec_param; -else - k=0:N-1; -end - - -if(any(k>=N) || any(k<0)) - error([time_freq_str ' decimation values need to within 0<=k<=N-1']); -end -Nfreq=length(k); - - -function dec_param=check_dec_value(dec_param,N,time_freq_str) -%--------------------------------------------------------------------- -% check (or set) that N/a is an integer -%--------------------------------------------------------------------- -if(rem(N,dec_param)) - warning(['N not divisable by ' time_freq_str ' decimation factor. Increasing....']); - while( rem(N,dec_param) ) - dec_param=dec_param+1; - end - disp( ['... decimation factor now=' num2str(dec_param)]); - if(dec_param>=N) - error([time_freq_str ' decimation factor is equal to N. N is prime? Pick smaller ' ... - 'decimation parameter']); - dec_param=1; - end -end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/dispEE.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/dispEE.m deleted file mode 100644 index 15d7b237..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/dispEE.m +++ /dev/null @@ -1,9 +0,0 @@ -%% disp error between two matrices .. -function dispEE( a, b ); - -ee = a - b; -diff_re = max( abs(real(ee(:))) ); -diff_im = max( abs(imag(ee(:))) ); -a_name=deblank(inputname(1)); -b_name=deblank(inputname(2)); -fprintf('<< %s - %s = %g + j%g >>\n',a_name,b_name,diff_re,diff_im); diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/dispVars.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/dispVars.m deleted file mode 100644 index 1fc9e5e3..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/dispVars.m +++ /dev/null @@ -1,26 +0,0 @@ -%------------------------------------------------------------------------------- -% Display variables to standard output -% -% DATE: 07-09-2010 -%------------------------------------------------------------------------------- -function dispVars( varargin ) -% $$$ for i=1:nargin -% $$$ keyboard; -% $$$ varargin{i} -% $$$ end - -str = ''; -for i=1:nargin - if( iscell(varargin{i}) ) - for j=1:length(varargin{i}) - str = [ str ' |' char(inputname(i)) '(' num2str(j) ') =' ... - num2str(varargin{i}{j}) ]; - end - else - - str = strcat(str,' |',char(inputname(i)),'=',num2str(varargin{i})); - end - -end - -disp(str); diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/disp_bytes.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/disp_bytes.m deleted file mode 100644 index 08a47896..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/disp_bytes.m +++ /dev/null @@ -1,25 +0,0 @@ -function str = disp_bytes(NumBytes) -% BYTES2STR Private function to take integer bytes and convert it to -% scale-appropriate size. -% - -% taken from 'StackOverflow' response, by 'MatlabSorter', 31/1/11 - -scale = floor(log(NumBytes)/log(1024)); -switch scale - case 0 - str = [sprintf('%.0f',NumBytes) ' b']; - case 1 - str = [sprintf('%.2f',NumBytes/(1024)) ' kb']; - case 2 - str = [sprintf('%.2f',NumBytes/(1024^2)) ' Mb']; - case 3 - str = [sprintf('%.2f',NumBytes/(1024^3)) ' Gb']; - case 4 - str = [sprintf('%.2f',NumBytes/(1024^4)) ' Tb']; - case -inf - % Size occasionally returned as zero (eg some Java objects). - str = 'Not Available'; - otherwise - str = 'Over a petabyte!!!'; -end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/fold_vector_full.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/fold_vector_full.m deleted file mode 100644 index d407016c..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/fold_vector_full.m +++ /dev/null @@ -1,40 +0,0 @@ -%------------------------------------------------------------------------------- -% fold_vector_full: fold the vector for frequency decimation: -% -% y[n] = y[n] + sum_{p=0}^{a-l} x[pJ+n] -% -% for n=0,1,...,J-1 -% -% which returns DFT{y[n]} = Y[ak] -% -% Syntax: y=fold_vector_full(x,J,a) -% -% Inputs: -% x,J,a - -% -% Outputs: -% y - -% -% Example: -% -% - -% John M. O' Toole, University College Cork -% Started: 23-04-2014 -% -% last update: Time-stamp: <2014-04-23 17:11:54 (otoolej)> -%------------------------------------------------------------------------------- -function y=fold_vector_full(x,J,a) -% Assume that all parameters (J,a) are sane. - -y=zeros(J,1); -x=x(:); - -n=0:J-1; -y(n+1)=x(n+1); -for p=1:a-1 - y(n+1)=y(n+1)+x(p*J+n+1); -end - -% scale by decimation factor: -y=y./a; diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/fold_vector_half.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/fold_vector_half.m deleted file mode 100644 index 37e79b1a..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/fold_vector_half.m +++ /dev/null @@ -1,34 +0,0 @@ -%------------------------------------------------------------------------------- -% fold_vector_half: Fold vector -% -% y[n] = y[n] + sum_{p=0}^{a-l} x[pJ+n] -% -% for n=0,1,...,Jh -% -% Syntax: y=fold_vector_half(x,J,Jh,a) -% -% Inputs: -% x,J,Jh,a - -% -% Outputs: -% y - -% -% Example: -% -% - -% John M. O' Toole, University College Cork -% Started: 23-04-2014 -% -% last update: Time-stamp: <2014-04-23 14:05:04 (otoolej)> -%------------------------------------------------------------------------------- -function y=fold_vector_half(x,J,Jh,a) -% Assume that all parameters (J,Jh,a) are sane. - -y=zeros(Jh+1,1); -x=x(:); - -n=0:(Jh); -for p=0:a-1 - y(n+1)=y(n+1)+x(p*J+n+1); -end diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/gen_LFM.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/gen_LFM.m deleted file mode 100644 index 0d781f9f..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/gen_LFM.m +++ /dev/null @@ -1,29 +0,0 @@ -%------------------------------------------------------------------------------- -% Generate a linear frequency modulated (LFM) signal -% -% USE: sig=gen_LFM(N,fstart,fstop,phase) -% -% INPUT: -% N = length of LFM signal -% fstart = starting frequency -% fend = ending frequency -% phase = (optional) phase offset -% -% OUTPUT: -% sig = LFM signal of length-N -% -% EXAMPLE: -% N=256; fstart=0.1; fend=0.4; -% x=gen_LFM(N,fstart,fend); -% plot(x); -%------------------------------------------------------------------------------- -function sig=gen_LFM(N,fstart,fstop,phase) -if(nargin<1 || isempty(N)) N=128; end -if(nargin<2 || isempty(fstart)) fstart=0.1; end -if(nargin<3 || isempty(fstop)) fstop=0.4; end -if(nargin<4 || isempty(phase)) phase=0; end - - - -n=0:N-1; -sig=cos( 2*pi.*(fstart.*n + ((fstop-fstart)/(2*N)).*(n.^2)) + phase ); diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/get_analytic_signal.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/get_analytic_signal.m deleted file mode 100644 index 44879f2d..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/get_analytic_signal.m +++ /dev/null @@ -1,76 +0,0 @@ -%------------------------------------------------------------------------------- -% get_analytic_signal: analytic signal as per [1] -% -% Syntax: [z,N2,N,Nh]=get_analytic_signal(z) -% -% INPUT: -% s = real-valued signal -% -% OUTPUT: -% z = complex-valued analytic signal -% -% EXAMPLE: -% N=64; f=0.1; N2=2*N; -% s=cos( 2*pi*f.*(0:N-1)); -% z=get_analytic_signal(s); -% plot(1:N2,real(z),1:N2,imag(z)); -% legend('real','imaginary'); -% -% -% [1] J. M. O' Toole, M. Mesbah, and B. Boashash, "A New Discrete Analytic Signal for -% Reducing Aliasing in the Discrete Wigner-Ville Distribution", IEEE Trans. on Signal -% Processing, vol. 56, no. 11, pp. 5427-5434, Nov. 2008. - - -% John M. O' Toole, University College Cork -% Started: 14-04-2014 -% -% last update: Time-stamp: <2016-08-11 17:18:41 (otoolej)> -%------------------------------------------------------------------------------- -function [z,N2,N,Nh]=get_analytic_signal(z) -if(rem(length(z),2)) - warn_str=sprintf(['odd-length signal.\nCurrently, code works for even-length signal ' ... - 'only.\n\nRemoving last sample of the signal to force to ' ... - 'even-length.\n']); - warning(warn_str); - z=z(1:(end-1)); -end - - -if(isreal(z)) - z=gen_analytic(z); -else - warn_str=sprintf(['using complex-valued signal; assuming this is an analytic signal ' ... - 'zero-padded to length-2N?\n\n If unsure, input the real part ' ... - 'of signal only, i.e. real(x)\n'] ); - warning(warn_str); -end -N2=length(z); N=N2/2; Nh=ceil(N/2); - -if(N~=fix(N)) - error('Analytic signal must be length 2N.'); -end - - - -function z=gen_analytic(s1) -%--------------------------------------------------------------------- -% generate the analytic signal (with zero-padding in the time-direction) -%--------------------------------------------------------------------- -s1=real(s1); -N=length(s1); N2=2*N; - -% 1. zero-pad N-point signal to 2N -s1=[s1(:); zeros(N,1)]; -S1=fft(s1); - -% 2. Get analytic signal of 2N-point signal -H=zeros(N2,1); -H([1 N+1])=1; -H(2:N)=2; -z_cb=ifft(S1.*H); - - -% 3. Force the second half of the time-domain signal to zero. -z=[z_cb(1:N); zeros(N,1)]; - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/get_window.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/get_window.m deleted file mode 100644 index b24fb8b9..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/get_window.m +++ /dev/null @@ -1,176 +0,0 @@ -%-------------------------------------------------------------------------------- -% General function to calculate a window function (mostly a wrapper for the existing -% window functions). -% -% USE: win = get_window( win_length, win_type, [win_param], [DFT_WINDOW], [Npad] ) -% -% INPUT: -% win_length = length of window -% win_type = type of window: { 'delta' | 'rect' | 'bart' | 'hamm' -% | 'hann' | 'tukey' | 'gauss' | 'cosh' | 'blackmanharris' } -% win_param = (optional) window parameter. -% DFT_WINDOW = (optional) parameter { 0 | 1 }. -% If 1 returns DFT of window. -% Npad = (optional) zero-pad window to length Npad. -% -% OUTPUT: -% win = window -% -% See also: BARTLETT, HANNING, HAMMING, GAUSSWIN, TUKEYWIN, CIRCSHIFT, FFT -% -% EXAMPLE -% N=64; -% win=get_window(N,'tukey',0.4,0,2*N); -% plot(win); - - -% Copyright (C) 2007,2008 John M. O' Toole, The University of Queensland -% -% 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 . -%-------------------------------------------------------------------------------- -function win = get_window( win_length, win_type, win_param, DFT_WINDOW, Npad ) -if( nargin<3 ) win_param=[]; end -if( nargin<4 ) DFT_WINDOW=0; end -if( nargin<5 ) Npad=0; end - - -win=get_win(win_length,win_type,win_param,DFT_WINDOW); -win=shift_win(win); - -if(Npad>0) - win=pad_win(win,Npad); -end - - - -function win=get_win(win_length, win_type, win_param, DFT_WINDOW ) -%-------------------------------------------------------------------------------- -% Get the window. Negative indices are first. -%-------------------------------------------------------------------------------- - -switch win_type - case 'delta' - win=zeros(win_length,1); - wh = floor(win_length/2); - win(wh+1)=1; - case 'rect' - win(1:win_length) = 1; - case {'bart', 'bartlett'} - win = bartlett( win_length ); - case {'hamm', 'hamming'} - win = hamming( win_length ); - case {'hann', 'hanning'} - win = hanning( win_length ); - case 'tukey' - % NOTE: seems to be problem with Octave's (v2.9.12) tukeywin.m for N odd. - if(isempty(win_param)) - win = tukeywin( win_length ); - else - win = tukeywin( win_length, win_param ); - end - case 'gauss' - if(isempty(win_param)) - win = gausswin( win_length ); - else - win = gausswin( win_length, win_param ); - end - case 'cosh' - win_hlf = fix( win_length / 2); - - if(isempty(win_param)) - win_param = 0.01; - end - for m = -win_hlf:win_hlf - win(mod(m,win_length)+1) = cosh( m ).^( -2 * win_param ); - end - win = fftshift(win); - case {'blackmanharris', 'bmh'} - win = blackmanharris(win_length, 'symmetric'); - case {'nuttall'} - win = nuttallwin(win_length, 'symmetric'); - case {'dolph', 'chebwin'} - win = chebwin(win_length, win_param); - - otherwise - error(['Unknown window type ' win_type]); -end - - -%--------------------------------------------------------------------- -% If want the DFT of win -%--------------------------------------------------------------------- -if(DFT_WINDOW) - win=circshift(win(:),ceil(win_length/2)); - win=fft(win); - win=circshift(win(:),floor(win_length/2)); -end - - -function w=shift_win(w) -%-------------------------------------------------------------------------------- -% Shift the window so that positive indices are first. -%-------------------------------------------------------------------------------- -N=length(w); -w=circshift(w(:),ceil(N/2)); - - - -function w_pad=pad_win(w,Npad) -%-------------------------------------------------------------------------------- -% -% Pad window to Npad. -% -% Presume that positive window indices are first. -% -% When N is even use method described in [1] -% -% References: -% [1] S. Lawrence Marple, Jr., Computing the discrete-time analytic -% signal via FFT, IEEE Transactions on Signal Processing, Vol. 47, -% No. 9, September 1999, pp.2600--2603. -% -%-------------------------------------------------------------------------------- -w=w(:); -w_pad=zeros(Npad,1); -N=length(w); -Nh=floor(N/2); -if(Npad E ) flag=0; end - - diff --git a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/padWin.m b/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/padWin.m deleted file mode 100644 index d2038921..00000000 --- a/src/paradigma/ppg/hr_functions/TFD toolbox JOT/utils/padWin.m +++ /dev/null @@ -1,97 +0,0 @@ -%-------------------------------------------------------------------------------- -% -% Pad window to Npad. -% -% Presume that positive window indices are first. -% -% USE: w_pad=padWin(w,Npad) -% -% INPUT: -% w = window (vector) of length N -% Npad = pad window to length N (Npad>N) -% -% OUTPUT: -% w_pad = window of length N zeropadded to length Npad -% -% -% When N is even use method described in [1] -% -% References: -% [1] S. Lawrence Marple, Jr., Computing the discrete-time analytic -% signal via FFT, IEEE Transactions on Signal Processing, Vol. 47, -% No. 9, September 1999, pp.2600--2603. -% -% -% STARTED: 04-01-2008 - -% Copyright (c) 2010, John M. O' Toole, The University of Queensland -% All rights reserved. -% -% Redistribution and use in source and binary forms, with or without -% modification, are permitted provided that the following -% conditions are met: -% * Redistributions of source code must retain the above -% copyright notice, this list of conditions and the following -% disclaimer. -% * 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. -% * Neither the name of the The University of Queensland nor the -% names of its contributors may be used to endorse or promote -% products derived from this software without specific prior -% written permission. -% -% THIS SOFTWARE IS PROVIDED BY JOHN M. O' TOOLE ''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 JOHN M. O' TOOLE 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. -%-------------------------------------------------------------------------------- -function w_pad=padWin(w,Npad) -DB=0; -w=w(:); -w_pad=zeros(Npad,1); -N=length(w); -Nh=floor(N/2); -if(DB) dispVars(N,Npad); end -if(Npad