plateform
stringclasses 1
value | repo_name
stringlengths 13
113
| name
stringlengths 3
74
| ext
stringclasses 1
value | path
stringlengths 12
229
| size
int64 23
843k
| source_encoding
stringclasses 9
values | md5
stringlengths 32
32
| text
stringlengths 23
843k
|
---|---|---|---|---|---|---|---|---|
github | weifanjiang/UWA_OCT_Image_Processing-master | Snake.m | .m | UWA_OCT_Image_Processing-master/Snake.m | 12,530 | utf_8 | 89478754a3bf6f3b3f51604af4e97df5 | %% <Snake.m>
%
% Weifan Jiang
% This function finds and marks the lymphatic vessels within an OCT image
% with the active contour model (Snake) algorithm.
%=========================================================================
function Snake(img)
%% Function Parameters:
% img: the OCT image needs to be processed.
%% Local Variables:
% These parameters are used for Before_Segmentation.m to pre-process
% scans, each parameter's function is specified in
% Before_Segmentation.m.
Lower_Bound = 12;
Lower_Value = 0;
Higher_Bound = 45;
Higher_Value = 45;
% Iteration_Count: the maximum iterations active contour is run. This
% number can be changed based on the complexity of exterior shape of
% image, as well as the size of image (i.e. larger image requires more
% iterations for the snake to reach inside).
% This one is used for initial active contour which detects the surface
Iteration_Count_1 = 1000;
% This one is used for active contouring inside of image.
Iteration_Count_2 = 1000;
% pushing: push the averaged esum line downward to ensure it is within
% the inner part of OCT image. This value should be adjusted based on
% image.
pushing = 114;
% thick: how thick the mask should be initially, this value should also
% be adjusted based on image.
thick = 150;
% expected_pixel: the maximum intensity a pixel holds in order to be
% determined as vessel
% default = 20
expected_pixel = 30;
% ecpected count: for each pixel determined as vessel in result of
% active contour applied in last part, the surrounding 3x3 window in
% raw picture is expected to contain at least this number of pixels
% with expected_pixel intensity.
% default = 3
expected_count = 1;
%% Display original image and process with pre-process function
figure;
subplot(2, 3, 1); imagesc(img, [Lower_Value Higher_Value]); title('Original Image'); colormap(gray);
raw = Before_Segmentation(img, Lower_Bound, Lower_Value, Higher_Bound, Higher_Value);
subplot(2, 3, 2); imagesc(raw); title('Before segmentation processing'); colormap(gray);
%% Find centers of all the connected regions of pixels with intensity = 0
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% ========================================================= %
% ========================================================= %
% ========== Please keep this part commented ============== %
% ========================================================= %
% ========================================================= %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Note: this part implements an algorithm of Breath-First
% Search based on graph theory of Computer Science.
% It may work for small pictures, but the data size for this project is
% too large for this part to work efficiently. Thus keeping this part
% commented is essential for this function to run.
% [width, height] = size(raw);
% ptr = 1;
% flags = zeros(width, height);
% centers = [];
%
% while ptr <= width * height
% ptr_x = mod(ptr, width);
% ptr_y = floor(ptr / width) + 1;
%
% if flags(ptr_x, ptr_y) == 0 && raw(ptr_x, ptr_y) == 0
%
% curr = [ptr_x, ptr_y];
% toExplore = [ptr_x, ptr_y];
% seen = zeros(width, height);
% seem(ptr_x, ptr_y) = 1;
%
% while sum(sum(toExplore)) ~= 0
% loc = toExplore(1, :);
% toExplore = toExplore(2:end, :);
% loc_x = loc(1);
% loc_y = loc(2);
% flags(loc_x, loc_y) = 1;
% curr = [curr
% loc_x, loc_y];
%
%
% if loc_x > 1
% if raw(loc_x - 1, loc_y) == 0 && flags(loc_x - 1, loc_y) == 0 && seen(loc_x - 1, loc_y) == 0
% toExplore = [toExplore
% loc_x - 1, loc_y];
% seen(loc_x - 1, loc_y) = 1;
% end
% end
% if loc_y > 1
% if raw(loc_x, loc_y - 1) == 0 && flags(loc_x, loc_y - 1) == 0 && seen(loc_x, loc_y - 1) == 0
% toExplore = [toExplore
% loc_x, loc_y - 1];
% seen(loc_x, loc_y - 1) = 1;
% end
% end
% if loc_x < width
% if raw(loc_x + 1, loc_y) == 0 && flags(loc_x + 1, loc_y) == 0 && seen(loc_x + 1, loc_y) == 0
% toExplore = [toExplore
% loc_x + 1, loc_y];
% seen(loc_x + 1, loc_y) = 1;
% end
% end
% if loc_y < height
% if raw(loc_x, loc_y + 1) == 0 && flags(loc_x, loc_y + 1) == 0 && seen(loc_x, loc_y + 1) == 0
% toExplore = [toExplore
% loc_x, loc_y + 1];
% seen(loc_x, loc_y + 1) = 1;
% end
% end
% end
%
% all_x = curr(1, :);
% all_y = curr(2, :);
%
% [num, gg] = size(all_x);
%
% centers = [centers
% floor(sum(all_x)/num), floor(sum(all_y)/num)];
% end
% ptr = ptr + 1;
% end
%
% [centerCount, gg] = size(centers);
% centerGraph = zeros(width, height);
% for j = (1:centerCount)
% centerGraph(centers(1, j), centers(2, j)) = 255;
% end
% figure; imagesc(centerGraph); title('Centers for black pixels regions'); colormap(gray);
%% Using active contour to find the upper & lower edges of image's exterior surface.
[width, height] = size(raw);
% initial mask of active contour, can be adjusted based on property of
% original graph.
mask = zeros(width, height);
mask(10:end-10, 10:end-10) = 1;
% Outputs the background of image.
% Background should be set to black (index = 0) while image set to
% white (index = 1).
background = activecontour(raw, mask, Iteration_Count_1);
%% Denoise the background by removing selected pixels.
% for each non-zero intensed pixel in the background image, set it to
% non-special (i.e. change its intensity to 0) if there are no other
% non-background pixels within the surrounding 3x3 window.
backGround_extend = zeros(width + 2, height + 2);
backGround_extend(2:end-1, 2:end-1) = background;
for j = (2:width + 1)
for k = (2:height + 1)
if backGround_extend(j, k) > 0
% Count surrounding non-zero pixels.
count = 0;
for delta_x = [-1 0 1]
for delta_y = [-1 0 1]
if backGround_extend(j + delta_x, k + delta_y) > 0
count = count + 1;
end
end
end
if count == 1
% count == 1 indicates only 1 non-background pixel
% inside 3x3 window (which is target pixel itself).
background(j - 1, k - 1) = 0;
end
end
end
end
%% Binarilize original image to discard noise
% Note: This part can be activated if there are too many noises that
% the previous denoise portions cannot handle. Since the
% Before_Segmentation.m function oftern set the center of each vessel
% to 0 intensity, binarilize the "raw" picture can discard many noises,
% but also produces great risk of discarding useful informations.
% Not recommended in most of the situations.
% for j = (1:width)
% for k = (1:height)
% if raw(j, k) ~= 0
% raw(j, k) = 1;
% end
% end
% end
%% Apply mean filter to background to further remove small noises.
denoise = background;
mean_filted = zeros(width + 2, height + 2); % Applied in 3x3 window.
outer = zeros(width + 4, height + 4);
outer(3:width + 2, 3:height + 2) = denoise;
for j = [-1, 0, 1]
for k = [-1, 0, 1]
mean_filted = mean_filted + outer(2 + j:width + 3 + j, 2 + k:height + 3 + k);
end
end
mean_filted = mean_filted / 9;
%Resize to original size.
mean_filted = mean_filted(3:width + 2, 3:height + 2);
background = mean_filted;
% Binarilize background.
for j = (1:width)
for k = (1:height)
if background(j, k) ~= 1
background(j, k) = 0;
end
end
end
subplot(2, 3, 3); imagesc(background); title('Background'); colormap(gray);
%% Remove background in the previous image by setting background to a smooth color
for j = (1:width)
for k = (1:height)
if background(j, k) == 0
% background(j, k) == 0 indicates that it is not the
% useful portion of picture, thus we set the corresponding
% pixel in raw picture to a smooth color, which will be
% less-likely influncing the snake as it changes iteration
% by iteration.
% Since the original picture is between 0-45, we choose a
% value in between for the background, seems like 27 works
% the best by experience.
raw(j, k) = 27;
end
end
end
subplot(2, 3, 4); imagesc(raw); title('Background removed in original picture'); colormap(gray);
%% Construct a mask to explore the interior of image.
mask2 = zeros(width, height); % make sure the mask has same size as original picture.
% We choose the initial place of mask to be the averge of position of
% the first black pixel in each column.
esum = 0; %% keep track of sum of all first black pixels' positions
for j=(1:height)
ptr = 1;
% Keep iterating until ptr represents a black pixel
while ptr < width && background(ptr, j) == 0
ptr = ptr + 1;
end
esum = esum + ptr;
end
esum = floor(esum / height); % Divide by total number of columns.
% Adjust the initial position of snake with pushing and determine the
% range of window by thick.
esum = esum + pushing;
% Set the region in mask2 to be 1.
mask2(esum:esum + thick, :) = 1;
subplot(2, 3, 5); imagesc(mask2); title('Second mask'); colormap(gray);
%% Apply actvie contour to raw picture
% At this point, the black background of raw should be changed to a
% smooth color, so the snake will go inside the image.
fig = activecontour(raw, mask2, Iteration_Count_2);
%% Construct final result with previous answers
% Count surrounding 3x3 window in the raw picture of any pixel defined
% as vessel from active coutour, discard pixels do not meet standard.
% Use ecxpected_pixel and expected_count to filter out unwanted noises.
result = ones(width, height);
for j = (2:width-1)
for k = (2:height-1)
% 0 intensity: vessel pixel
if fig(j, k) == 0
count = 0;
for delta_x = [-1 0 1]
for delta_y = [-1 0 1]
if raw(j + delta_x, k + delta_y) < expected_pixel
count = count + 1;
end
end
end
if count > expected_count
% Set to 0 indicates a vessel-pixel is marked black in
% result.
result(j, k) = 0;
end
end
end
end
%% Return final answer.
final = result;
subplot(2, 3, 6); imagesc(final); title('final result'); colormap(gray);
end |
github | weifanjiang/UWA_OCT_Image_Processing-master | Gradient_Segmentation.m | .m | UWA_OCT_Image_Processing-master/Gradient_Segmentation.m | 6,265 | utf_8 | a53c1107b94131770459c208d748d110 | %% <Gradient_Segmentation.m>
%
% Weifan Jiang
% This function finds and marks the lymphatic vessels within an OCT image
% with an algorithm based on gradient calculation.
%=========================================================================
function Gradient_Segmentation(img)
%% Function Parameters:
% img: the OCT image being processed.
%% Local Variables:
% These parameters are used for Before_Segmentation.m to pre-process
% scans, each parameter's function is specified in
% Before_Segmentation.m.
Lower_Bound = 12;
Lower_Value = 0;
Higher_Bound = 45;
Higher_Value = 45;
% gradient_method: indicates which gradient-calculating method would be
% used to calculate gradient.
%
% possible values: 'sobel', 'prewitt', 'roberts', 'central', 'intermediate'.
gradient_method = 'intermediate';
% thr: gradient magnitude lower than this value would be treated as
% noise and eliminated.
% for sobel and prewitt operator, thr should be set to approximately 50
% for roberts, thr should be set to about 15
% for central and intermediate, thr should be set to about 5
thr = 5;
% vessel_intensity: in the original picture, any pixel with intensity
% lower than thr is determined to be vessel signal.
% default = 10
vessel_intensity = 25;
% expect_vessel: expected vessel pixel number in the 5x5 window
% centered in a target pixel.
% default = 5
expect_vessel = 5;
% expect_grad: expected number of pixels with non-zero gradient within
% an 5x5 window centered at the target pixel
% default = 5
expect_grad = 5;
%% Display original image and process with pre-process function
figure;
subplot(2, 2, 1); imagesc(img, [Lower_Value Higher_Value]); title('Original Image'); colormap(gray);
raw = Before_Segmentation(img, Lower_Bound, Lower_Value, Higher_Bound, Higher_Value);
subplot(2, 2, 2); imagesc(raw); title('Before segmentation processing'); colormap(gray);
%% Calculate Gradient of picture
% Note: the default option of imgradient function in Matlab uses
% Sobel's operator to calculate gradient magnitude and direction, other
% operator can also be used, but other parameters may need to be
% adjusted.
[Gmag, Gdir] = imgradient(raw, gradient_method);
% This algorithm would only analyze image based on Gradient magnitude
% since lymphatic vessels usually don't process a regular shape.
%% Use Thresholding to filter out low signal of gradient.
% Since there are many noise pixels within the picture, and it differs
% not much in intensity with surrounding pixels, therefore it would
% result in a small value of gradient magnitude thus needs to be
% discarded.
% use thr to eliminate lower magnitude pixels.
[width, height] = size(Gmag);
for j = (1:width)
for k = (1:height)
if Gmag(j, k) < thr
Gmag(j, k) = 0;
end
end
end
%% Compare Gradient picture with original picture
detect = zeros(width + 4, height + 4);
detect(3:2+width, 3:2+height) = Gmag;
raw_extend = zeros(width + 4, height + 4);
raw_extend(3:2+width, 3:2+height) = raw;
% All pixels with non-zero gradient magnitude in this picture will be
% determined whether it is noise by counting the number of surrounding
% vessel pixels and surrounding pixels with non-zero gradient magnitude
% in a 5x5 window.
% vessel_intensity, expected_vessel and expected_grad are used here.
for center_x = (3:2+width)
for center_y = (3:2+height)
if detect(center_x, center_y) > 0
raw_count = 0; % count number of edge pixels within the window
edge_count = 0; % count non-zero gradient magnitude pixels
for delta_x = (-2:2)
for delta_y = (-2:2)
if raw_extend(center_x - delta_x, center_y - delta_y) < vessel_intensity
raw_count = raw_count + 1;
end
if detect(center_x - delta_x, center_y - delta_y) > 0
edge_count = edge_count + 1;
end
end
end
% Set a pixel's gradient magnitude to zero if either the
% vessel pixel count or gradient magnitude pixel number
% count fails to meet the expected standard.
if raw_count < expect_vessel
detect(center_x, center_y) = 0;
end
if edge_count < expect_grad
detect(center_x, center_y) = 0;
end
end
end
end
% Resize the picture to original size.
detect = detect((3:2+width), (3:2+height));
%% Apply a 3x3 mean filter to the graph to reduce small noises.
denoise = detect;
[width, height] = size(denoise);
mean_filted = zeros(width + 2, height + 2);
outer = zeros(width + 4, height + 4);
outer(3:width + 2, 3:height + 2) = denoise;
% Add up surrounding pixel's intensity.
for j = [-1, 0, 1]
for k = [-1, 0, 1]
mean_filted = mean_filted + outer(2 + j:width + 3 + j, 2 + k:height + 3 + k);
end
end
% Take average.
mean_filted = mean_filted / 9;
% Resize the window to original size.
mean_filted = mean_filted(3:width + 2, 3:height + 2);
denoise = mean_filted;
%% Binarilize the image for better viewing.
% by setting non-zero pixels to 255 intensity.
for j = (1:width)
for k = (1:height)
if denoise(j, k) ~= 0
denoise(j, k) = 255;
else
denoise(j, k) = 0;
end
end
end
%% display final picture.
final = denoise;
subplot(2, 2, 3); imagesc(final); title(gradient_method); colormap(gray);
end |
github | weifanjiang/UWA_OCT_Image_Processing-master | Before_Segmentation.m | .m | UWA_OCT_Image_Processing-master/Before_Segmentation.m | 4,269 | utf_8 | e916d2d94e98712f3ffa7138709dc1e3 | %% <Before_Segmentation.m>
%
% Weifan Jiang
% This function pre-processes an OCT image, including denoising,
% smoothing and contrast enhancement.
%=========================================================================
function final = Before_Segmentation(I, lower_bound, lower_value, higher_bound, higher_value)
%% Function Parameters:
% I: the OCT image being processed by this function
% lower_bound: the lowest intensed pixel needed to be processed
% lower_value: the lowest intensed pixel allowed in output
% higher_bound: the highest intensed pixel needed to be processed
% higher_value: the highest intensed pixel allowed in output
%% Local Variables:
% Step: indicates the height of each region where local intensity will
% be calculated when adjusting attenuation.
step = 15;
% set_value: set_value is used to determine if a special pixel is noise
% by looking at surrounding numbers of background pixels in 5x5 window.
% If there are more than set_value amount of background pixels around a
% special pixel, then that pixel is determined to be noise instead of
% vessel.
%
% Larger set_value can filter out more noise but also produces the risk
% of losing vessel pixels.
set_value = 15;
%% Median Filter to discard minor noises.
img = medfilt2(I);
%% Adjust attenuation of the picture
[width, height] = size(img);
ptr = 1;
intensity = []; % holds all intensity levels for each region
while ptr + step - 1 <= height
curr = 0;
% Add up all intensities in current region.
for j = (1:width)
for k = (ptr:ptr + step - 1)
curr = curr + img(j, k);
end
end
% Append to intensity
intensity = [intensity, curr];
% Increment the pointer for current region.
ptr = ptr + step;
end
% Re-scale each-region's intensity by setting each pixel's intensity
% to:
%
% new_intensity = (old_intensity / average_intensity_of_region) *
% max_regional_average_intensity
count = 1;
ptr = 1;
while ptr + step - 1 <= height
for j = (1:width)
for k = (ptr:ptr + step - 1)
img(j, k) = (img(j, k) / intensity(count)) * max(intensity);
end
end
ptr = ptr + step;
count = count + 1;
end
%% Set all pixels below lower_bound or above upper_bound to appropriate
for j = (1:width)
for k = (1:height)
if img(j, k) < lower_bound
img(j, k) = lower_value;
end
if img(j, k) > higher_bound
img(j, k) = higher_value;
end
end
end
%% Compare processed image with original image
% set a pixel A in processed image to non-special if there are more than
% a certain value of non-special pixels in the 5x5 window centered at A
% in the original picture.
% use set_value to determine if a pixel is noise.
detect = zeros(width + 4, height + 4);
detect(3:2+width, 3:2+height) = img;
for center_x = (3:2+width)
for center_y = (3:2+height)
count = 0;
%sum = 0;
for delta_x = (-2:2)
for delta_y = (-2:2)
%sum = sum + detect(center_x + delta_x, center_y + delta_y);
if detect(center_x + delta_x, center_y + delta_y) == lower_value
count = count + 1;
end
end
end
if count > set_value
detect(center_x, center_y) = 0;
% detect(center_x. center_y) = sum / 25;
end
end
end
% Note: there is also the option to set the intensity to average of the
% 25-pixel window instead of setting it directly to 0, which option is
% better depends on other parameters and the gradient-calculating
% method used previously.
% Rescale the picture to original.
detect = detect((3:2+width), (3:2+height));
%% Return final answer
final = detect;
end |
github | LorisMarini/content_caching_with_reinforcement_learning-master | Configure_The_Network.m | .m | content_caching_with_reinforcement_learning-master/network_configurations/Configure_The_Network.m | 5,652 | utf_8 | a8761718fc1d3605ad9b8219e6207502 | function [ Network_Parameters ] = Configure_The_Network( N_Networks, Diameter, Radius_Protected_Area, Step_Size, H, N, Alpha)
%{
------------------------- AUTHORSHIP -------------------------
Developer: Loris Marini
Affiliation: The University of Sydney
Contact: [email protected]
Notes:
------------------------- DESCRIPTION -------------------------
This function creates N_Networks different instances of a radio cell. If the
function is run more than once there are two possibilities:
1. The Network_Parameters differs from those defined previously. The function
creates a subdirectory with a random name and saves the data there.
2. The Network_Parameters is identical to the one already defined. The
function does not do anyhting.
------------------------- INPUT PARAMETERS -------------------------
-- N_Networks --
Number of different networks to simulate
-- Diameter --
Diameter of the cell in meters.
-- Radius_Protected_Area --
Radius of clear space around each user (Necessary to avoid ...)
-- Step_Size --
Distance between two points on the cell. Must be <= 1. The ratio Diameter/Step_Size
is equal to the number of points along the diameter of the cell.
-- H --
Number of Helpers in the cell.
-- N --
Number of users in the cell.
-- Alpha --
The free space absorption coefficient
------------------------- OUTPUT PARAMETERS -------------------------
-- Parameters --
A struct containing all the relevant parameters for the function call.
------------------------- EXAMPLE OF CALL -----------------------
% Number of radio cells to deploy
Nrc = 2;
% Cell diameter [m]
Diam = 1000;
% Clear space around each helper [m]:
CS = 10;
% Step size
SS = 0.1
% Number of helpers in the network
Nh = 20;
% Number of users in the network
Nu = 100;
% A propagation Loss of 1 [km^-1]
Ap = 1;
[ Parameters ] = Configure_The_Network( Nrc, Diam, CS, SS, Nh, Nu, Ap)
%}
% ---------------------------- CODE --------------------------
% Add the communications toolbox to path. This is a known issue in Matlab
% 2017a. See this post for more info:
% https://au.mathworks.com/matlabcentral/answers/350491-how-to-set-the-correct-path-
% for-communications-toolbox-for-rtl-sdr-support-package-at-startup
addpath(fullfile(matlabroot, 'toolbox', 'comm', 'comm'), '-end')
% Define the path to the directory where you store the network configurations:
% path_to_networks = 'C:\Users\lmar1564\Documents\MATLAB\FemtoChaching\Network_Configuration\Configurations';
path_to_networks = '/home/loris/Desktop/test';
% Create a struct with the name and value of all relevant parameters used
% in this function call:
Network_Parameters = struct('Number_Of_Netoworks_Generated',N_Networks, 'Diameter',Diameter, ...
'Radius_Protected_Area',Radius_Protected_Area, 'Step_Size',Step_Size, ...
'N_Of_Helpers',H, 'N_Of_Users', N, 'Propagation_Loss_Alpha', Alpha );
% Define the name with which you save the Network_Parameters:
parameters_saveas = ['Network_Parameters_' num2str(N_Networks),...
'_Random_Networks_H' num2str(H) '_N' num2str(N) '.mat'];
cd(path_to_networks);
search = dir(parameters_saveas);
if ~isempty( search )
% Check they are identical
l = load(parameters_saveas);
Loaded_param = l.Network_Parameters;
if isequal(Loaded_param, Network_Parameters)
% File exists and has identical parameters. Do nothing
disp('Configuration already exists.');
return;
elseif Loaded_param ~= Network_Parameters
% perform the full simulation but save data in subdirectory that
% starts with the idenfifiers of parameters_saveas plus a random
% string of integers
random_string = num2str(randi(9,1,7));
random_string(random_string==' ') = [];
subdir_name = ['N_Net_' num2str(N_Networks),'H' num2str(H) '_N' num2str(N),'_id_',random_string];
% ????
end
else
% Do nothing here and continue execution.
end
% Save to disk the network parameters in the 'path_to_networks' with the 'parameters_saveas' name:
save( fullfile( path_to_networks ,parameters_saveas), 'Network_Parameters');
for n = 1:1:N_Networks
% Call the function Place_Users to randomly place users in a cell
[ distances, fh ] = Place_Users( Diameter, Radius_Protected_Area, Step_Size, H,N );
% Save distances matrix to file
Matrix_Distances_Name = ['Distances_' num2str(n) '_of_' num2str(N_Networks) '_with_H' num2str(H) '_N' num2str(N) '.mat'];
save( fullfile( path_to_networks ,Matrix_Distances_Name), 'distances');
Network_Delays = Network_Normalised_Delays( distances, Alpha );
% Save Matrix of delays
Matrix_Delays_Name = ['Network_Delays_' num2str(n) '_of_' num2str(N_Networks) '_with_H' num2str(H) '_N' num2str(N) '.mat'];
save( fullfile( path_to_networks ,Matrix_Delays_Name), 'Network_Delays');
% Save the figure representing the cell with helpers and users
Figure_Name = ['Network_Scenario_' num2str(n) '_of_' num2str(N_Networks) '_with_H' num2str(H) '_N' num2str(N) '.fig'];
Figure_File_Name = fullfile(path_to_networks, Figure_Name);
figure(fh);
saveas(fh, Figure_File_Name);
end
close all;
end
|
github | LorisMarini/content_caching_with_reinforcement_learning-master | PLAY.m | .m | content_caching_with_reinforcement_learning-master/Multi_Agent_CIDGPA_Framework/PLAY.m | 11,557 | utf_8 | eef3771b11c2b4b66f71ed303fd16d17 |
function [ Conv_Actions, Game_Iterations, History_Delays, Convergence_Delays, New_Learning] = PLAY( Network_Delays, Popularities, Learning, Reward_Type, Resolution, P_Threshold )
%{
-------------------------- AUTHORSHIP ---------------------------------
Developer: Loris Marini
Affiliation: The University of Sydney
Contact: [email protected]
Notes:
--------------------------- DESCRIPTION -------------------------------
This script initializes a game of learning automata using DGPA
reinforcement learning.
----------------------------- DEPENDENCIES --------------------------------
Learners_Files_Selection(...)
User_Weighted_Delay(...)
User_NCA_Selection(...)
Best_File_Based_Reward()
Weighted_Delay_Based_Reward()
-------------------------------- INPUT ----------------------------------
Network_Delays
Popularities
Learning
The Set of Learners as Initialised by the 'INITIALIZE_Game_Of_DGPA'.
Reward_Type
(See ...)
Resolution
Typically 1, is the resolution step of the DGPA.
P_Threshold
Level of probability we consider to convergence.
-------------------------------- OUTPUT ----------------------------------
Conv_Actions
The set of actions for each learner that the game has converged to.
Weighted_Delays
The final weighted delay for each user.
GAME_Delay_Performance
The history of weighted delays for each user during the GAME.
% ----------------------------- CODE ---------------------------------
%}
NP = size(Network_Delays,2); % Number of content providers (BS or Helpers) in the cell
H = NP - 1; % Number of Helpers in the cell
N = size(Network_Delays,1); % Number of users in the cell
M = size(Learning,1); % Caching capability of each Helper
F = H*M; % Total number of files that can be cached.
S = 1:1:F; % S: Space of Actions. F: How many files we can offload from the BS.
Delta = 1/(F.*Resolution); % Resulution Step
Conv_Actions = zeros(M,H); % The Matrix of actions to which learners converge during the game.
GAME_Positive_Feedbacks = zeros(M,H); % ....
GITER = 1; % Game Iteration Number.
Elapsed_Time = 0; % Time Initialisation.
Min_Weighted_Delay = Inf*ones(1,N);
Min_Average_Weighted_Delay = Inf*ones(1,H);
Average_Weighted_Delay = zeros(1,H);
while ~Check_Game_Convergence( Learning, P_Threshold )
tic; % Iteration Timing
% Learners Select Files in Parallel (same time)
[Available_Files, New_Learning] = Learners_Files_Selection( S, Learning );
Learning = New_Learning;
% Feedbacks from the users:
% Pre-allocate cumulative Rewards for all users
% Pre-allocate cumulative Penalsties for all users
GAME_Rewards = zeros(M,H+1);
GAME_Penalties = zeros(M,H+1);
switch Reward_Type
case 'Best_File_Based_Reward'
for n = 1:1:N
% Let each user choose which content they prefer using the
% policy if nearest available (Nearest Content Available
% NCA)
User_Selections = User_NCA_Selection( n, S, Available_Files, Network_Delays);
% Calculate the weighted latency that the user would experience
Delay_Performance(GITER,n) = User_Weighted_Delay( User_Selections, Popularities );
User_Delays = Network_Delays(n,:);
% Let the user provide its own feedback
[ Current_Rewards, ~, Current_Penalties, ~ ] = Best_File_Based_Reward( User_Delays, User_Selections, Popularities );
% Update Rewards and Penalties
GAME_Rewards = GAME_Rewards + Current_Rewards;
GAME_Penalties = GAME_Penalties + Current_Penalties;
end
case 'Weighted_Delay_Based_Reward'
for n = 1:1:N
% Let each user choose which content they prefer using the
% policy if nearest available (Nearest Content Available
% NCA)
User_Selections = User_NCA_Selection( n, S, Available_Files, Network_Delays);
% Calculate the weighted latency that the user would experience
Delay_Performance(GITER,n) = User_Weighted_Delay( User_Selections, Popularities );
User_Delays = Network_Delays(n,:);
if (Weighted_Delay < Min_Weighted_Delay(n))
Min_Weighted_Delay(n) = Weighted_Delay;
end
if( GITER == 1)
Current_Minima = Inf;
elseif (GITER > 1)
Current_Minima = Min_Weighted_Delay(n);
end
% Let the user provide its own feedback
[ Current_Rewards, ~, Current_Penalties, ~ ]...
= Weighted_Delay_Based_Reward( User_Delays, User_Selections, Weighted_Delay, Current_Minima , Popularities );
% Update Rewards and Penalties
GAME_Rewards = GAME_Rewards + Current_Rewards;
GAME_Penalties = GAME_Penalties + Current_Penalties;
end
case 'Average_Weighted_Delay_Based_Reward'
Tot_Rewards = zeros(M,H+1,N);
Tot_Penalties = zeros(M,H+1,N);
for n = 1:1:N
% Let each user choose which content they prefer using the
% policy if nearest available (Nearest Content Available
% NCA)
User_Selections(n,:,:,:) = User_NCA_Selection( n, S, Available_Files, Network_Delays);
% Calculate the weighted latency that the user would experience
This_User_Selections = squeeze(User_Selections(n,:,:,:));
Delay_Performance(GITER,n) = User_Weighted_Delay( This_User_Selections, Popularities );
% Let the user provide its own feedback
User_Delays = Network_Delays(n,:);
[ Current_Rewards, ~, Current_Penalties, ~ ] = Best_File_Based_Reward( User_Delays, This_User_Selections, Popularities );
Tot_Rewards(:,:,n) = Current_Rewards;
Tot_Penalties(:,:,n) = Current_Penalties;
end
for j=1:1:H
% Take only the users connected to the learner (j,k)
Who_to_Average = Network_Delays(:,j) ~= Inf;
Average_Weighted_Delay(j) = sum( Weighted_Delay(Who_to_Average)) / sum(Who_to_Average);
if (Average_Weighted_Delay(j) <= Min_Average_Weighted_Delay(j) )
Min_Average_Weighted_Delay(j) = Average_Weighted_Delay(j);
GAME_Rewards(:,j) = GAME_Rewards(:,j) + sum( squeeze( Tot_Rewards(:,j,:) ),2);
GAME_Penalties(:,j) = GAME_Penalties(:,j) + sum( squeeze( Tot_Penalties(:,j,:) ),2);
else
GAME_Rewards(:,j) = GAME_Rewards(:,j);
GAME_Penalties(:,j) = GAME_Penalties(:,j) + sum( squeeze( Tot_Rewards(:,j,:) ),2) + sum( squeeze( Tot_Penalties(:,j,:) ),2);
end
end
History_Of_Average_Weighted_Delays(GITER,:) = Average_Weighted_Delay;
end
% GAME Learners Determine the Environment Feedback Democratically
% 'Env_Feedback(k,j)'= 1 --> Larner(k,j) Rewarded.
% 'Env_Feedback(k,j)'= 0 --> Learner(k,j) Penalised.
for j = 1:1:H
for k = 1:1:M
Curr_Action = Learning(k,j).Ai;
if (GAME_Rewards(k,j) > GAME_Penalties(k,j))
GAME_Positive_Feedbacks(k,j) = GAME_Positive_Feedbacks(k,j) + 1;
Learning(k,j).W(Curr_Action) = Learning(k,j).W(Curr_Action) + 1;
Who_to_Divide = Learning(k,j).W ~= 0;
Learning(k,j).D(Who_to_Divide) = Learning(k,j).W(Who_to_Divide)./ Learning(k,j).Z(Who_to_Divide);
else
% Do nothing.
end
end
end
% GAME Probabilities Vectors Update.
[ Updated_Learning, Updated_Conv_Actions ] = New_P_Vectors_DGPA_A( Conv_Actions, Learning, Delta, P_Threshold);
Learning = Updated_Learning;
Conv_Actions = Updated_Conv_Actions;
% Iteration Timing
Time = toc;
Elapsed_Time = Elapsed_Time + Time;
Average_Time = Elapsed_Time/GITER;
disp(['This is iteration number ' num2str(GITER) '. The Average Time per iteration is: ' num2str(Average_Time) '.'] );
GITER = GITER + 1;
end
Game_Iterations = GITER - 1;
New_Learning = Learning;
% Output Variables:
switch Reward_Type
case 'Best_File_Based_Reward'
History_Delays = Delay_Performance;
Convergence_Delays = Delay_Performance(end,:);
case 'Weighted_Delay_Based_Reward'
History_Delays = Delay_Performance;
Convergence_Delays = Delay_Performance(end,:);
case 'Average_Weighted_Delay_Based_Reward'
History_Delays = History_Of_Average_Weighted_Delays;
Convergence_Delays = History_Of_Average_Weighted_Delays(end,:);
end
% VISUAL OUTPUT (Uncomment if needed in debugging mode)
%{
disp('-------------------------------------------------------------------');
disp('=================== Convergence COMPLETE. ======================');
disp('-------------------------------------------------------------------');
switch Reward_Type
case 'Best_File_Based_Reward'
disp(Reward_Type);
disp(['The converged weighted delays are: ' num2str(Delay_Performance(GITER-1,:)) '.']);
disp(['The Average Weighted Delay among all the users is: ' num2str(sum( Delay_Performance(GITER-1,:) )./N) '.']);
disp(['The game with ' num2str(M*H) ' players (that is file memories) converged after ' num2str(GITER-1) ' iterations.']);
case 'Weighted_Delay_Based_Reward'
disp(Reward_Type);
disp(['The converged weighted delays are: ' num2str(Delay_Performance(GITER-1,:)) '.']);
disp(['The Average Weighted Delay among all the users is: ' num2str(sum(Delay_Performance(GITER-1,:))./N) '.']);
disp(['The game with ' num2str(M*H) ' players (that is file memories) converged after ' num2str(GITER-1) ' iterations.']);
case 'Average_Weighted_Delay_Based_Reward'
disp(Reward_Type);
disp(['The converged weighted delays are: ' num2str(Delay_Performance(GITER-1,:)) '.']);
disp(['The Min_Average_Weighted_Delays, at convergence are : ' num2str(Min_Average_Weighted_Delay) '.']);
disp(['The game with ' num2str(M*H) ' players (that is file memories) converged after ' num2str(GITER-1) ' iterations.']);
end
%}
end
|
github | LorisMarini/content_caching_with_reinforcement_learning-master | INITIALIZE.m | .m | content_caching_with_reinforcement_learning-master/Multi_Agent_CIDGPA_Framework/INITIALIZE.m | 9,684 | utf_8 | 148284711069c94d8689ab4b2a9b11dd |
function [ Learning, Iterations ] = INITIALIZE( Learning_Setup, Network_Delays, M, Popularities, Reward_Type, Initialization_Number )
%{
-------------------------- AUTHORSHIP ---------------------------------
Developer: Loris Marini
Affiliation: The University of Sydney
Contact: [email protected]
Notes:
--------------------------- DESCRIPTION -------------------------------
This script initializes a game of learning automata using DGPA
reinforcement learning.
----------------------------- DEPENDENCIES --------------------------------
Allocate_Learners(...)
Learners_Files_Selection(...)
User_NCA_Selection(...)
User_Weighted_Delay(...)
Best_File_Based_Reward()
Weighted_Delay_Based_Reward()
-------------------------------- INPUT ----------------------------------
Network_Delays
Matrix of delays NxH+1 where N= number of users and H+1= Number of providers
M
Caching capability of a single helper;
Popularities
File Popularities
Reward_Type
Initialization_Number
See NITIALIZE_Game_Of_DGPA
-------------------------------- OUTPUT ----------------------------------
Learning
KxH Initialized learners
Iterations
The actual number of iteratiosn that it took to initialize.
% ----------------------------- CODE ---------------------------------
%}
H = size(Network_Delays,2) - 1; % Number of Helpers in the cell
N = size(Network_Delays,1); % Number of users in the cell
F = H*M; % Total number of files that can be cached.
S = 1:1:F; % S: Space of Actions. F: How many files we can offload from the BS.
N_Ini = Initialization_Number; % Initial #Iterations for estimation of D from each Learner
INI_Positive_Feedbacks = zeros(M,H); % Initialise Environmental Feedback
Zeros = Inf; % Is a variable to control the learners with empty D.
ITER = 1; % Iteration Number
Min_Weighted_Delay = Inf*ones(1,N);
Min_Average_Weighted_Delay = Inf*ones(1,H);
Average_Weighted_Delay = zeros(1,H);
% Loop until you make sure that all actions are selected at least N_Ini
% times. We do it with 'Lesser_Selected' which is a variable that controls
% the action that has been selected the least.
Lesser_Selected = 0;
% Initialize learners
Learning = Learners_Allocation( Learning_Setup, S, H,M,F );
while (Lesser_Selected < N_Ini || Zeros > 0)
% If we reach 10^4 iterations we declared the initialization to have
% failed. since actions are selected at random, for small numbers of
% N_Ini and smalle sets convergence should be reached much earlier.
% However, larger sets and N_Init might need to adjust this threshold
% to a larger value.
if ITER > 10000
error('Initialisation Failed.');
end
% Learners Select Files in Parallel (same time)
[Available_Files, New_Learning] = Learners_Files_Selection( S, Learning );
Learning = New_Learning;
% Feedbacks from the users:
% Pre-allocate cumulative Rewards for all users
% Pre-allocate cumulative Penalsties for all users
INI_Rewards = zeros(M,H+1);
INI_Penalties = zeros(M,H+1);
switch Reward_Type
case 'Best_File_Based_Reward'
for n = 1:1:N
% Let each user choose which content they prefer using the
% policy if nearest available (Nearest Content Available
% NCA)
user_selections = User_NCA_Selection( n, S, Available_Files, Network_Delays);
% Calculate the weighted latency that the user would experience
delays(ITER,n) = User_Weighted_Delay( user_selections, Popularities );
this_user_delays = Network_Delays(n,:);
% Let the user provide its own feedback
[Current_Rewards, ~, Current_Penalties, ~ ] = Best_File_Based_Reward( this_user_delays, user_selections, Popularities );
% Update Rewards and Penalties
INI_Rewards = INI_Rewards + Current_Rewards;
INI_Penalties = INI_Penalties + Current_Penalties;
end
case 'Weighted_Delay_Based_Reward'
for n = 1:1:N
% Let each user choose which content they prefer using the
% policy if nearest available (Nearest Content Available
% NCA)
user_selections = User_NCA_Selection( n, S, Available_Files, Network_Delays);
% Calculate the weighted latency that the user would experience
delays(ITER,n) = User_Weighted_Delay( user_selections, Popularities );
% Extract the actual delays that interest this user
this_user_delays = Network_Delays(n,:);
if (Weighted_Delay < Min_Weighted_Delay(n))
Min_Weighted_Delay(n) = Weighted_Delay;
end
if( ITER == 1)
Current_Minima = Inf;
elseif (ITER > 1)
Current_Minima = Min_Weighted_Delay(n);
end
[ Current_Rewards, ~, Current_Penalties, ~ ]...
= Weighted_Delay_Based_Reward( this_user_delays, user_selections, Weighted_Delay, Current_Minima , Popularities );
% Update Rewards and Penalties
INI_Rewards = INI_Rewards + Current_Rewards;
INI_Penalties = INI_Penalties + Current_Penalties;
end
case 'Average_Weighted_Delay_Based_Reward'
Tot_Rewards = zeros(M,H+1,N);
Tot_Penalties = zeros(M,H+1,N);
for n = 1:1:N
% Let each user choose which content they prefer using the
% policy if nearest available (Nearest Content Available
% NCA)
user_selections(n,:,:,:) = User_NCA_Selection( n, S, Available_Files, Network_Delays);
This_User_Selections = squeeze(user_selections(n,:,:,:));
delays(ITER,n) = User_Weighted_Delay( This_User_Selections, Popularities );
this_user_delays = Network_Delays(n,:);
[ Current_Rewards, ~, Current_Penalties, ~ ] = Best_File_Based_Reward( this_user_delays,This_User_Selections, Popularities );
Tot_Rewards(:,:,n) = Current_Rewards;
Tot_Penalties(:,:,n) = Current_Penalties;
end
for j=1:1:H
% Take only the users connected to the learner (j,k)
Who_to_Average = Network_Delays(:,j) ~= Inf;
Average_Weighted_Delay(j) = sum( Weighted_Delay(Who_to_Average)) / sum(Who_to_Average);
if (Average_Weighted_Delay(j) <= Min_Average_Weighted_Delay(j) )
Min_Average_Weighted_Delay(j) = Average_Weighted_Delay(j);
INI_Rewards(:,j) = INI_Rewards(:,j) + sum( squeeze( Tot_Rewards(:,j,:) ),2);
INI_Penalties(:,j) = INI_Penalties(:,j) + sum( squeeze( Tot_Penalties(:,j,:) ),2);
else
INI_Rewards(:,j) = INI_Rewards(:,j);
INI_Penalties(:,j) = INI_Penalties(:,j) + sum( squeeze( Tot_Rewards(:,j,:) ),2) + sum( squeeze( Tot_Penalties(:,j,:) ),2);
end
end
end
% INI Learners Determine the Environment Feedback Democratically
[ Learning, INI_Positive_Feedbacks ] = Determine_Environment_Feedback( Learning, INI_Rewards, INI_Penalties, INI_Positive_Feedbacks);
% CHECKS
Curr_min = Inf;
for j = 1:1:H
for k = 1:1:M
if (min(Learning(k,j).Z) < Curr_min)
Curr_min = min(Learning(k,j).Z);
end
end
end
Lesser_Selected = Curr_min;
Zeros = 0;
MaxNZeros = 0;
for j = 1:1:H
for k = 1:1:M
% All the elements of D of (k,j) are zero. Until Zeros is ~= 0 we should keep initerating.
if (max(Learning(k,j).D) == 0)
Zeros = Zeros+1;
end
if (sum(Learning(k,j).D == 0) > MaxNZeros)
MaxNZeros = sum(Learning(k,j).D == 0);
end
end
end
disp(['INITIALISATION: Iteration ' num2str(ITER) ]);
disp(['The weighted delays are: ' num2str(delays(ITER,:)) '.There are ' num2str(Zeros) ' learners with a zero D vector.']);
disp(['The maximum number of zeros in the D vectors is: ' num2str(MaxNZeros) '.'])
ITER = ITER +1;
end
Iterations = ITER - 1;
% OUTPUT Variables
Learning = Learning;
Network_Delays = Network_Delays;
end
|
github | locatelf/cone-greedy-master | PWNMP.m | .m | cone-greedy-master/NMF/dense_square/PWNMP.m | 2,143 | utf_8 | 5ee02a618bbd1dfeffef955fc3b18dc4 | function [X_r, residual_time,test_error] = PWNMP(Y,X_0,R,nil,LMO_it,X_tst)
%% variables init
convergence_check = zeros(1,R+1);
X_r=X_0;
S = zeros(size(X_0));
alpha = 0;
test_error = zeros(R,1);
residual_time = zeros(1,R);
cnt = 0;
A = zeros(size(Y,1),1);
B = zeros(size(Y,2),1);
for r = 1:R
r
%% call to the oracle
grad = -(Y-X_r);
[a,b,residual] = LMO(-grad,Y,X_r,nil,LMO_it);
residual_time(r) = residual;
Z = a*b';
A = cat(2,A,a);
B = cat(2,B,b);
maxV=0;
idxV=1;
idxZ=-1;
for it=1:numel(alpha)
c = S(:,:,it);
if dot(grad(:),c(:))>maxV
idxV = it;
maxV = dot(grad(:),c(:));
end
if dot(Z(:),c(:)) == norm(Z(:))^2
idxZ = it;
end
end
if idxZ == -1
idxZ = numel(alpha) + 1;
S = cat(3,S,Z);
alpha = [alpha,0];
end
V = S(:,:,idxV);
D = Z - V;
if dot(-grad(:),D(:)) == 0
break
end
gamma = dot(-grad(:),D(:))/norm(D(:));
idxDelete = [];
if idxV~=1
if alpha(idxV)-gamma<=0
gamma = alpha(idxV);
cnt = cnt +1;
idxDelete = idxV;
else
alpha(idxV) = alpha(idxV) - gamma;
A(:,idxV) = A(:,idxV).*sqrt(alpha(idxV));
B(:,idxV) = B(:,idxV).*sqrt(alpha(idxV));
end
end
alpha(idxZ) = alpha(idxZ) + gamma;
A(:,idxZ) = A(:,idxZ).*sqrt(alpha(idxZ));
B(:,idxZ) = B(:,idxZ).*sqrt(alpha(idxZ));
alpha(idxDelete) = [];
S(:,:,idxDelete) = [];
A(:,idxDelete) = [];
B(:,idxDelete) = [];
[Aprov, Bprov, ~] = NMF_GCD(Y,size(A,2)-1,20,A(:,2:end),B(:,2:end)',1);
X_r = Aprov*Bprov;
A = [zeros(size(X_r,1),1), normc(Aprov)];
B = [zeros(size(X_r,2),1), normc(Bprov')];
for itt = 1:size(A,2)
S(:,:,itt) = sparse(A(:,itt)*B(:,itt)');
%Sfull(:,:,itt) = Zprov;
end
alpha = [0,norms(Aprov).*norms(Bprov')];
convergence_check(r) = 2*(sum(X_r(:).^2)-1);
test_error(r) = 0.5*norm(X_tst - X_r,'fro')^2;
r = size(S,3);
end
end
function S = norms(S)
S = sqrt(sum(S.^2,1));
end |
github | locatelf/cone-greedy-master | nnls1_asgivens.m | .m | cone-greedy-master/TensorFactorization/nnls1_asgivens.m | 4,652 | utf_8 | fe4f132c0c6503c13c348aa65cc9e7ef | function [ x,y,success,iter ] = nnls1_asgivens( A,b,overwrite, isInputProd, init )
% Nonnegativity-constrained least squares for single righthand side : minimize |Ax-b|_2
% Jingu Kim ([email protected])
%
% Reference:
% Jingu Kim and Haesun Park. Fast Nonnegative Matrix Factorization: An Activeset-like Method and Comparisons,
% SIAM Journal on Scientific Computing, 33(6), pp. 3261-3281, 2011.
%
% Updated 2011.03.20: First implemented, overwrite option
% Updated 2011.03.21: init option
% Updated 2011.03.23: Givens updating not always
if nargin<3, overwrite = false; end
if nargin<4, isInputProd = false; end
if isInputProd
AtA=A;,Atb=b;
else
AtA=A'*A;, Atb=A'*b;
end
n=size(Atb,1);
MAX_ITER = n*5;
% set initial feasible solution
if overwrite
x = AtA\Atb;
x(x<0) = 0;
PassiveList = find(x > 0)';
R = chol(AtA(PassiveList,PassiveList));
Rinv_b = (R')\Atb(PassiveList);
iter = 1;
else
if nargin<5
PassiveList = [];
R = [];
Rinv_b = zeros(0,0);
x = zeros(n,1);
else
x = init;
x(x<0) = 0;
PassiveList = find(x > 0)';
R = chol(AtA(PassiveList,PassiveList));
Rinv_b = (R')\Atb(PassiveList);
end
iter=0;
end
success=1;
while(success)
if iter >= MAX_ITER, break, end
% find unconstrained LS solution for the passive set
if ~isempty(PassiveList)
z = R\Rinv_b;
iter = iter + 1;
else
z = [];
end
z( abs(z)<1e-12 ) = 0; % One can uncomment this line for numerical stability.
InfeaSet = find(z < 0);
if isempty(InfeaSet) % if feasibile
x(:) = 0;
x(PassiveList) = z;
y = AtA * x - Atb;
y( PassiveList) = 0;
y( abs(y)<1e-12 ) = 0; % One can uncomment this line for numerical stability.
NonOptSet = find(y < 0);
if isempty(NonOptSet), success=0; % check optimality
else
[minVal,minIx] = min(y);
PassiveList = [PassiveList minIx]; % increase passive set
[R,Rinv_b] = cholAdd(R,AtA(PassiveList,minIx),Rinv_b,Atb(minIx));
end
else % if not feasibile
x_pass = x(PassiveList);
x_infeaset = x_pass(InfeaSet);
z_infeaset = z(InfeaSet);
[minVal,minIx] = min(x_infeaset./(x_infeaset-z_infeaset));
x_pass_new = x_pass+(z-x_pass).*minVal;
x_pass_new(InfeaSet(minIx))=0;
zeroSetSub = sort(find(x_pass_new==0),'descend');
for i=1:length(zeroSetSub)
subidx = zeroSetSub(i);
PassiveList(subidx) = [];
% Givens updating is not always better (maybe only in matlab?).
if subidx >= 0.9 * size(R,2)
R = cholDelete(R,subidx);
else
R = chol(AtA(PassiveList,PassiveList));
end
end
Rinv_b = (R')\Atb(PassiveList);
x_pass_new(x_pass_new == 0) = [];
x(:) = 0;
x(PassiveList) = x_pass_new;
end
end
end
function [new_R,new_d] = cholAdd(R,v,d,val)
if isempty(R)
new_R = sqrt(v);
new_d = val/new_R;
else
n = size(R,1);
new_R = zeros(n+1,n+1);
new_R(1:n,1:n)=R;
vec = zeros(n+1,1);
vec(1:n)=R'\v(1:n);
vec(n+1)=sqrt(v(n+1)-vec(1:n)'*vec(1:n));
new_R(:,n+1) = vec;
new_d = [d;zeros(1,1)];
new_d(n+1) = (val-vec(1:n)'*d)/vec(n+1);
end
end
function [new_R] = cholDelete(R,idx)
n = size(R,1);
new_R = R;
new_R(:,idx) = [];
for i=idx:n-1
%G=getGivens(new_R(:,i),i,i+1);
G=planerot(new_R([i i+1],i));
new_R([i i+1],:)=G*new_R([i i+1],:);, new_R(i+1,i)=0;
end
new_R = new_R(1:n-1,1:n-1);
end
% function [G]=getGivens(a,i,j)
% G=zeros(2,2);
% [c,s]=givensRotation(a(i),a(j));
% G(1,1)=c;
% G(1,2)=s;
% G(2,1)=-s;
% G(2,2)=c;
% end
%
% function [c,s]=givensRotation(a,b)
% % Givens Rotation to annihilate b with respect to a
% if(b==0)
% c=1;s=0;
% else
% if (abs(b)>abs(a))
% t=-a/b;
% s=1/sqrt(1+t*t);
% c=s*t;
% else
% t=-b/a;
% c=1/sqrt(1+t*t);
% s=c*t;
% end
% end
% end
|
github | locatelf/cone-greedy-master | cast_to_set.m | .m | cone-greedy-master/TensorFactorization/cast_to_set.m | 624 | utf_8 | 0a51464057642c461237748e511a466f | function rez = cast_to_set(rez,normalized,non_negative,sparsity)
if strcmp(non_negative,'true')
rez(rez<0)=0;
end
if ~strcmp(sparsity,'0')
rez = to_sparse(rez,str2double(sparsity));
end
if strcmp(normalized,'true')
rez=rez./norm(rez);
end
end
function in = to_sparse(in,k)
[~,sortIndex] = sort(abs(in(:)),'ascend'); %# Sort the values in ascending order
assert(size(sortIndex,1)-k>=0,'non zero falues greater than number of entries')
minIndex = sortIndex(1:size(sortIndex,1)-k); %# Get a linear index into A of the 5 largest values
in(minIndex) = 0;
end |
github | locatelf/cone-greedy-master | nmf.m | .m | cone-greedy-master/TensorFactorization/nmf.m | 23,853 | utf_8 | 7462a6647d7acb938254b76c028c50d1 | % Nonnegative Matrix Factorization Algorithms Toolbox
%
% Written by Jingu Kim ([email protected])
% Work done at
% School of Computational Science and Engineering
% College of Computing, Georgia Institute of Technology
%
% Please send bug reports, comments, or questions to Jingu Kim.
% This code comes with no guarantee or warranty of any kind.
%
% Reference:
% [1] Jingu Kim, Yunlong He, and Haesun Park.
% Algorithms for Nonnegative Matrix and Tensor Factorizations: A Unified View
% Based on Block Coordinate Descent Framework.
% Journal of Global Optimization, 58(2), pp. 285-319, 2014.
%
% [2] Jingu Kim and Haesun Park.
% Fast Nonnegative Matrix Factorization: An Active-set-like Method And Comparisons.
% SIAM Journal on Scientific Computing (SISC), 33(6), pp. 3261-3281, 2011.
%
% Last modified on 07/28/2013
%
% <Inputs>
% A : Input data matrix (m x n)
% k : Target low-rank
%
% (Below are optional arguments: can be set by providing name-value pairs)
%
% METHOD : Algorithm for solving NMF. Available values are as follows. Default is 'anls_bpp'.
% 'anls_bpp' : ANLS with Block Principal Pivoting Method
% 'anls_asgivens': ANLS with Active Set Method and Givens Updating
% 'anls_asgroup' : ANLS with Active Set Method and Column Grouping
% 'als' : Alternating Least Squares Method
% 'hals' : Hierarchical Alternating Least Squares Method
% 'mu' : Multiplicative Updating Method
% See publication [1] (and references therein) for the details of these algorithms.
% TOL : Stopping tolerance. Default is 1e-3.
% If you want to obtain a more accurate solution,
% decrease TOL and increase MAX_ITER at the same time.
% Note that algorithms will need more time to terminate if you do so.
% MAX_ITER : Maximum number of iterations. Default is 500.
% MIN_ITER : Minimum number of iterations. Default is 20.
% MAX_TIME : Maximum amount of time in seconds. Default is 1,000,000.
% INIT : A struct containing initial values. INIT.W and INIT.H should contain
% initial values of W and H of size (m x k) and (k x n), respectively.
% When INIT is not given, W and H are randomly initialized.
% VERBOSE : 0 (default) - No debugging information is collected.
% 1 (debugging/experimental purpose) - History of computation is returned.
% See 'REC' variable.
% 2 (debugging/experimental purpose) - History of computation is additionally
% printed on screen.
% REG_W, REG_H : Regularization parameters for W and H.
% Both REG_W and REG_H should be vector of two nonnegative numbers.
% The first component is a parameter with Frobenius norm regularization, and
% the second component is a parameter with L1-norm regularization.
% For example, to promote sparsity in H, one might set
% REG_W = [alpha 0] and REG_H = [0 beta]
% where alpha and beta are positive numbers.
% See papers [1] and [2] for more details.
% Defaut is [0 0] for both REG_W and REG_H, which means no regularization.
% <Outputs>
% W : Obtained basis matrix (m x k)
% H : Obtained coefficient matrix (k x n)
% iter : Number of iterations
% HIS : (debugging/experimental purpose) Auxiliary information about the execution
% <Usage Examples>
% nmf(A,10)
% nmf(A,20,'verbose',2)
% nmf(A,20,'verbose',1,'method','anls_bpp')
% nmf(A,20,'verbose',1,'method','hals')
% nmf(A,20,'verbose',1,'reg_w',[0.1 0],'reg_h',[0 0.5])
function [W,H,iter,REC]=nmf(A,k,varargin)
% parse parameters
params = inputParser;
params.addParamValue('method' ,'anls_bpp',@(x) ischar(x) );
params.addParamValue('tol' ,1e-3 ,@(x) isscalar(x) & x > 0);
params.addParamValue('min_iter' ,20 ,@(x) isscalar(x) & x > 0);
params.addParamValue('max_iter' ,500 ,@(x) isscalar(x) & x > 0);
params.addParamValue('max_time' ,1e6 ,@(x) isscalar(x) & x > 0);
params.addParamValue('init' ,struct([]),@(x) isstruct(x));
params.addParamValue('verbose' ,1 ,@(x) isscalar(x) & x >= 0);
params.addParamValue('reg_w' ,[0 0] ,@(x) isvector(x) & length(x) == 2);
params.addParamValue('reg_h' ,[0 0] ,@(x) isvector(x) & length(x) == 2);
% The following options are reserved for debugging/experimental purposes.
% Make sure to understand them before making changes
params.addParamValue('subparams' ,struct([]),@(x) isstruct(x) );
params.addParamValue('track_grad' ,1 ,@(x) isscalar(x) & x >= 0);
params.addParamValue('track_prev' ,1 ,@(x) isscalar(x) & x >= 0);
params.addParamValue('stop_criterion',2 ,@(x) isscalar(x) & x >= 0);
params.parse(varargin{:});
% copy from params object
[m,n] = size(A);
par = params.Results;
par.m = m;
par.n = n;
par.k = k;
% If stopping criterion is based on the gradient information, turn on 'track_grad' option.
if par.stop_criterion > 0
par.track_grad = 1;
end
% initialize
if isempty(par.init)
W = rand(m,k); H = rand(k,n);
else
W = par.init.W; H = par.init.H;
end
% This variable is for analysis/debugging, so it does not affect the output (W,H) of this program
REC = struct([]);
clear('init');
init.norm_A = norm(A,'fro');
init.norm_W = norm(W,'fro');
init.norm_H = norm(H,'fro');
init.baseObj = getObj((init.norm_A)^2,W,H,par);
if par.verbose % Collect initial information for analysis/debugging
if par.track_grad
[gradW,gradH] = getGradient(A,W,H,par);
init.normGr_W = norm(gradW,'fro');
init.normGr_H = norm(gradH,'fro');
init.SC_NM_PGRAD = getInitCriterion(1,A,W,H,par,gradW,gradH);
init.SC_PGRAD = getInitCriterion(2,A,W,H,par,gradW,gradH);
init.SC_DELTA = getInitCriterion(3,A,W,H,par,gradW,gradH);
else
gradW = 0; gradH = 0;
end
if par.track_prev
prev_W = W; prev_H = H;
else
prev_W = 0; prev_H = 0;
end
ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,0,0,gradW,gradH);
REC(1).init = init;
REC.HIS = ver;
if par.verbose == 2
display(init);
end
tPrev = cputime;
end
initializer= str2func([par.method,'_initializer']);
iterSolver = str2func([par.method,'_iterSolver']);
iterLogger = str2func([par.method,'_iterLogger']);
[W,H,par,val,ver] = feval(initializer,A,W,H,par);
if par.verbose & ~isempty(ver)
tTemp = cputime;
REC.HIS = saveHIS(1,ver,REC.HIS);
tPrev = tPrev+(cputime-tTemp);
end
REC(1).par = par;
REC.start_time = datestr(now);
display(par);
tStart = cputime;, tTotal = 0;
if par.track_grad
initSC = getInitCriterion(par.stop_criterion,A,W,H,par);
end
SCconv = 0; SC_COUNT = 3;
for iter=1:par.max_iter
% Actual work of this iteration is executed here.
[W,H,gradW,gradH,val] = feval(iterSolver,A,W,H,iter,par,val);
if par.verbose % Collect information for analysis/debugging
elapsed = cputime-tPrev;
tTotal = tTotal + elapsed;
clear('ver');
ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,iter,elapsed,gradW,gradH);
ver = feval(iterLogger,ver,par,val,W,H,prev_W,prev_H);
REC.HIS = saveHIS(iter+1,ver,REC.HIS);
if par.track_prev, prev_W = W; prev_H = H; end
if par.verbose == 2, display(ver);, end
tPrev = cputime;
end
if (iter > par.min_iter)
if (par.verbose && (tTotal > par.max_time)) || (~par.verbose && ((cputime-tStart)>par.max_time))
break;
elseif par.track_grad
SC = getStopCriterion(par.stop_criterion,A,W,H,par,gradW,gradH);
if (SC/initSC <= par.tol)
SCconv = SCconv + 1;
if (SCconv >= SC_COUNT), break;, end
else
SCconv = 0;
end
end
end
end
[m,n]=size(A);
[W,H]=normalize_by_W(W,H);
if par.verbose
final.elapsed_total = sum(REC.HIS.elapsed);
else
final.elapsed_total = cputime-tStart;
end
final.iterations = iter;
sqErr = getSquaredError(A,W,H,init);
final.relative_error = sqrt(sqErr)/init.norm_A;
final.relative_obj = getObj(sqErr,W,H,par)/init.baseObj;
final.W_density = length(find(W>0))/(m*k);
final.H_density = length(find(H>0))/(n*k);
if par.verbose
REC.final = final;
end
REC.finish_time = datestr(now);
display(final);
end
%----------------------------------------------------------------------------
% Implementation of methods
%----------------------------------------------------------------------------
% 'anls_bpp' : ANLS with Block Principal Pivoting Method
% See nnlsm_blockpivot.m for reference and details.
function [W,H,par,val,ver] = anls_bpp_initializer(A,W,H,par)
H = zeros(size(H));
ver.turnZr_W = 0;
ver.turnZr_H = 0;
ver.turnNz_W = 0;
ver.turnNz_H = 0;
ver.numChol_W = 0;
ver.numChol_H = 0;
ver.numEq_W = 0;
ver.numEq_H = 0;
ver.suc_W = 0;
ver.suc_H = 0;
val(1).WtA = W'*A;
val.WtW = W'*W;
end
function [W,H,gradW,gradH,val] = anls_bpp_iterSolver(A,W,H,iter,par,val)
WtW_reg = applyReg(val.WtW,par,par.reg_h);
[H,temp,suc_H,numChol_H,numEq_H] = nnlsm_blockpivot(WtW_reg,val.WtA,1,H);
HHt_reg = applyReg(H*H',par,par.reg_w);
[W,gradW,suc_W,numChol_W,numEq_W] = nnlsm_blockpivot(HHt_reg,H*A',1,W');
W = W';
val.WtA = W'*A;
val.WtW = W'*W;
if par.track_grad
gradW = gradW';
gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par);
else
gradW = 0;gradH =0;
end
val(1).numChol_W = numChol_W;
val.numChol_H = numChol_H;
val.numEq_W = numEq_W;
val.numEq_H = numEq_H;
val.suc_W = suc_W;
val.suc_H = suc_H;
end
function [ver] = anls_bpp_iterLogger(ver,par,val,W,H,prev_W,prev_H)
if par.track_prev
ver.turnZr_W = length(find( (prev_W>0) & (W==0) ))/(par.m*par.k);
ver.turnZr_H = length(find( (prev_H>0) & (H==0) ))/(par.n*par.k);
ver.turnNz_W = length(find( (prev_W==0) & (W>0) ))/(par.m*par.k);
ver.turnNz_H = length(find( (prev_H==0) & (H>0) ))/(par.n*par.k);
end
ver.numChol_W = val.numChol_W;
ver.numChol_H = val.numChol_H;
ver.numEq_W = val.numEq_W;
ver.numEq_H = val.numEq_H;
ver.suc_W = val.suc_W;
ver.suc_H = val.suc_H;
end
% 'anls_asgivens': ANLS with Active Set Method and Givens Updating
% See nnls1_asgivens.m for reference and details.
function [W,H,par,val,ver] = anls_asgivens_initializer(A,W,H,par)
H = zeros(size(H));
ver.turnZr_W = 0;
ver.turnZr_H = 0;
ver.turnNz_W = 0;
ver.turnNz_H = 0;
ver.numChol_W = 0;
ver.numChol_H = 0;
ver.suc_W = 0;
ver.suc_H = 0;
val(1).WtA = W'*A;
val.WtW = W'*W;
end
function [W,H,gradW,gradH,val] = anls_asgivens_iterSolver(A,W,H,iter,par,val)
WtW_reg = applyReg(val.WtW,par,par.reg_h);
ow = 0;
suc_H = zeros(1,size(H,2));
numChol_H = zeros(1,size(H,2));
for i=1:size(H,2)
[H(:,i),temp,suc_H(i),numChol_H(i)] = nnls1_asgivens(WtW_reg,val.WtA(:,i),ow,1,H(:,i));
end
suc_W = zeros(1,size(W,1));
numChol_W = zeros(1,size(W,1));
HHt_reg = applyReg(H*H',par,par.reg_w);
HAt = H*A';
Wt = W';
gradWt = zeros(size(Wt));
for i=1:size(W,1)
[Wt(:,i),gradWt(:,i),suc_W(i),numChol_W(i)] = nnls1_asgivens(HHt_reg,HAt(:,i),ow,1,Wt(:,i));
end
W = Wt';
val.WtA = W'*A;
val.WtW = W'*W;
if par.track_grad
gradW = gradWt';
gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par);
else
gradW = 0; gradH =0;
end
val(1).numChol_W = sum(numChol_W);
val.numChol_H = sum(numChol_H);
val.suc_W = any(suc_W);
val.suc_H = any(suc_H);
end
function [ver] = anls_asgivens_iterLogger(ver,par,val,W,H,prev_W,prev_H)
if par.track_prev
ver.turnZr_W = length(find( (prev_W>0) & (W==0) ))/(par.m*par.k);
ver.turnZr_H = length(find( (prev_H>0) & (H==0) ))/(par.n*par.k);
ver.turnNz_W = length(find( (prev_W==0) & (W>0) ))/(par.m*par.k);
ver.turnNz_H = length(find( (prev_H==0) & (H>0) ))/(par.n*par.k);
end
ver.numChol_W = val.numChol_W;
ver.numChol_H = val.numChol_H;
ver.suc_W = val.suc_W;
ver.suc_H = val.suc_H;
end
% 'anls_asgroup' : ANLS with Active Set Method and Column Grouping
% See nnlsm_activeset.m for reference and details.
function [W,H,par,val,ver] = anls_asgroup_initializer(A,W,H,par)
[W,H,par,val,ver] = anls_bpp_initializer(A,W,H,par);
end
function [W,H,gradW,gradH,val] = anls_asgroup_iterSolver(A,W,H,iter,par,val)
WtW_reg = applyReg(val.WtW,par,par.reg_h);
ow = 0;
[H,temp,suc_H,numChol_H,numEq_H] = nnlsm_activeset(WtW_reg,val.WtA,ow,1,H);
HHt_reg = applyReg(H*H',par,par.reg_w);
[W,gradW,suc_W,numChol_W,numEq_W] = nnlsm_activeset(HHt_reg,H*A',ow,1,W');
W = W';
val.WtA = W'*A;
val.WtW = W'*W;
if par.track_grad
gradW = gradW';
gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par);
else
gradW = 0; gradH =0;
end
val(1).numChol_W = numChol_W;
val.numChol_H = numChol_H;
val.numEq_W = numEq_W;
val.numEq_H = numEq_H;
val.suc_W = suc_W;
val.suc_H = suc_H;
end
function [ver] = anls_asgroup_iterLogger(ver,par,val,W,H,prev_W,prev_H)
ver = anls_bpp_iterLogger(ver,par,val,W,H,prev_W,prev_H);
end
% 'als': Alternating Least Squares Method
% Reference:
% Berry, M. and Browne, M. and Langville, A. and Pauca, V. and Plemmons, R.
% Algorithms and applications for approximate nonnegative matrix factorization.
% Computational Statistics and Data Analysis, 52(1), pp. 155–173 ,2007
function [W,H,par,val,ver] = als_initializer(A,W,H,par)
ver = struct([]);
val.WtA = W'*A;
val.WtW = W'*W;
end
function [W,H,gradW,gradH,val] = als_iterSolver(A,W,H,iter,par,val)
WtW_reg = applyReg(val.WtW,par,par.reg_h);
H = WtW_reg\val.WtA;
H(H<0)=0;
AHt = A*H';
HHt_reg = applyReg(H*H',par,par.reg_w);
Wt = HHt_reg\AHt'; W=Wt';
W(W<0)=0;
% normalize : necessary for ALS
[W,H,weights] = normalize_by_W(W,H);
D = diag(weights);
val.WtA = W'*A;
val.WtW = W'*W;
AHt = AHt*D;
HHt_reg = D*HHt_reg*D;
if par.track_grad
gradW = W*HHt_reg - AHt;
gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par);
else
gradH = 0; gradW = 0;
end
end
function [ver] = als_iterLogger(ver,par,val,W,H,prev_W,prev_H)
end
% 'mu' : Multiplicative Updating Method
% Reference:
% Lee, D. D. and Seung, H. S.
% Algorithms for Non-negative Matrix Factorization.
% Advances in Neural Information Processing Systems 13, pp. 556-562, 2001
function [W,H,par,val,ver] = mu_initializer(A,W,H,par)
ver = struct([]);
val.WtA = W'*A;
val.WtW = W'*W;
end
function [W,H,gradW,gradH,val] = mu_iterSolver(A,W,H,iter,par,val)
epsilon = 1e-16;
WtW_reg = applyReg(val.WtW,par,par.reg_h);
H = H.*val.WtA./(WtW_reg*H + epsilon);
HHt_reg = applyReg(H*H',par,par.reg_w);
AHt = A*H';
W = W.*AHt./(W*HHt_reg + epsilon);
val.WtA = W'*A;
val.WtW = W'*W;
if par.track_grad
gradW = W*HHt_reg - AHt;
gradH = getGradientOne(val.WtW,val.WtA,H,par.reg_h,par);
else
gradH = 0; gradW = 0;
end
end
function [ver] = mu_iterLogger(ver,par,val,W,H,prev_W,prev_H)
end
% 'hals' : Hierarchical Alternating Least Squares Method
% Reference (See Algorithm 2):
% Cichocki, A. and Phan, A.H.
% Fast local algorithms for large scale nonnegative matrix and tensor factorizations.
% IEICE Trans. Fundam. Electron. Commun. Comput. Sci. E92-A(3), 708–721 (2009)
function [W,H,par,val,ver] = hals_initializer(A,W,H,par)
[W,H]=normalize_by_W(W,H);
val = struct([]);
ver = struct([]);
end
function [W,H,gradW,gradH,val] = hals_iterSolver(A,W,H,iter,par,val)
epsilon = 1e-16;
WtA = W'*A;
WtW = W'*W;
WtW_reg = applyReg(WtW,par,par.reg_h);
for i = 1:par.k
H(i,:) = max(H(i,:) + WtA(i,:) - WtW_reg(i,:) * H,epsilon);
end
AHt = A*H';
HHt_reg = applyReg(H*H',par,par.reg_w);
for i = 1:par.k
W(:,i) = max(W(:,i) * HHt_reg(i,i) + AHt(:,i) - W * HHt_reg(:,i),epsilon);
if sum(W(:,i))>0
W(:,i) = W(:,i)/norm(W(:,i));
end
end
if par.track_grad
gradW = W*HHt_reg - AHt;
gradH = getGradientOne(W'*W,W'*A,H,par.reg_h,par);
else
gradH = 0; gradW = 0;
end
end
function [ver] = hals_iterLogger(ver,par,val,W,H,prev_W,prev_H)
end
%----------------------------------------------------------------------------------------------
% Utility Functions
%----------------------------------------------------------------------------------------------
% This function prepares information about execution for a experiment purpose
function ver = prepareHIS(A,W,H,prev_W,prev_H,init,par,iter,elapsed,gradW,gradH)
ver.iter = iter;
ver.elapsed = elapsed;
sqErr = getSquaredError(A,W,H,init);
ver.rel_Error = sqrt(sqErr)/init.norm_A;
ver.rel_Obj = getObj(sqErr,W,H,par)/init.baseObj;
ver.norm_W = norm(W,'fro');
ver.norm_H = norm(H,'fro');
if par.track_prev
ver.rel_Change_W = norm(W-prev_W,'fro')/init.norm_W;
ver.rel_Change_H = norm(H-prev_H,'fro')/init.norm_H;
end
if par.track_grad
ver.rel_NrPGrad_W = norm(projGradient(W,gradW),'fro')/init.normGr_W;
ver.rel_NrPGrad_H = norm(projGradient(H,gradH),'fro')/init.normGr_H;
ver.SC_NM_PGRAD = getStopCriterion(1,A,W,H,par,gradW,gradH)/init.SC_NM_PGRAD;
ver.SC_PGRAD = getStopCriterion(2,A,W,H,par,gradW,gradH)/init.SC_PGRAD;
ver.SC_DELTA = getStopCriterion(3,A,W,H,par,gradW,gradH)/init.SC_DELTA;
end
ver.density_W = length(find(W>0))/(par.m*par.k);
ver.density_H = length(find(H>0))/(par.n*par.k);
end
% Execution information is collected in HIS variable
function HIS = saveHIS(idx,ver,HIS)
fldnames = fieldnames(ver);
for i=1:length(fldnames)
flname = fldnames{i};
HIS.(flname)(idx) = ver.(flname);
end
end
%-------------------------------------------------------------------------------
function retVal = getInitCriterion(stopRule,A,W,H,par,gradW,gradH)
% STOPPING_RULE : 1 - Normalized proj. gradient
% 2 - Proj. gradient
% 3 - Delta by H. Kim
% 0 - None (want to stop by MAX_ITER or MAX_TIME)
if nargin~=7
[gradW,gradH] = getGradient(A,W,H,par);
end
[m,k]=size(W);, [k,n]=size(H);, numAll=(m*k)+(k*n);
switch stopRule
case 1
retVal = norm([gradW(:); gradH(:)])/numAll;
case 2
retVal = norm([gradW(:); gradH(:)]);
case 3
retVal = getStopCriterion(3,A,W,H,par,gradW,gradH);
case 0
retVal = 1;
end
end
%-------------------------------------------------------------------------------
function retVal = getStopCriterion(stopRule,A,W,H,par,gradW,gradH)
% STOPPING_RULE : 1 - Normalized proj. gradient
% 2 - Proj. gradient
% 3 - Delta by H. Kim
% 0 - None (want to stop by MAX_ITER or MAX_TIME)
if nargin~=7
[gradW,gradH] = getGradient(A,W,H,par);
end
switch stopRule
case 1
pGradW = projGradient(W,gradW);
pGradH = projGradient(H,gradH);
pGrad = [pGradW(:); pGradH(:)];
retVal = norm(pGrad)/length(pGrad);
case 2
pGradW = projGradient(W,gradW);
pGradH = projGradient(H,gradH);
pGrad = [pGradW(:); pGradH(:)];
retVal = norm(pGrad);
case 3
resmat=min(H,gradH); resvec=resmat(:);
resmat=min(W,gradW); resvec=[resvec; resmat(:)];
deltao=norm(resvec,1); %L1-norm
num_notconv=length(find(abs(resvec)>0));
retVal=deltao/num_notconv;
case 0
retVal = 1e100;
end
end
%-------------------------------------------------------------------------------
function sqErr = getSquaredError(A,W,H,init)
sqErr = max((init.norm_A)^2 - 2*trace(H*(A'*W))+trace((W'*W)*(H*H')),0 );
end
function retVal = getObj(sqErr,W,H,par)
retVal = 0.5 * sqErr;
retVal = retVal + par.reg_w(1) * sum(sum(W.*W));
retVal = retVal + par.reg_w(2) * sum(sum(W,2).^2);
retVal = retVal + par.reg_h(1) * sum(sum(H.*H));
retVal = retVal + par.reg_h(2) * sum(sum(H,1).^2);
end
function AtA = applyReg(AtA,par,reg)
% Frobenius norm regularization
if reg(1) > 0
AtA = AtA + 2 * reg(1) * eye(par.k);
end
% L1-norm regularization
if reg(2) > 0
AtA = AtA + 2 * reg(2) * ones(par.k,par.k);
end
end
function [grad] = modifyGradient(grad,X,reg,par)
if reg(1) > 0
grad = grad + 2 * reg(1) * X;
end
if reg(2) > 0
grad = grad + 2 * reg(2) * ones(par.k,par.k) * X;
end
end
function [grad] = getGradientOne(AtA,AtB,X,reg,par)
grad = AtA*X - AtB;
grad = modifyGradient(grad,X,reg,par);
end
function [gradW,gradH] = getGradient(A,W,H,par)
HHt = H*H';
HHt_reg = applyReg(HHt,par,par.reg_w);
WtW = W'*W;
WtW_reg = applyReg(WtW,par,par.reg_h);
gradW = W*HHt_reg - A*H';
gradH = WtW_reg*H - W'*A;
end
%-------------------------------------------------------------------------------
function pGradF = projGradient(F,gradF)
pGradF = gradF(gradF<0|F>0);
end
%-------------------------------------------------------------------------------
function [W,H,weights] = normalize_by_W(W,H)
norm2=sqrt(sum(W.^2,1));
toNormalize = norm2>0;
if any(toNormalize)
W(:,toNormalize) = W(:,toNormalize)./repmat(norm2(toNormalize),size(W,1),1);
H(toNormalize,:) = H(toNormalize,:).*repmat(norm2(toNormalize)',1,size(H,2));
end
weights = ones(size(norm2));
weights(toNormalize) = norm2(toNormalize);
end
|
github | locatelf/cone-greedy-master | nnlsm_blockpivot.m | .m | cone-greedy-master/TensorFactorization/nnlsm_blockpivot.m | 4,542 | utf_8 | 376a788b205edbb0344ec40fc5afbf9f | % Nonnegativity Constrained Least Squares with Multiple Righthand Sides
% using Block Principal Pivoting method
%
% This software solves the following problem: given A and B, find X such that
% minimize || AX-B ||_F^2 where X>=0 elementwise.
%
% Reference:
% Jingu Kim and Haesun Park. Fast Nonnegative Matrix Factorization: An Activeset-like Method and Comparisons,
% SIAM Journal on Scientific Computing, 33(6), pp. 3261-3281, 2011.
%
% Written by Jingu Kim ([email protected])
% School of Computational Science and Engineering,
% Georgia Institute of Technology
%
% Note that this algorithm assumes that the input matrix A has full column rank.
% This code comes with no guarantee or warranty of any kind.
% Please send bug reports, comments, or questions to Jingu Kim.
%
% Modified Feb-20-2009
% Modified Mar-13-2011: numChol and numEq
%
% <Inputs>
% A : input matrix (m x n) (by default), or A'*A (n x n) if isInputProd==1
% B : input matrix (m x k) (by default), or A'*B (n x k) if isInputProd==1
% isInputProd : (optional, default:0) if turned on, use (A'*A,A'*B) as input instead of (A,B)
% init : (optional) initial value for X
% <Outputs>
% X : the solution (n x k)
% Y : A'*A*X - A'*B where X is the solution (n x k)
% success : 0 for success, 1 for failure.
% Failure could only happen on a numericall very ill-conditioned problem.
% numChol : number of unique cholesky decompositions done
% numEqs : number of systems of linear equations solved
function [ X,Y,success,numChol,numEq ] = nnlsm_blockpivot( A, B, isInputProd, init )
if nargin<3, isInputProd=0;, end
if isInputProd
AtA = A;, AtB = B;
else
AtA = A'*A;, AtB = A'*B;
end
if size(AtA,1)==1
X = AtB/AtA; X(X<0) = 0;
Y = AtA*X - AtB;
numChol = 1; numEq = size(AtB,2); success = 1;
return
end
[n,k]=size(AtB);
MAX_BIG_ITER = n*5;
% set initial feasible solution
X = zeros(n,k);
if nargin<4
Y = - AtB;
PassiveSet = false(n,k);
numChol = 0;
numEq = 0;
else
PassiveSet = (init > 0);
[ X,numChol,numEq] = normalEqComb(AtA,AtB,PassiveSet);
Y = AtA * X - AtB;
end
% parameters
pbar = 3;
P = zeros(1,k);, P(:) = pbar;
Ninf = zeros(1,k);, Ninf(:) = n+1;
NonOptSet = (Y < 0) & ~PassiveSet;
InfeaSet = (X < 0) & PassiveSet;
NotGood = sum(NonOptSet)+sum(InfeaSet);
NotOptCols = NotGood > 0;
bigIter = 0;, success=0;
while(~isempty(find(NotOptCols)))
bigIter = bigIter+1;
if ((MAX_BIG_ITER >0) && (bigIter > MAX_BIG_ITER)) % set max_iter for ill-conditioned (numerically unstable) case
success = 1;, break
end
Cols1 = NotOptCols & (NotGood < Ninf);
Cols2 = NotOptCols & (NotGood >= Ninf) & (P >= 1);
Cols3Ix = find(NotOptCols & ~Cols1 & ~Cols2);
if ~isempty(find(Cols1))
P(Cols1) = pbar;,Ninf(Cols1) = NotGood(Cols1);
PassiveSet(NonOptSet & repmat(Cols1,n,1)) = true;
PassiveSet(InfeaSet & repmat(Cols1,n,1)) = false;
end
if ~isempty(find(Cols2))
P(Cols2) = P(Cols2)-1;
PassiveSet(NonOptSet & repmat(Cols2,n,1)) = true;
PassiveSet(InfeaSet & repmat(Cols2,n,1)) = false;
end
if ~isempty(Cols3Ix)
for i=1:length(Cols3Ix)
Ix = Cols3Ix(i);
toChange = max(find( NonOptSet(:,Ix)|InfeaSet(:,Ix) ));
if PassiveSet(toChange,Ix)
PassiveSet(toChange,Ix)=false;
else
PassiveSet(toChange,Ix)=true;
end
end
end
[ X(:,NotOptCols),tempChol,tempEq ] = normalEqComb(AtA,AtB(:,NotOptCols),PassiveSet(:,NotOptCols));
numChol = numChol + tempChol;
numEq = numEq + tempEq;
X(abs(X)<1e-12) = 0; % One can uncomment this line for numerical stability.
Y(:,NotOptCols) = AtA * X(:,NotOptCols) - AtB(:,NotOptCols);
Y(abs(Y)<1e-12) = 0; % One can uncomment this line for numerical stability.
% check optimality
NotOptMask = repmat(NotOptCols,n,1);
NonOptSet = NotOptMask & (Y < 0) & ~PassiveSet;
InfeaSet = NotOptMask & (X < 0) & PassiveSet;
NotGood = sum(NonOptSet)+sum(InfeaSet);
NotOptCols = NotGood > 0;
end
end
|
github | locatelf/cone-greedy-master | nnlsm_activeset.m | .m | cone-greedy-master/TensorFactorization/nnlsm_activeset.m | 5,185 | utf_8 | 96f73fcf70f7083cd2d2a9bd9f71767a | % Nonnegativity Constrained Least Squares with Multiple Righthand Sides
% using Active Set method
%
% This software solves the following problem: given A and B, find X such that
% minimize || AX-B ||_F^2 where X>=0 elementwise.
%
% Reference:
% Charles L. Lawson and Richard J. Hanson, Solving Least Squares Problems,
% Society for Industrial and Applied Mathematics, 1995
% M. H. Van Benthem and M. R. Keenan,
% Fast Algorithm for the Solution of Large-scale Non-negativity-constrained Least Squares Problems,
% J. Chemometrics 2004; 18: 441-450
%
% Written by Jingu Kim ([email protected])
% School of Computational Science and Engineering,
% Georgia Institute of Technology
%
% Please send bug reports, comments, or questions to Jingu Kim.
%
% Updated Feb-20-2010
% Updated Mar-20-2011: numChol, numEq
%
% <Inputs>
% A : input matrix (m x n) (by default), or A'*A (n x n) if isInputProd==1
% B : input matrix (m x k) (by default), or A'*B (n x k) if isInputProd==1
% overwrite : (optional, default:0) if turned on, unconstrained least squares solution is computed in the beginning
% isInputProd : (optional, default:0) if turned on, use (A'*A,A'*B) as input instead of (A,B)
% init : (optional) initial value for X
% <Outputs>
% X : the solution (n x k)
% Y : A'*A*X - A'*B where X is the solution (n x k)
% iter : number of systems of linear equations solved
% success : 0 for success, 1 for failure.
% Failure could only happen on a numericall very ill-conditioned problem.
function [ X,Y,success,numChol,numEq ] = nnlsm_activeset( A, B, overwrite, isInputProd, init)
if nargin<3, overwrite=0;, end
if nargin<4, isInputProd=0;, end
if isInputProd
AtA=A;,AtB=B;
else
AtA=A'*A;, AtB=A'*B;
end
if size(AtA,1)==1
X = AtB/AtA; X(X<0) = 0;
Y = AtA*X - AtB;
numChol = 1; numEq = size(AtB,2); success = 1;
return
end
[n,k]=size(AtB);
MAX_ITER = n*5;
% set initial feasible solution
if overwrite
[X,numChol,numEq] = normalEqComb(AtA,AtB);
PassSet = (X > 0);
NotOptSet = any(X<0);
elseif nargin>=5
X = init;
X(X<0)=0;
PassSet = (X > 0);
NotOptSet = true(1,k);
numChol = 0;
numEq = 0;
else
X = zeros(n,k);
PassSet = false(n,k);
NotOptSet = true(1,k);
numChol = 0;
numEq = 0;
end
Y = zeros(n,k);
Y(:,~NotOptSet)=AtA*X(:,~NotOptSet) - AtB(:,~NotOptSet);
NotOptCols = find(NotOptSet);
bigIter = 0;, success=0;
while(~isempty(NotOptCols))
bigIter = bigIter+1;
if ((MAX_ITER >0) && (bigIter > MAX_ITER)) % set max_iter for ill-conditioned (numerically unstable) case
success = 1;, break
end
% find unconstrained LS solution for the passive set
[ Z,tempChol,tempEq ] = normalEqComb(AtA,AtB(:,NotOptCols),PassSet(:,NotOptCols));
numChol = numChol + tempChol;
numEq = numEq + tempEq;
Z(abs(Z)<1e-12) = 0; % One can uncomment this line for numerical stability.
InfeaSubSet = Z < 0;
InfeaSubCols = find(any(InfeaSubSet));
FeaSubCols = find(all(~InfeaSubSet));
if ~isempty(InfeaSubCols) % for infeasible cols
ZInfea = Z(:,InfeaSubCols);
InfeaCols = NotOptCols(InfeaSubCols);
Alpha = zeros(n,length(InfeaSubCols));, Alpha(:) = Inf;
[i,j] = find(InfeaSubSet(:,InfeaSubCols));
InfeaSubIx = sub2ind(size(Alpha),i,j);
if length(InfeaCols) == 1
InfeaIx = sub2ind([n,k],i,InfeaCols * ones(length(j),1));
else
InfeaIx = sub2ind([n,k],i,InfeaCols(j)');
end
Alpha(InfeaSubIx) = X(InfeaIx)./(X(InfeaIx)-ZInfea(InfeaSubIx));
[minVal,minIx] = min(Alpha);
Alpha(:,:) = repmat(minVal,n,1);
X(:,InfeaCols) = X(:,InfeaCols)+Alpha.*(ZInfea-X(:,InfeaCols));
IxToActive = sub2ind([n,k],minIx,InfeaCols);
X(IxToActive) = 0;
PassSet(IxToActive) = false;
end
if ~isempty(FeaSubCols) % for feasible cols
FeaCols = NotOptCols(FeaSubCols);
X(:,FeaCols) = Z(:,FeaSubCols);
Y(:,FeaCols) = AtA * X(:,FeaCols) - AtB(:,FeaCols);
Y( abs(Y)<1e-12 ) = 0; % One can uncomment this line for numerical stability.
NotOptSubSet = (Y(:,FeaCols) < 0) & ~PassSet(:,FeaCols);
NewOptCols = FeaCols(all(~NotOptSubSet));
UpdateNotOptCols = FeaCols(any(NotOptSubSet));
if ~isempty(UpdateNotOptCols)
[minVal,minIx] = min(Y(:,UpdateNotOptCols).*~PassSet(:,UpdateNotOptCols));
PassSet(sub2ind([n,k],minIx,UpdateNotOptCols)) = true;
end
NotOptSet(NewOptCols) = false;
NotOptCols = find(NotOptSet);
end
end
end
|
github | locatelf/cone-greedy-master | ncp.m | .m | cone-greedy-master/TensorFactorization/ncp.m | 16,643 | utf_8 | 688c72175fc36a416b097532b15c08b8 | % Nonnegative Tensor Factorization (Canonical Decomposition / PARAFAC)
%
% Written by Jingu Kim ([email protected])
% School of Computational Science and Engineering,
% Georgia Institute of Technology
%
% This software implements nonnegativity-constrained low-rank approximation of tensors in PARAFAC model.
% Assuming that a k-way tensor X and target rank r are given, this software seeks F1, ... , Fk
% by solving the following problem:
%
% minimize || X- sum_(j=1)^r (F1_j o F2_j o ... o Fk_j) ||_F^2 + G(F1, ... , Fk) + H(F1, ..., Fk)
% where
% G(F1, ... , Fk) = sum_(i=1)^k ( alpha_i * ||Fi||_F^2 ),
% H(F1, ... , Fk) = sum_(i=1)^k ( beta_i sum_(j=1)^n || Fi_j ||_1^2 ).
% such that
% Fi >= 0 for all i.
%
% To use this software, it is necessary to first install MATLAB Tensor Toolbox
% by Brett W. Bader and Tamara G. Kolda, available at http://csmr.ca.sandia.gov/~tgkolda/TensorToolbox/.
% The latest version that was tested with this software is Version 2.4, March 2010.
% Refer to the help manual of the toolbox for installation and basic usage.
%
% Reference:
% Jingu Kim and Haesun Park.
% Fast Nonnegative Tensor Factorization with an Active-set-like Method.
% In High-Performance Scientific Computing: Algorithms and Applications, Springer, 2012, pp. 311-326.
%
% Please send bug reports, comments, or questions to Jingu Kim.
% This code comes with no guarantee or warranty of any kind.
%
% Last modified 03/26/2012
%
% <Inputs>
% X : Input data tensor. X is a 'tensor' object of tensor toolbox.
% r : Target low-rank
%
% (Below are optional arguments: can be set by providing name-value pairs)
%
% METHOD : Algorithm for solving NMF. One of the following values:
% 'anls_bpp' 'anls_asgroup' 'hals' 'mu'
% See above paper (and references therein) for the details of these algorithms.
% Default is 'anls_bpp'.
% TOL : Stopping tolerance. Default is 1e-4. If you want to obtain a more accurate solution,
% decrease TOL and increase MAX_ITER at the same time.
% MIN_ITER : Minimum number of iterations. Default is 20.
% MAX_ITER : Maximum number of iterations. Default is 200.
% : A cell array that contains initial values for factors Fi.
% See examples to learn how to set.
% VERBOSE : 0 (default) - No debugging information is collected.
% 1 (debugging/experimental purpose) - History of computation is returned. See 'REC' variable.
% 2 (debugging/experimental purpose) - History of computation is additionally printed on screen.
% <Outputs>
% F : a 'ktensor' object that represent a factorized form of a tensor. See tensor toolbox for more info.
% iter : Number of iterations
% REC : (debugging/experimental purpose) Auxiliary information about the execution
% <Usage Examples>
% F = ncpp(X,5);
% F = ncp(X,10,'tol',1e-3);
% F = ncp(X,10,'tol',1e-3,'verbose',2);
% F = ncp(X,7,'init',Finit,'tol',1e-5,'verbose',2);
function [F,iter,REC]=ncp(X,r,varargin)
% set parameters
params = inputParser;
params.addParamValue('method' ,'anls_bpp' ,@(x) ischar(x) );
params.addParamValue('tol' ,1e-4 ,@(x) isscalar(x) & x > 0 );
params.addParamValue('stop_criterion' ,1 ,@(x) isscalar(x) & x >= 0);
params.addParamValue('min_iter' ,20 ,@(x) isscalar(x) & x > 0);
params.addParamValue('max_iter' ,200 ,@(x) isscalar(x) & x > 0 );
params.addParamValue('max_time' ,1e6 ,@(x) isscalar(x) & x > 0);
params.addParamValue('init' ,cell(0) ,@(x) iscell(x) );
params.addParamValue('verbose' ,0 ,@(x) isscalar(x) & x >= 0 );
params.addParamValue('orderWays',[]);
params.parse(varargin{:});
% copy from params object
par = params.Results;
par.nWay = ndims(X);
par.r = r;
par.size = size(X);
if isempty(par.orderWays)
par.orderWays = [1:par.nWay];
end
% set initial values
if ~isempty(par.init)
F_cell = par.init;
par.init_type = 'User provided';
par.init = cell(0);
else
Finit = cell(par.nWay,1);
for i=1:par.nWay
Finit{i}=rand(size(X,i),r);
end
F_cell = Finit;
par.init_type = 'Randomly generated';
end
% This variable is for analysis/debugging, so it does not affect the output (W,H) of this program
REC = struct([]);
tPrev = cputime;
REC(1).start_time = datestr(now);
grad = getGradient(X,F_cell,par);
ver= struct([]);
clear('init');
init.nr_X = norm(X);
init.nr_grad_all = 0;
for i=1:par.nWay
this_value = norm(grad{i},'fro');
init.(['nr_grad_',num2str(i)]) = this_value;
init.nr_grad_all = init.nr_grad_all + this_value^2;
end
init.nr_grad_all = sqrt(init.nr_grad_all);
REC(1).init = init;
initializer= str2func([par.method,'_initializer']);
iterSolver = str2func([par.method,'_iterSolver']);
iterLogger = str2func([par.method,'_iterLogger']);
% Collect initial information for analysis/debugging
if par.verbose
tTemp = cputime;
prev_F_cell = F_cell;
pGrad = getProjGradient(X,F_cell,par);
ver = prepareHIS(ver,X,F_cell,ktensor(F_cell),prev_F_cell,pGrad,init,par,0,0);
tPrev = tPrev+(cputime-tTemp);
end
% Execute initializer
[F_cell,par,val,ver] = feval(initializer,X,F_cell,par,ver);
if par.verbose & ~isempty(ver)
tTemp = cputime;
if par.verbose == 2, display(ver);, end
REC.HIS = ver;
tPrev = tPrev+(cputime-tTemp);
end
REC(1).par = par;
tTemp = cputime; display(par); tPrev = tPrev+(cputime-tTemp);
tStart = tPrev;, tTotal = 0;
if (par.stop_criterion == 2) && ~isfield(ver,'rel_Error')
F_kten = ktensor(F_cell);
ver(1).rel_Error = getRelError(X,ktensor(F_cell),init);
end
% main iterations
for iter=1:par.max_iter;
cntu = 1;
[F_cell,val] = feval(iterSolver,X,F_cell,iter,par,val);
pGrad = getProjGradient(X,F_cell,par);
F_kten = ktensor(F_cell);
prev_Ver = ver;
ver= struct([]);
if (iter >= par.min_iter)
if (par.verbose && (tTotal > par.max_time)) || (~par.verbose && ((cputime-tStart)>par.max_time))
cntu = 0;
else
switch par.stop_criterion
case 1
ver(1).SC_PGRAD = getStopCriterion(pGrad,init,par);
if (ver.SC_PGRAD<par.tol) cntu = 0; end
case 2
ver(1).rel_Error = getRelError(X,F_kten,init);
ver.SC_DIFF = abs(prev_Ver.rel_Error - ver.rel_Error);
if (ver.SC_DIFF<par.tol) cntu = 0; end
case 99
ver(1).rel_Error = getRelError(X,F_kten,init);
if ver(1).rel_Error< 1 cntu = 0; end
end
end
end
% Collect information for analysis/debugging
if par.verbose
elapsed = cputime-tPrev;
tTotal = tTotal + elapsed;
ver = prepareHIS(ver,X,F_cell,F_kten,prev_F_cell,pGrad,init,par,iter,elapsed);
ver = feval(iterLogger,ver,par,val,F_cell,prev_F_cell);
if ~isfield(ver,'SC_PGRAD')
ver.SC_PGRAD = getStopCriterion(pGrad,init,par);
end
if ~isfield(ver,'SC_DIFF')
ver.SC_DIFF = abs(prev_Ver.rel_Error - ver.rel_Error);
end
REC.HIS = saveHIS(iter+1,ver,REC.HIS);
prev_F_cell = F_cell;
if par.verbose == 2, display(ver);, end
tPrev = cputime;
end
if cntu==0, break; end
end
F = arrange(F_kten);
% print finishing information
final.iterations = iter;
if par.verbose
final.elapsed_sec = tTotal;
else
final.elapsed_sec = cputime-tStart;
end
for i=1:par.nWay
final.(['f_density_',num2str(i)]) = length(find(F.U{i}>0))/(size(F.U{i},1)*size(F.U{i},2));
end
final.rel_Error = getRelError(X,F_kten,init);
REC.final = final;
REC.finish_time = datestr(now);
display(final);
end
%----------------------------------------------------------------------------------------------
% Utility Functions
%----------------------------------------------------------------------------------------------
function ver = prepareHIS(ver,X,F,F_kten,prev_F,pGrad,init,par,iter,elapsed)
ver(1).iter = iter;
ver.elapsed = elapsed;
if ~isfield(ver,'rel_Error')
ver.rel_Error = getRelError(X,F_kten,init);
end
for i=1:par.nWay
ver.(['f_change_',num2str(i)]) = norm(F{i}-prev_F{i});
ver.(['f_density_',num2str(i)]) = length(find(F{i}>0))/(size(F{i},1)*size(F{i},2));
ver.(['rel_nr_pgrad_',num2str(i)]) = norm(pGrad{i},'fro')/init.(['nr_grad_',num2str(i)]);
end
end
function HIS = saveHIS(idx,ver,HIS)
fldnames = fieldnames(ver);
for i=1:length(fldnames)
flname = fldnames{i};
HIS.(flname)(idx) = ver.(flname);
end
end
function rel_Error = getRelError(X,F_kten,init)
rel_Error = sqrt(max(init.nr_X^2 + norm(F_kten)^2 - 2 * innerprod(X,F_kten),0))/init.nr_X;
end
function [grad] = getGradient(X,F,par)
grad = cell(par.nWay,1);
for k=1:par.nWay
ways = 1:par.nWay;
ways(k)='';
XF = mttkrp(X,F,k);
% Compute the inner-product matrix
FF = ones(par.r,par.r);
for i = ways
FF = FF .* (F{i}'*F{i});
end
grad{k} = F{k} * FF - XF;
end
end
function [pGrad] = getProjGradient(X,F,par)
pGrad = cell(par.nWay,1);
for k=1:par.nWay
ways = 1:par.nWay;
ways(k)='';
XF = mttkrp(X,F,k);
% Compute the inner-product matrix
FF = ones(par.r,par.r);
for i = ways
FF = FF .* (F{i}'*F{i});
end
grad = F{k} * FF - XF;
pGrad{k} = grad(grad<0|F{k}>0);
end
end
function retVal = getStopCriterion(pGrad,init,par)
retVal = 0;
for i=1:par.nWay
retVal = retVal + (norm(pGrad{i},'fro'))^2;
end
retVal = sqrt(retVal)/init.nr_grad_all;
end
% 'anls_bpp' : ANLS with Block Principal Pivoting Method
% Reference:
% Jingu Kim and Haesun Park.
% Fast Nonnegative Tensor Factorization with an Active-set-like Method.
% In High-Performance Scientific Computing: Algorithms and Applications,
% Springer, 2012, pp. 311-326.
function [F,par,val,ver] = anls_bpp_initializer(X,F,par,ver)
F{par.orderWays(1)} = zeros(size(F{par.orderWays(1)}));
for k=1:par.nWay
ver(1).(['turnZr_',num2str(k)]) = 0;
ver.(['turnNz_',num2str(k)]) = 0;
ver.(['numChol_',num2str(k)]) = 0;
ver.(['numEq_',num2str(k)]) = 0;
ver.(['suc_',num2str(k)]) = 0;
end
val.FF = cell(par.nWay,1);
for k=1:par.nWay
val.FF{k} = F{k}'*F{k};
end
end
function [F,val] = anls_bpp_iterSolver(X,F,iter,par,val)
% solve NNLS problems for each factor
for k=1:par.nWay
curWay = par.orderWays(k);
ways = 1:par.nWay;
ways(curWay)='';
XF = mttkrp(X,F,curWay);
% Compute the inner-product matrix
FF = ones(par.r,par.r);
for i = ways
FF = FF .* val.FF{i};
end
[Fthis,temp,sucThis,numCholThis,numEqThis] = nnlsm_blockpivot(FF,XF',1,F{curWay}');
F{curWay}=Fthis';
val(1).FF{curWay} = F{curWay}'*F{curWay};
val.(['numChol_',num2str(k)]) = numCholThis;
val.(['numEq_',num2str(k)]) = numEqThis;
val.(['suc_',num2str(k)]) = sucThis;
end
end
function [ver] = anls_bpp_iterLogger(ver,par,val,F,prev_F)
for k=1:par.nWay
ver.(['turnZr_',num2str(k)]) = length(find( (prev_F{k}>0) & (F{k}==0) ))/(size(F{k},1)*size(F{k},2));
ver.(['turnNz_',num2str(k)]) = length(find( (prev_F{k}==0) & (F{k}>0) ))/(size(F{k},1)*size(F{k},2));
ver.(['numChol_',num2str(k)]) = val.(['numChol_',num2str(k)]);
ver.(['numEq_',num2str(k)]) = val.(['numEq_',num2str(k)]);
ver.(['suc_',num2str(k)]) = val.(['suc_',num2str(k)]);
end
end
% 'anls_asgroup' : ANLS with Active Set Method and Column Grouping
% Reference:
% Kim, H. and Park, H. and Elden, L.
% Non-negative Tensor Factorization Based on Alternating Large-scale Non-negativity-constrained Least Squares.
% In Proceedings of IEEE 7th International Conference on Bioinformatics and Bioengineering
% (BIBE07), 2, pp. 1147-1151,2007
function [F,par,val,ver] = anls_asgroup_initializer(X,F,par,ver)
[F,par,val,ver] = anls_bpp_initializer(X,F,par,ver);
end
function [F,val] = anls_asgroup_iterSolver(X,F,iter,par,val)
% solve NNLS problems for each factor
for k=1:par.nWay
curWay = par.orderWays(k);
ways = 1:par.nWay;
ways(curWay)='';
XF = mttkrp(X,F,curWay);
% Compute the inner-product matrix
FF = ones(par.r,par.r);
for i = ways
FF = FF .* val.FF{i};
end
ow = 0;
[Fthis,temp,sucThis,numCholThis,numEqThis] = nnlsm_activeset(FF,XF',ow,1,F{curWay}');
F{curWay}=Fthis';
val(1).FF{curWay} = F{curWay}'*F{curWay};
val.(['numChol_',num2str(k)]) = numCholThis;
val.(['numEq_',num2str(k)]) = numEqThis;
val.(['suc_',num2str(k)]) = sucThis;
end
end
function [ver] = anls_asgroup_iterLogger(ver,par,val,F,prev_F)
ver = anls_bpp_iterLogger(ver,par,val,F,prev_F);
end
% 'mu' : Multiplicative Updating Method
% Reference:
% M. Welling and M. Weber.
% Positive tensor factorization.
% Pattern Recognition Letters, 22(12), pp. 1255???1261, 2001.
function [F,par,val,ver] = mu_initializer(X,F,par,ver)
val.FF = cell(par.nWay,1);
for k=1:par.nWay
val.FF{k} = F{k}'*F{k};
end
end
function [F,val] = mu_iterSolver(X,F,iter,par,val)
epsilon = 1e-16;
for k=1:par.nWay
curWay = par.orderWays(k);
ways = 1:par.nWay;
ways(curWay)='';
% Calculate Fnew = X_(n) * khatrirao(all U except n, 'r').
XF = mttkrp(X,F,curWay);
% Compute the inner-product matrix
FF = ones(par.r,par.r);
for i = ways
FF = FF .* val.FF{i};
end
F{curWay} = F{curWay}.*XF./(F{curWay}*FF+epsilon);
val(1).FF{curWay} = F{curWay}'*F{curWay};
end
end
function [ver] = mu_iterLogger(ver,par,val,F,prev_F)
end
% 'hals' : Hierarchical Alternating Least Squares Method
% Reference:
% Cichocki, A. and Phan, A.H.
% Fast local algorithms for large scale nonnegative matrix and tensor factorizations.
% IEICE Trans. Fundam. Electron. Commun. Comput. Sci. E92-A(3), 708???721 (2009)
function [F,par,val,ver] = hals_initializer(X,F,par,ver)
% normalize
d = ones(1,par.r);
for k=1:par.nWay-1
curWay = par.orderWays(k);
norm2 = sqrt(sum(F{curWay}.^2,1));
F{curWay} = F{curWay}./repmat(norm2,size(F{curWay},1),1);
d = d .* norm2;
end
curWay = par.orderWays(end);
F{curWay} = F{curWay}.*repmat(d,size(F{curWay},1),1);
val.FF = cell(par.nWay,1);
for k=1:par.nWay
val.FF{k} = F{k}'*F{k};
end
end
function [F,val] = hals_iterSolver(X,F,iter,par,val)
epsilon = 1e-16;
d = sum(F{par.orderWays(end)}.^2,1);
for k=1:par.nWay
curWay = par.orderWays(k);
ways = 1:par.nWay;
ways(curWay)='';
% Calculate Fnew = X_(n) * khatrirao(all U except n, 'r').
XF = mttkrp(X,F,curWay);
% Compute the inner-product matrix
FF = ones(par.r,par.r);
for i = ways
FF = FF .* val.FF{i};
end
if k<par.nWay
for j = 1:par.r
F{curWay}(:,j) = max( d(j) * F{curWay}(:,j) + XF(:,j) - F{curWay} * FF(:,j),epsilon);
F{curWay}(:,j) = F{curWay}(:,j) ./ norm(F{curWay}(:,j));
end
else
for j = 1:par.r
F{curWay}(:,j) = max( F{curWay}(:,j) + XF(:,j) - F{curWay} * FF(:,j),epsilon);
end
end
val(1).FF{curWay} = F{curWay}'*F{curWay};
end
end
function [ver] = hals_iterLogger(ver,par,val,F,prev_F)
end
|
github | locatelf/cone-greedy-master | lsqnonnegMy.m | .m | cone-greedy-master/NNMP/lsqnonnegMy.m | 8,296 | utf_8 | fda5216b3d7550977d2efa475e8ca118 | function [x,allres,resnorm,resid,exitflag,output,lambda] = lsqnonnegMy(C,d,options,varargin)
%LSQNONNEG Linear least squares with nonnegativity constraints.
% X = LSQNONNEG(C,d) returns the vector X that minimizes NORM(d-C*X)
% subject to X >= 0. C and d must be real.
%
% X = LSQNONNEG(C,d,OPTIONS) minimizes with the default optimization
% parameters replaced by values in the structure OPTIONS, an argument
% created with the OPTIMSET function. See OPTIMSET for details. Used
% options are Display and TolX. (A default tolerance TolX of
% 10*MAX(SIZE(C))*NORM(C,1)*EPS is used.)
%
% X = LSQNONNEG(PROBLEM) finds the minimum for PROBLEM. PROBLEM is a
% structure with the matrix 'C' in PROBLEM.C, the vector 'd' in
% PROBLEM.d, the options structure in PROBLEM.options, and solver name
% 'lsqnonneg' in PROBLEM.solver.
%
% [X,RESNORM] = LSQNONNEG(...) also returns the value of the squared 2-norm of
% the residual: norm(d-C*X)^2.
%
% [X,RESNORM,RESIDUAL] = LSQNONNEG(...) also returns the value of the
% residual: d-C*X.
%
% [X,RESNORM,RESIDUAL,EXITFLAG] = LSQNONNEG(...) returns an EXITFLAG that
% describes the exit condition. Possible values of EXITFLAG and the
% corresponding exit conditions are
%
% 1 LSQNONNEG converged with a solution X.
% 0 Iteration count was exceeded. Increasing the tolerance
% (OPTIONS.TolX) may lead to a solution.
%
% [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT] = LSQNONNEG(...) returns a structure
% OUTPUT with the number of steps taken in OUTPUT.iterations, the type of
% algorithm used in OUTPUT.algorithm, and the exit message in OUTPUT.message.
%
% [X,RESNORM,RESIDUAL,EXITFLAG,OUTPUT,LAMBDA] = LSQNONNEG(...) returns
% the dual vector LAMBDA where LAMBDA(i) <= 0 when X(i) is (approximately) 0
% and LAMBDA(i) is (approximately) 0 when X(i) > 0.
%
% See also LSCOV, SLASH.
% Copyright 1984-2016 The MathWorks, Inc.
% Reference:
% Lawson and Hanson, "Solving Least Squares Problems", Prentice-Hall, 1974.
% Check if more inputs have been passed. In that case error.
if nargin > 4
error('MATLAB:lsqnonneg:TooManyInputs',...
getString(message('MATLAB:optimfun:lsqnonneg:TooManyInputs')));
end
defaultopt = struct('Display','notify','TolX','10*eps*norm(C,1)*length(C)');
% If just 'defaults' passed in, return the default options in X
if nargin == 1 && nargout <= 1 && isequal(C,'defaults')
x = defaultopt;
return
end
if nargin < 3
options = [];
end
if nargin == 1
% Detect problem structure input
if isa(C,'struct')
[C,d,options] = separateOptimStruct(C);
else % Single input and non-structure.
error('MATLAB:lsqnonneg:InputArg',...
getString(message('MATLAB:optimfun:lsqnonneg:InputArg')));
end
end
if nargin == 0
error('MATLAB:lsqnonneg:NotEnoughInputs',...
getString(message('MATLAB:optimfun:lsqnonneg:NotEnoughInputs')));
end
if ~isreal(C) || ~isreal(d)
error('MATLAB:lsqnonneg:ComplexCorD',...
getString(message('MATLAB:optimfun:lsqnonneg:ComplexCorD')));
end
% Check for non-double inputs
if ~isa(C,'double') || ~isa(d,'double')
error('MATLAB:lsqnonneg:NonDoubleInput',...
getString(message('MATLAB:optimfun:lsqnonneg:NonDoubleInput')));
end
% Check if options was created with optimoptions
if ~isempty(options) && isa(options,'optim.options.SolverOptions')
error('MATLAB:lsqnonneg:ArgNotStruct',...
getString(message('MATLAB:optimfun:commonMessages:ArgNotStruct', 3)));
end
% Check for deprecated syntax
options = deprecateX0(options,nargin,varargin{:});
printtype = optimget(options,'Display',defaultopt,'fast');
tol = optimget(options,'TolX',defaultopt,'fast');
% In case the defaults were gathered from calling: optimset('lsqnonneg'):
if ischar(tol)
if strcmpi(tol,'10*eps*norm(c,1)*length(c)')
tol = 10*eps*norm(C,1)*length(C);
else
error('MATLAB:lsqnonneg:OptTolXNotPosScalar',...
getString(message('MATLAB:optimfun:lsqnonneg:OptTolXNotPosScalar')));
end
end
switch printtype
case {'notify','notify-detailed'}
verbosity = 1;
case {'none','off'}
verbosity = 0;
case {'iter','iter-detailed'}
warning('MATLAB:lsqnonneg:InvalidDisplayValueIter',...
getString(message('MATLAB:optimfun:lsqnonneg:InvalidDisplayValueIter')));
verbosity = 3;
case {'final','final-detailed'}
verbosity = 2;
otherwise
error('MATLAB:lsqnonneg:InvalidOptParamDisplay',...
getString(message('MATLAB:optimfun:lsqnonneg:InvalidOptParamDisplay')));
end
n = size(C,2);
% Initialize vector of n zeros and Infs (to be used later)
nZeros = zeros(n,1);
wz = nZeros;
% Initialize set of non-active columns to null
P = false(n,1);
% Initialize set of active columns to all and the initial point to zeros
Z = true(n,1);
x = nZeros;
resid = d - C*x;
w = C'*resid;
% Set up iteration criterion
outeriter = 0;
iter = 0;
itmax = 50;%3*n;
exitflag = 1;
allres = zeros(itmax,1);
% Outer loop to put variables into set to hold positive coefficients
while any(Z) && any(w(Z) > tol)
outeriter = outeriter + 1;
% Reset intermediate solution z
z = nZeros;
% Create wz, a Lagrange multiplier vector of variables in the zero set.
% wz must have the same size as w to preserve the correct indices, so
% set multipliers to -Inf for variables outside of the zero set.
wz(P) = -Inf;
wz(Z) = w(Z);
% Find variable with largest Lagrange multiplier
[~,t] = max(wz);
% Move variable t from zero set to positive set
P(t) = true;
Z(t) = false;
% Compute intermediate solution using only variables in positive set
z(P) = C(:,P)\d;
% inner loop to remove elements from the positive set which no longer belong
while any(z(P) <= 0)
iter = iter + 1;
if iter > itmax
msg = getString(message('MATLAB:optimfun:lsqnonneg:IterationCountExceeded'));
if verbosity
disp(msg)
end
exitflag = 0;
output.iterations = outeriter;
output.message = msg;
output.algorithm = 'active-set';
resnorm = sum(resid.*resid);
x = z;
lambda = w;
return
end
% Find indices where intermediate solution z is approximately negative
Q = (z <= 0) & P;
% Choose new x subject to keeping new x nonnegative
alpha = min(x(Q)./(x(Q) - z(Q)));
x = x + alpha*(z - x);
% Reset Z and P given intermediate values of x
Z = ((abs(x) < tol) & P) | Z;
P = ~Z;
z = nZeros; % Reset z
z(P) = C(:,P)\d; % Re-solve for z
end
x = z;
resid = d - C*x;
allres(outeriter) = norm(resid)^2;
w = C'*resid;
end
lambda = w;
resnorm = resid'*resid;
output.iterations = outeriter;
output.algorithm = 'active-set';
% msg = getString(message('MATLAB:optimfun:lsqnonneg:OptimizationTerminated'));
% if verbosity > 1
% disp(msg)
% end
%output.message = msg;
allres(outeriter+1:end)= 10000000000000000;
er_pre = 1000000000;
for i = 1:itmax
allres(i) = min(allres(i),er_pre);
er_pre = allres(i);
end
%--------------------------------------------------------------------------
function options = deprecateX0(options,numInputs,varargin)
% Code to check if user has passed in x0. If so, ignore it and warn of its
% deprecation. Also check whether the options have been passed in either
% the 3rd or 4th input.
if numInputs == 4
% 4 inputs given; the 3rd (variable name "options") will be interpreted
% as x0, and the 4th as options
if ~isempty(options)
% x0 is non-empty
warning('MATLAB:lsqnonneg:ignoringX0',...
getString(message('MATLAB:optimfun:lsqnonneg:ignoringX0')));
end
% Take the 4th argument as the options
options = varargin{1};
elseif numInputs == 3
% Check if a non-empty or non-struct has been passed in for options
% If so, assume that it's an attempt to pass x0
if ~isstruct(options) && ~isempty(options)
warning('MATLAB:lsqnonneg:ignoringX0',...
getString(message('MATLAB:optimfun:lsqnonneg:ignoringX0')));
% No options passed, set to empty
options = [];
end
end
|
github | locatelf/cone-greedy-master | experiment_EEAs.m | .m | cone-greedy-master/HyperspectralImaging/experiment_EEAs.m | 1,254 | utf_8 | 6824855f221c01fc60b03f94ac1d27fd | % Running the algorithm on data set M
function [Kall, Hall, resultsErr, Hall2, resultsErr2, nEEAs,resultsErr3,resultsErr4,resultsErr5] = experiment_EEAs( M , r )
% 2. Running the EEAs on the full and subsampled data set
maxitNNLS = 10;
nEEAs{1} = 'SPA ';
nEEAs{2} = 'VCA ';
nEEAs{3} = 'XRAY ';
nEEAs{4} = 'H2NMF';
nEEAs{5} = 'SNPA ';
for algo = 1 : 5
D = M; % full data set
fprintf([nEEAs{algo}, ' on the full data set...']);
%% Normalization to apply EEAs that need it (SPA, VCA, H2NMF, SNPA)
e = cputime;
K = EEAs(D,r,algo); % extract endmembers from 'dictionary'
Kall{algo} = K;
% Error
[H, err] = plotnnlsHALSupdt(M,D(:,K),[],maxitNNLS,algo); % optimal weights
[H2, Hslow,HPW,HA] = NNMPmatrix(M,D(:,K),maxitNNLS,algo,err,nEEAs{algo});
Hall{algo} = H;
Hall2{algo} = H2;
resultsErr(algo) = 100*norm(M - D(:,K)*H,'fro')/norm(M,'fro');
resultsErr2(algo) = 100*norm(M - D(:,K)*H2,'fro')/norm(M,'fro');
resultsErr3(algo) = 100*norm(M - Hslow,'fro')/norm(M,'fro');
resultsErr4(algo) = 100*norm(M - D(:,K)*HPW,'fro')/norm(M,'fro');
resultsErr5(algo) = 100*norm(M - D(:,K)*HA,'fro')/norm(M,'fro');
fprintf(' done.\n');
end
|
github | locatelf/cone-greedy-master | fquad.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/fquad.m | 1,774 | utf_8 | 85e40c6d6d0a040702758d817f0a5008 | % Select treshold to split the entries of x into two subsets
%
% See Section 3.2 in
% Gillis, Kuang, Park, `Hierarchical Clustering of Hyperspectral Images
% using Rank-Two Nonnegative Matrix Factorization', arXiv.
function [thres,delta,fobj] = fquad(x,s);
if nargin == 1
s = 0.01; % grid for the values of delta
end
[fdel,fdelp,delta,finter,gs] = fdelta(x,s);
% fdel is the percentage of values smaller than delta
% finter is the number of points in a small interval around delta
warning('off');
fobj = -log( fdel.* (1-fdel) ) + exp(finter);
% Can potentially use other objectives:
%fobj = -log( fdel.* (1-fdel) ) + 2.^(finter);
%fobj = ( 2*(fdel - 0.5) ).^2 + finter.^2;
%fobj = -log( fdel.* (1-fdel) ) + finter.^2;
%fobj = ( 2*(fdel - 0.5) ).^2 + finter.^2;
warning('on');
[a,b] = min(fobj);
thres = delta(b);
% Evaluate the function fdel = sum( x_i <= delta)/n and its derivate
% for all delta in interval [0,1] with step s
function [fdel,fdelp,delta,finter,gs] = fdelta(x,s);
n = length(x);
if nargin == 1
s = 0.01;
end
delta = 0:s:1;
lD = length(delta);
gs = 0.05; % Other values could be used, in [0,0.5]
for i = 1 : lD
fdel(i) = sum(x <= delta(i))/n;
if i == 2 % use only next point to evaluate fdelp(1)
fdelp(1) = (fdel(2)-fdel(1))/s;
elseif i >= 2 % use next and previous point to evaluate fdelp(i)
fdelp(i-1) = (fdel(i)-fdel(i-2))/2/s;
if i == lD % use only previous point to evaluate fdelp(lD)
fdelp(lD) = (fdel(lD)-fdel(lD-1))/s;
end
end
deltahigh = min(1,delta(i) + gs);
deltalow = max(0,delta(i) - gs);
finter(i) = ( sum(x <= deltahigh) - sum(x < deltalow) )/n/(deltahigh-deltalow) ;
end |
github | locatelf/cone-greedy-master | anls_entry_rank2_precompute_opt.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/anls_entry_rank2_precompute_opt.m | 1,376 | utf_8 | 12fa56b139f94a061bb74c871176ec31 | % Solve min_H ||M - WH'||_2 s.t. H >= 0
%
% where left = W^TW and right = M^TW
%
% See Kuang, Park, `Fast Rank-2 Nonnegative Matrix Factorization
% for Hierarchical Document Clustering', KDD '13.
%
% See also Algorithm 4 in
% Gillis, Kuang, Park, `Hierarchical Clustering of Hyperspectral Images
% using Rank-Two Nonnegative Matrix Factorization', arXiv.
%
% ****** Input ******
% left : 2-by-2 matrix (or possibly 1-by-1)
% right : n-by-2 matrix (or possibly n-by-1)
%
% ****** Output ******
% H : nonnegative n-by-2 matrix, solution to KKT equations
function H = anls_entry_rank2_precompute_opt(left, right)
warning('off');
if length(left) == 1
H = max(0,right/left);
else
H = (left \ right')';
use_either = ~all(H>=0, 2);
H(use_either, :) = anls_entry_rank2_binary(left, right(use_either,:));
H = H';
end
warning('on');
% Case where one entry in each column of H has to be equal to zero
function solve_either = anls_entry_rank2_binary(left, right)
n = size(right, 1);
solve_either = zeros(n, 2);
solve_either(:, 1) = max(0, right(:, 1) ./ left(1,1));
solve_either(:, 2) = max(0, right(:, 2) ./ left(2,2));
cosine_either = solve_either.* repmat([sqrt(left(1,1)), sqrt(left(2,2))],n,1);
choose_first = (cosine_either(:, 1) >= cosine_either(:, 2));
solve_either(choose_first, 2) = 0;
solve_either(~choose_first, 1) = 0; |
github | locatelf/cone-greedy-master | hierclust2nmf.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/hierclust2nmf.m | 9,170 | utf_8 | 2ed0455c900bc24ed801586e0ea7ebd8 | % Hierarchical custering based on rank-two nonnegative matrix factorization
%
% Given a data matrix M (m-by-n) representing n data points in an
% m-dimensional space, this algorithm computes a set of clusters obtained
% using the hierarchical rank-two NMF method described in
%
% Gillis, Kuang, Park, `Hierarchical Clustering of Hyperspectral Images
% using Rank-Two Nonnegative Matrix Factorization', arXiv.
%
%
% ****** Input ******
% M : m-by-n data matrix (or a H-by-L-by-m tensor)
% n (=HL) is the number of pixels, m the number of wavelengths
% r : number of clusters to generate, OR
% for r = []: the user is asked how many clusters she/he wants,
% OR she/he can choose the leaf node to be split based
% on the displayed current clusters. (default)
% algo : algorithm used to split the clusters
% 1. rank-two NMF (default)
% 2. k-means
% 3. spherical k-means
%
% sol : it can be used to resume a previous solution computed by
% hierclust2nmf (this allows to go deeper in the tree and
% generate more clusters from a previous solution).
% ---> Optional.
%
% displ: display the evolution of the hierarhical procedure
%
% ****** Output ******
% IDX : an indicator vector in {1,2,...,r}^m, identifying r clusters
% C, J : The columns of C are the spectral signatures of endmembers,
% that is, the cluster centroids.
% J is the index set locating the endmembers in the data set:
% C = M(:,J) (for matrix format).
% sol : contains the tree structure
function [IDX, C, J, sol] = hierclust2nmf(M,r,algo,sol,displ)
if nargin <= 4
displ = 1;
end
[m,n] = size(M);
if min(M(:)) < 0
warning('The input matrix contains negative entries which have been set to zero');
M = max(M,0);
end
% The input is a tensor --> matrix format
if length(size(M)) == 3
[H,L,m] = size(M);
n = H*L;
A = zeros(m,n);
for i = 1 : m
A(i,:) = reshape(M(:,:,i),1,n);
end
clear M; M = A;
end
if nargin == 1 || isempty(r)
if ~exist('algo') || isempty(algo)
algo = 1;
end
y = 1; n = 0;
b = input('Do you want to visually choose the cluster to be split? (y/n) \n');
[m,n] = size(M);
if b == 'y' || b == 1
if ~exist('L')
H = input('What is the number of pixels in each row of your hyperspectral image? \n');
L = n/H;
end
r = Inf;
manualsplit = 1; % Split according to user feedback
elseif b == 'n' || b == 0
r = input('How many clusters do you want to generate? ');
manualsplit = 0;
else
error('Enter ''y'' or ''n''.')
end
else
manualsplit = 0; % Split according to the proposed criterion
if nargin == 2
algo = 1;
end
end
if nargin < 4 || isempty(sol)
% Intialization of the tree structure
sol.K{1} = (1:n)'; % All clusters; the first node contains all pixels
sol.allnodes = 1; % nodes numbering
sol.maxnode = 1; % Last leaf node added
sol.parents = [0 0]; % Parents of leaf nodes
sol.childs = []; % Child(i,:) = child of node i
sol.leafnodes = 1; % Current clustering: set of leaf nodes corresponding to selected clusters
sol.e = -1; % Criterion to decide which leafnode to split
sol.U(:,1) = ones(m,1); % Centroids
sol.Ke(1) = 1; % index centroid: index of the endmember
sol.count = 1; % Number of clusters generated so far
sol.firstsv = 0;
end
if displ == 1
fprintf('Hierarchical clustering started... \n');
end
while sol.count < r
%***************************************************************
% Update: split leaf nodes added at previous iteration
%***************************************************************
for k = 1 : length(sol.leafnodes)
% Update leaf nodes not yet split
if sol.e(sol.leafnodes(k)) == -1 && length(sol.K{sol.leafnodes(k)}) > 1
% Update leaf node ind(k) by splitting it and adding its child nodes
[Kc,Uc,sc] = splitclust(M(:,sol.K{sol.leafnodes(k)}),algo);
if ~isempty(Kc{2}) % the second cluster has to be non-empty: this can occur for a rank-one matrix.
% Add the two leaf nodes, child of nodes(sol.leafnodes(k))
sol.allnodes = [sol.allnodes; sol.maxnode+1; sol.maxnode+2];
sol.parents(sol.maxnode+1,:) = [sol.leafnodes(k) 0];
sol.parents(sol.maxnode+2,:) = [sol.leafnodes(k) 0];
sol.childs(sol.leafnodes(k), : ) = [sol.maxnode+1 sol.maxnode+2];
sol.childs(sol.maxnode+1 , :) = 0;
sol.childs(sol.maxnode+2 , :) = 0;
sol.K{sol.maxnode+1} = sol.K{sol.leafnodes(k)}(Kc{1});
sol.K{sol.maxnode+2} = sol.K{sol.leafnodes(k)}(Kc{2});
[sol.U(:,sol.maxnode+1),sol.firstsv(sol.maxnode+1), sol.Ke(sol.maxnode+1)] = reprvec(M(:,sol.K{sol.maxnode+1}));
[sol.U(:,sol.maxnode+2),sol.firstsv(sol.maxnode+2), sol.Ke(sol.maxnode+2)] = reprvec(M(:,sol.K{sol.maxnode+2}));
% Update criterion to choose next cluster to split
sol.e([sol.maxnode+1 sol.maxnode+2]) = -1;
% Compte the reduction in the error if kth cluster is split
sol.e(sol.leafnodes(k)) = sol.firstsv(sol.maxnode+1)^2 + sol.firstsv(sol.maxnode+2)^2 - sol.firstsv(sol.leafnodes(k))^2;
sol.maxnode = sol.maxnode+2;
end
end
end
%***************************************************************
% Choose the cluster to split, split it, and update leaf nodes
%***************************************************************
if sol.count == 1 % Only one leaf node, the root node: split it.
b = 1;
elseif manualsplit == 0 % Split the node maximizing the critetion e
[a,b] = max(sol.e(sol.leafnodes));
elseif manualsplit == 1 % Split w.r.t. user visual feedback
[a,b] = max(sol.e(sol.leafnodes));
close all; a = affclust(sol.K(sol.leafnodes),H,L);
fprintf('Which cluster do you want to split (between 1 and %2.0f)? \n', sol.count);
fprintf('Suggested cluster to split w.r.t. error: %2.0f \n', b);
fprintf('Type 0 if you want to stop. \n');
fprintf('Type -1 if you want to fuse two clusters. \n');
b = input('Choice: ');
if b == 0
IDX = clu2vec(sol.K(sol.leafnodes));
for k = 1 : length(sol.leafnodes)
J(k) = sol.K{sol.leafnodes(k)}(sol.Ke(sol.leafnodes(k)));
end
C = sol.U(:,sol.leafnodes);
disp('*************************************************************');
return;
end
end
if b == -1
fprintf('Which clusters do you want to fuse? (between 1 and %2.0f)? \n', sol.count);
b1 = input('Choice 1: ');
b2 = input('Choice 2: ');
b = sort([b1 b2]);
% Create a new node, child of the two fused ones, and update its entries
sol.maxnode = sol.maxnode+1;
sol.allnodes = [sol.allnodes; sol.maxnode+1];
sol.parents(sol.maxnode+1,:) = [sol.leafnodes(b(1)) sol.leafnodes(b(2))];
sol.childs(sol.maxnode+1,:) = 0;
sol.K{sol.maxnode+1} = [sol.K{sol.leafnodes(b(1))}; sol.K{sol.leafnodes(b(2))}];
[u1,s1,ke1] = reprvec(M(:,sol.K{sol.maxnode+1}));
sol.firstsv(sol.maxnode+1) = s1;
sol.U(:,sol.maxnode+1) = u1;
sol.Ke(:,sol.maxnode+1) = ke1;
sol.e([sol.maxnode+1]) = -1;
sol.e2([sol.maxnode+1]) = -1;
% Update leaf nodes: delete two fused and add the new one
sol.leafnodes = sol.leafnodes([1:b(1)-1 b(1)+1:b(2)-1 b(2)+1:end]);
sol.leafnodes = [sol.leafnodes; sol.maxnode+1];
% Update counters
sol.maxnode = sol.maxnode+1;
sol.count = sol.count-1;
else
sol.leafnodes = [sol.leafnodes; sol.childs(sol.leafnodes(b),:)']; % Add its two children
sol.leafnodes = sol.leafnodes([1:b-1 b+1:end]); % Remove bth leaf node
if manualsplit == 0 && displ == 1 % Dispay progress in tree exploration
if mod(sol.count,10) == 0,
fprintf('%1.0f...\n',sol.count);
else
fprintf('%1.0f...',sol.count);
end
if sol.count == r-1,
fprintf('Done. \n',sol.count);
end
elseif manualsplit == 1
disp('*************************************************************');
end
sol.count = sol.count+1;
end
end
IDX = clu2vec(sol.K(sol.leafnodes));
for k = 1 : length(sol.leafnodes)
J(k) = sol.K{sol.leafnodes(k)}(sol.Ke(sol.leafnodes(k)));
end
C = sol.U(:,sol.leafnodes); |
github | locatelf/cone-greedy-master | fastsvds.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/fastsvds.m | 683 | utf_8 | b81c39bffb76f2522e20bd1c42ae60b0 | % "Fast" but less accurate SVD by computing the SVD of MM^T or M^TM
% ***IF*** one of the dimensions of M is much smaller than the other.
% Note. This is numerically less stable, but useful for large hyperspectral
% images.
function [u,s,v] = fastsvds(M,r);
[m,n] = size(M);
rationmn = 10; % Parameter, should be >= 1
if m < rationmn*n
MMt = M*M';
[u,s,v] = svds(MMt,r);
v = M'*u;
v = v.*repmat( (sum(v.^2)+1e-16).^(-0.5),n,1);
s = sqrt(s);
elseif n < rationmn*m
MtM = M'*M;
[u,s,v] = svds(MtM,r);
u = M*v;
u = u.*repmat( (sum(u.^2)+1e-16).^(-0.5),m,1);
s = sqrt(s);
else
[u,s,v] = svds(M,r);
end |
github | locatelf/cone-greedy-master | splitclust.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/splitclust.m | 1,644 | utf_8 | 3db01b4e0e55f4537496b1675c54445a | % Given a matrix M, split its columns into two subsets
%
% See Section 3 in
%
% Gillis, Kuang, Park, `Hierarchical Clustering of Hyperspectral Images
% using Rank-Two Nonnegative Matrix Factorization', arXiv.
%
%
% ****** Input ******
% M : m-by-n data matrix (or a H-by-L-by-m tensor)
% algo : algorithm used to split the clusters
% 1. rank-two NMF (default)
% 2. k-means
% 3. spherical k-means
%
% ****** Output ******
% K : two clusters
% U : corresponding centroids
% s : first singular value of M
function [K,U,s] = splitclust(M,algo);
if nargin == 1
algo = 1;
end
if algo == 1 % rank-2 NMF
[U,V,s] = rank2nmf(M);
% Normalize columns of V to sum to one
V = V.*repmat( (sum(V)+1e-16).^(-1), 2,1);
x = V(1,:)';
% Compute treshold to split cluster
threshold = fquad(x);
K{1} = find(x >= threshold);
K{2} = find(x < threshold);
elseif algo == 2 % k-means
[u,s,v] = fastsvds(M,2); % Initialization: SVD+SPA
Kf = FastSepNMF(s*v',2,0);
U0 = u*s*v(Kf,:)';
[IDX,U] = kmeans(M', 2, 'EmptyAction','singleton','Start',U0');
U = U';
K{1} = find(IDX==1);
K{2} = find(IDX==2);
s = s(1);
elseif algo == 3 % shperical k-means
[u,s,v] = fastsvds(M,2); % Initialization: SVD+SPA
Kf = FastSepNMF(s*v',2,0);
U0 = u*s*v(Kf,:)';
[IDX,U] = spkmeans(M, U0);
% or (?)
%[IDX,U] = kmeans(M', 2, 'EmptyAction','singleton','Start',U0','Distance','cosine');
K{1} = find(IDX==1);
K{2} = find(IDX==2);
s = s(1);
end |
github | locatelf/cone-greedy-master | vectoind.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/vectoind.m | 220 | utf_8 | 8820e9734a50ee8f7795f604051c3e34 | % From cluster indicator vector to indicator matrix
function V = vectoind(IDX,r)
m = length(IDX);
if nargin == 1
r = max(IDX(:));
end
V = zeros(m,r);
for i = 1 : r
V(find(IDX==i),i) = 1;
end |
github | locatelf/cone-greedy-master | rank2nmf.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/rank2nmf.m | 945 | utf_8 | 22891abe4abe34be96416d412279a329 | % Given a data matrix M (m-by-n), computes a rank-two NMF of M.
%
% See Algorithm 3 in
%
% Gillis, Kuang, Park, `Hierarchical Clustering of Hyperspectral Images
% using Rank-Two Nonnegative Matrix Factorization', arXiv.
%
% ****** Input ******
% M : a nonnegative m-by-n data matrix
%
% ****** Output ******
% (U,V) : a rank-two NMF of M
% s1 : first singular value of M
function [U,V,s1] = rank2nmf(M)
[m,n] = size(M);
% Best rank-two approximation of M
if min(m,n) == 1
[U,S,V] = fastsvds(M,1);
U = abs(U); V = abs(V); s1 = S;
else
[u,s,v] = fastsvds(M,2);
s1 = s(1);
K = FastSepNMF(s*v',2);
U = zeros(size(M,1),2);
if length(K) >= 1
U(:,1) = max(u*s*v(K(1),:)',0);
end
if length(K) >= 2
U(:,2) = max(u*s*v(K(2),:)',0);
end
% Compute corresponding optimal V
V = anls_entry_rank2_precompute_opt(U'*U, M'*U);
end |
github | locatelf/cone-greedy-master | affclust.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/affclust.m | 572 | utf_8 | f25d9a40ba0a120bd94d132688082bb1 | % Display clusters
function [a, Vaff] = affclust(K,H,L,ncol,bw);
n = H*L;
if iscell(K)
K = clu2vec(K,n);
end
% K is an indicator vector of type IDX
A = vectoind(K);
r = size(A,2);
% 'Optimize' display in 16/9
if nargin < 4
ncol = 1; nrow = ceil(r/ncol);
while (r > 1 && L*ncol*9 < H*nrow*16) || rem(r,ncol) == 1
ncol = ncol+1;
nrow = ceil(r/ncol);
end
end
if nargin == 5 && bw == 1
[a, Vaff] = affichage(A,ncol,H,L,bw); %bw==1 switches black and white
else
[a, Vaff] = affichage(A,ncol,H,L);
end |
github | locatelf/cone-greedy-master | affichage.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/affichage.m | 1,155 | utf_8 | ebfdbc0a5a5f07a8cbf18f410f322bdc | % Display (=affichage in French) of a NMF solution, for image datasets
%
% a = affichage(V,lig,Li,Co)
%
% Input.
% V : (m x r) matrix whose colums contains vectorized images
% lig : number of images per row in the display
% (Co,Li) : dimensions of images
% bw : if bw=1, reverse gray level
%
% Output.
% Diplay columns of matrix V as images
function [a, Vaff] = affichage(V,lig,Li,Co,bw)
V = max(V,0); [m,r] = size(V);
for i = 1 : r
if max(V(:,i)) > 0
V(:,i) = V(:,i)/max(V(:,i));
end
end
Vaff = [];
for i = 1 : r
ligne = floor((i-1)/lig)+1; col = i - (ligne-1)*lig;
Vaff((ligne-1)*Li+1:ligne*Li,(col-1)*Co+1:col*Co) = reshape(V(:,i),Li,Co);
end
[m,n] = size(Vaff);
for i = 1 : n/Co-1
Vaff = [Vaff(:,1:Co*i+i-1) 0.5*ones(m,1) Vaff(:,Co*i+i:end)];
end
[m,n] = size(Vaff);
for i = 1 : m/Li-1
Vaff = [Vaff(1:Li*i+i-1,:); 0.5*ones(1,n); Vaff(Li*i+i:end,:)];
end
warning('off'); figure;
if nargin == 5 && bw == 1
imshow(Vaff,[0 1]);
else
imshow(1-Vaff,[0 1]);
end
colormap(gray);
warning('on');
a = 1; |
github | locatelf/cone-greedy-master | nnlsm_blockpivot.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/nnlsm_blockpivot.m | 4,413 | utf_8 | cb9bf3455d6fd3ae19ea98b4dd754547 | % Nonnegativity Constrained Least Squares with Multiple Righthand Sides
% using Block Principal Pivoting method
%
% This software solves the following problem: given A and B, find X such that
% minimize || AX-B ||_F^2 where X>=0 elementwise.
%
% Reference:
% Jingu Kim and Haesun Park, Toward Faster Nonnegative Matrix Factorization: A New Algorithm and Comparisons,
% In Proceedings of the 2008 Eighth IEEE International Conference on Data Mining (ICDM'08), 353-362, 2008
%
% Written by Jingu Kim ([email protected])
% Copyright 2008-2009 by Jingu Kim and Haesun Park,
% School of Computational Science and Engineering,
% Georgia Institute of Technology
%
% Check updated code at http://www.cc.gatech.edu/~jingu
% Please send bug reports, comments, or questions to Jingu Kim.
% This code comes with no guarantee or warranty of any kind. Note that this algorithm assumes that the
% input matrix A has full column rank.
%
% Last modified Feb-20-2009
%
% <Inputs>
% A : input matrix (m x n) (by default), or A'*A (n x n) if isInputProd==1
% B : input matrix (m x k) (by default), or A'*B (n x k) if isInputProd==1
% isInputProd : (optional, default:0) if turned on, use (A'*A,A'*B) as input instead of (A,B)
% init : (optional) initial value for X
% <Outputs>
% X : the solution (n x k)
% Y : A'*A*X - A'*B where X is the solution (n x k)
% iter : number of iterations
% success : 1 for success, 0 for failure.
% Failure could only happen on a numericall very ill-conditioned problem.
function [ X,Y,iter,success ] = nnlsm_blockpivot( A, B, isInputProd, init )
if nargin<3, isInputProd=0;, end
if isInputProd
AtA = A;, AtB = B;
else
AtA = A'*A;, AtB = A'*B;
end
[n,k]=size(AtB);
MAX_ITER = n*5;
% set initial feasible solution
X = zeros(n,k);
if nargin<4
Y = - AtB;
PassiveSet = false(n,k);
iter = 0;
else
PassiveSet = (init > 0);
[ X,iter ] = solveNormalEqComb(AtA,AtB,PassiveSet);
Y = AtA * X - AtB;
end
% parameters
pbar = 3;
P = zeros(1,k);, P(:) = pbar;
Ninf = zeros(1,k);, Ninf(:) = n+1;
iter = 0;
NonOptSet = (Y < 0) & ~PassiveSet;
InfeaSet = (X < 0) & PassiveSet;
NotGood = sum(NonOptSet)+sum(InfeaSet);
NotOptCols = NotGood > 0;
bigIter = 0;, success=1;
while(~isempty(find(NotOptCols)))
bigIter = bigIter+1;
if ((MAX_ITER >0) && (bigIter > MAX_ITER)) % set max_iter for ill-conditioned (numerically unstable) case
success = 0;, break
end
Cols1 = NotOptCols & (NotGood < Ninf);
Cols2 = NotOptCols & (NotGood >= Ninf) & (P >= 1);
Cols3Ix = find(NotOptCols & ~Cols1 & ~Cols2);
if ~isempty(find(Cols1))
P(Cols1) = pbar;,Ninf(Cols1) = NotGood(Cols1);
PassiveSet(NonOptSet & repmat(Cols1,n,1)) = true;
PassiveSet(InfeaSet & repmat(Cols1,n,1)) = false;
end
if ~isempty(find(Cols2))
P(Cols2) = P(Cols2)-1;
PassiveSet(NonOptSet & repmat(Cols2,n,1)) = true;
PassiveSet(InfeaSet & repmat(Cols2,n,1)) = false;
end
if ~isempty(Cols3Ix)
for i=1:length(Cols3Ix)
Ix = Cols3Ix(i);
toChange = max(find( NonOptSet(:,Ix)|InfeaSet(:,Ix) ));
if PassiveSet(toChange,Ix)
PassiveSet(toChange,Ix)=false;
else
PassiveSet(toChange,Ix)=true;
end
end
end
NotOptMask = repmat(NotOptCols,n,1);
[ X(:,NotOptCols),subiter ] = solveNormalEqComb(AtA,AtB(:,NotOptCols),PassiveSet(:,NotOptCols));
iter = iter + subiter;
X(abs(X)<1e-12) = 0; % for numerical stability
Y(:,NotOptCols) = AtA * X(:,NotOptCols) - AtB(:,NotOptCols);
Y(abs(Y)<1e-12) = 0; % for numerical stability
% check optimality
NonOptSet = NotOptMask & (Y < 0) & ~PassiveSet;
InfeaSet = NotOptMask & (X < 0) & PassiveSet;
NotGood = sum(NonOptSet)+sum(InfeaSet);
NotOptCols = NotGood > 0;
end
end
|
github | locatelf/cone-greedy-master | FastSepNMF.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/FastSepNMF.m | 3,369 | utf_8 | d1efacdacf79352c067116cbd6ec4a61 | % FastSepNMF - Fast and robust recursive algorithm for separable NMF
%
% *** Description ***
% At each step of the algorithm, the column of M maximizing ||.||_2 is
% extracted, and M is updated by projecting its columns onto the orthogonal
% complement of the extracted column.
%
% See N. Gillis and S.A. Vavasis, Fast and Robust Recursive Algorithms
% for Separable Nonnegative Matrix Factorization, arXiv:1208.1237.
%
% See also https://sites.google.com/site/nicolasgillis/
%
% [J,normM,U] = FastSepNMF(M,r,normalize)
%
% ****** Input ******
% M = WH + N : a (normalized) noisy separable matrix, that is, W is full rank,
% H = [I,H']P where I is the identity matrix, H'>= 0 and its
% columns sum to at most one, P is a permutation matrix, and
% N is sufficiently small.
% r : number of columns to be extracted.
% normalize : normalize=1 will scale the columns of M so that they sum to one,
% hence matrix H will satisfy the assumption above for any
% nonnegative separable matrix M.
% normalize=0 is the default value for which no scaling is
% performed. For example, in hyperspectral imaging, this
% assumption is already satisfied and normalization is not
% necessary.
%
% ****** Output ******
% J : index set of the extracted columns.
% normM : the l2-norm of the columns of the last residual matrix.
% U : normalized extracted columns of the residual.
%
% --> normM and U can be used to continue the recursion later on without
% recomputing everything from scratch.
%
% This implementation of the algorithm is based on the formula
% ||(I-uu^T)v||^2 = ||v||^2 - (u^T v)^2.
function [J,normM,U] = FastSepNMF(M,r,normalize)
[m,n] = size(M);
J = [];
if nargin <= 2, normalize = 0; end
if normalize == 1
% Normalization of the columns of M so that they sum to one
D = spdiags((sum(M).^(-1))', 0, n, n); M = M*D;
end
normM = sum(M.^2);
nM = max(normM);
i = 1;
% Perform r recursion steps (unless the relative approximation error is
% smaller than 10^-9)
while i <= r && max(normM)/nM > 1e-9
% Select the column of M with largest l2-norm
[a,b] = max(normM);
% Norm of the columns of the input matrix M
if i == 1, normM1 = normM; end
% Check ties up to 1e-6 precision
b = find((a-normM)/a <= 1e-6);
% In case of a tie, select column with largest norm of the input matrix M
if length(b) > 1, [c,d] = max(normM1(b)); b = b(d); end
% Update the index set, and extracted column
J(i) = b; U(:,i) = M(:,b);
% Compute (I-u_{i-1}u_{i-1}^T)...(I-u_1u_1^T) U(:,i), that is,
% R^(i)(:,J(i)), where R^(i) is the ith residual (with R^(1) = M).
for j = 1 : i-1
U(:,i) = U(:,i) - U(:,j)*(U(:,j)'*U(:,i));
end
% Normalize U(:,i)
U(:,i) = U(:,i)/norm(U(:,i));
% Compute v = u_i^T(I-u_{i-1}u_{i-1}^T)...(I-u_1u_1^T)
v = U(:,i);
for j = i-1 : -1 : 1
v = v - (v'*U(:,j))*U(:,j);
end
% Update the norm of the columns of M after orhogonal projection using
% the formula ||r^(i)_k||^2 = ||r^(i-1)_k||^2 - ( v^T m_k )^2 for all k.
normM = normM - (v'*M).^2;
i = i + 1;
end |
github | locatelf/cone-greedy-master | clu2vec.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/clu2vec.m | 302 | utf_8 | 59890ba3279c8d45d1c01fb24000bdc6 | % Transform a cluster cell to a vector
function IDX = clu2vec(K,m,r);
if nargin < 3
r = length(K);
end
if nargin < 2
% Compute max entry in K
m = 0;
for i = 1 : r
m = max(0, max(K{i}));
end
end
IDX = zeros(m,1);
for i = 1 : r
IDX(K{i}) = i;
end |
github | locatelf/cone-greedy-master | reprvec.m | .m | cone-greedy-master/HyperspectralImaging/hierclust2nmf_v2/reprvec.m | 726 | utf_8 | d3e05d1279b90585355adc9d6de3c3a7 | % Extract "most" representative column from a matrix M as follows:
%
% First, it computes the best rank-one approximation u v^T of M.
% Then, it identifies the column of M minimizing the MRSA with the first
% singular vector u of M.
%
% See Section 4.4.1 of
% Gillis, Kuang, Park, `Hierarchical Clustering of Hyperspectral Images
% using Rank-Two Nonnegative Matrix Factorization', arXiv.
function [u,s,b] = reprvec(M);
[u,s,v] = svds(M,1);
u = abs(u);
[m,n] = size(M);
% Exctract the column of M approximating u the best (up to a translation and scaling)
u = u - mean(u);
Mm = M - repmat(mean(M),m,1);
err = acos( (Mm'*u/norm(u))./( sqrt(sum(Mm.^2)) )' );
[a,b] = min(err);
u = M(:,b); |
github | locatelf/cone-greedy-master | EEAs.m | .m | cone-greedy-master/HyperspectralImaging/Endmember Extraction Algorithms/EEAs.m | 328 | utf_8 | b80a0699acd0816f24d73bf3969910ec | % Different EEA algorithms
function K = EEAs(M,r,algo);
if algo == 1
K = FastSepNMF(M,r);
elseif algo == 2
K = VCA(M,'Endmembers',r,'verbose','off');
elseif algo == 3
K = FastConicalHull(M,r);
elseif algo == 4
[~, ~, K] = hierclust2nmf(M,r,1,[],0);
elseif algo == 5
K = SNPA(M,r);
end |
github | locatelf/cone-greedy-master | RVCA.m | .m | cone-greedy-master/HyperspectralImaging/Endmember Extraction Algorithms/RVCA.m | 358 | utf_8 | 5f0767712f593be37f43c851734d741d | % Robust VCA
function K = RVCA(M,r,rparam);
maxiter = 10;
if nargin <= 2
rparam = 10;
end
emin = +Inf;
for i = 1 : rparam
[A, K] = VCA(M,'Endmembers',r,'verbose','off');
H = nnlsHALSupdt(M,M(:,K),[],maxiter);
err = norm(M-M(:,K)*H,'fro');
if err < emin
Kf = K;
emin = err;
end
end |
github | locatelf/cone-greedy-master | SimplexProj.m | .m | cone-greedy-master/HyperspectralImaging/Endmember Extraction Algorithms/SimplexProj.m | 1,374 | utf_8 | f6f156f333432d0897537cbf10fa3595 | function x = SimplexProj(y)
% Given y, computes its projection x* onto the simplex
%
% Delta = { x | x >= 0 and sum(x) <= 1 },
%
% that is, x* = argmin_x ||x-y||_2 such that x in Delta.
%
%
% See Appendix A.1 in N. Gillis, Successive Nonnegative Projection
% Algorithm for Robust Nonnegative Blind Source Separation, arXiv, 2013.
%
%
% x = SimplexProj(y)
%
% ****** Input ******
% y : input vector.
%
% ****** Output ******
% x : projection of y onto Delta.
x = max(y,0);
K = find(sum(x) > 1);
x(:,K) = blockSimplexProj(y(:,K));
end
function x = blockSimplexProj(y)
% Same as function SimplexProj except that sum(max(Y,0)) > 1.
[r,m] = size(y);
ys = sort(-y); ys = -ys;
indi2 = 1:m; lambda = zeros(1,m);
S(1,indi2) = 0;
for i = 2 : r
if i == 2
S(i,:) = (ys(1:i-1,:)-repmat(ys(i,:),i-1,1));
else
S(i,:) = sum(ys(1:i-1,:)-repmat(ys(i,:),i-1,1));
end
indi1 = find(S(i,indi2) >= 1);
indi1 = indi2(indi1);
indi2 = find(S(i,:) < 1);
if ~isempty(indi1)
if i == 1
lambda(indi1) = -ys(1,indi1)+1;
else
lambda(indi1) = (1-S(i-1,indi1))/(i-1) - ys(i-1,indi1);
end
end
if i == r
lambda(indi2) = (1-S(r,indi2))/r - ys(r,indi2);
end
end
x = max( y + repmat(lambda,r,1), 0);
end |
github | krasvas/LandRate-master | fixations_t2.m | .m | LandRate-master/fixations_t2.m | 3,218 | utf_8 | 35b1c3cbde506d34b53f3d7774c7b5f1 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%import fixations list after t1 criterion,fixation id and t2 parameter
%output:(fixx,fixy,number_t1,number_t2,duration,list_out_points)
%fixx,fixy: coordinates of the center
%number_t1: number of points before t2 criterion
%number_t2:number of points after t2 criterion
%list_out_points:points which are not used after t2 criterion
function [fixx,fixy,number_t1,number_t2,start_time,end_time,duration,list_out_points]=fixations_t2(fixations,fixation_id,t2) %fixations after t1 criterion
n=size(fixations);
n=n(1,1); %number of all points
fixations_id=zeros(1,4);
for i=1:n
if fixations(i,4)==fixation_id
fixations_id=[fixations_id;fixations(i,:)];
end
end
n=size(fixations_id);
n=n(1,1);
fixations_id=fixations_id(2:n,:); %list of data points with the defined id
%clustering according to criterion t2
number_t1=size(fixations_id);
x=fixations_id(:,1);
y=fixations_id(:,2);
t=fixations_id(:,3);
number_t1=number_t1(1,1); %number of points before t2
%initialize mean values of center
fixx=mean(fixations_id(:,1));
fixy=mean(fixations_id(:,2));
d=0; %distance between cluster point and mean point
for i=1:number_t1
d=distance2p(x(i),y(i),fixx,fixy);
if d>t2
fixations_id(i,4)=0;
end
end
%initialize new list (data points according to t2)
fixations_list_t2=zeros(1,4);
%initialize list of points which are nto used aftere t2 criterion
list_out_points=zeros(1,4);
for i=1:number_t1
if fixations_id(i,4)>0
fixations_list_t2=[fixations_list_t2;fixations_id(i,:)];
else
list_out_points=[list_out_points;fixations_id(i,:)];
end
end
n=size(fixations_list_t2);
n=n(1,1);
fixations_list_t2=fixations_list_t2(2:n,:);
number_t2=size(fixations_list_t2);
number_t2=number_t2(1,1);
fixx=mean(fixations_list_t2(:,1));
fixy=mean(fixations_list_t2(:,2));
if number_t2>0
start_time=fixations_list_t2(1,3);
end_time=fixations_list_t2(number_t2,3);
duration=fixations_list_t2(number_t2,3)-fixations_list_t2(1,3);
else
start_time=0;
end_time=0;
duration=0;
end
list_out_points;
n_out=size(list_out_points);
n_out=n_out(1,1);
if n_out>1
list_out_points=list_out_points(2:n_out,:);
else
list_out_points=[0 0 0 -1];%indicates that there are not points which are not used
end
end
|
github | krasvas/LandRate-master | angle_to_tracker.m | .m | LandRate-master/angle_to_tracker.m | 2,653 | utf_8 | d6c6e7e24857b7c66791375b69c56293 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function angle_to_tracker
%compute distance t in stimuli display from visual range in tracker units
%input parameters:
%-theta: visual angle range in degrees
%-d: distance between subject and stimulus in mm
%-tmm: the distance in mm which corresponds with 1 unit in tracker values
%export matlab matrix:
%-t:the corresponded spatial section in tracker units
%call function example:
%angle_to_tracker(8,555,301.1)
function t=angle_to_tracker(theta,d,tmm)
%transform angle from degrees to rads
theta=theta*pi()/180;
%compute t
t=(2*d/tmm)*tan(theta/2); %tracker units
fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
fprintf('\n')
fprintf(' This program is free software: you can redistribute it and/or modify\n')
fprintf(' it under the terms of the GNU General Public License as published by\n')
fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
fprintf(' (at your option) any later version.\n')
fprintf('\n')
fprintf(' This program is distributed in the hope that it will be useful,\n')
fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
fprintf(' GNU General Public License for more details.\n')
fprintf('\n')
fprintf(' You should have received a copy of the GNU General Public License\n')
fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
fprintf('\n')
fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end |
github | krasvas/LandRate-master | min_duration.m | .m | LandRate-master/min_duration.m | 1,455 | utf_8 | 08bbb2e381ecc7d1eaf94b5d1cd77dde | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%import the list of fixations (Center x, Center y, Number of data points
%after t1, Number of data points after second criterion, Start time, End
%time, Duration) and minimum duration
function fixations=min_duration(fixation_list,minDur)
n=size(fixation_list);
n=n(1,1);
%initialize new fixation list
fixations=zeros(1,7);
for i=1:n
if fixation_list(i,7)>minDur
fixations=[fixations;fixation_list(i,:)];
end
end
n=size(fixations);
n=n(1,1);
fixations=fixations(2:n,:);
end
|
github | krasvas/LandRate-master | points_in_region.m | .m | LandRate-master/points_in_region.m | 1,683 | utf_8 | 81e57f7705f5cae4ec62c23ff24f6996 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%x:horizontal coord from all records
%y:vertical coord from all records
function n_records_region=points_in_region(x,y,left_up_edge_x,left_up_edge_y,right_down_edge_x,right_down_edge_y)
%edges of region
right_up_edge_x=right_down_edge_x;
right_up_edge_y=left_up_edge_y;
left_down_edge_x=left_up_edge_x;
left_down_edge_y=right_down_edge_y;
%total number of records
n=size(x);
n=n(1,1);
%number of records in region
n_records_region=0;
for i=1:n
if (x(i)>left_up_edge_x || x(i)==left_up_edge_x) &&( x(i)<right_up_edge_x || x(i)==right_up_edge_x )&& (y(i)>left_up_edge_y || y(i)==left_up_edge_y) &&( y(i)<left_down_edge_y || y(i)==left_down_edge_y)
n_records_region=n_records_region+1;
end
end
end
|
github | krasvas/LandRate-master | ROI_analysis.m | .m | LandRate-master/ROI_analysis.m | 6,080 | utf_8 | daaa2c110078af2f97a7f3a6c2ec7388 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function ROI_analysis
%analysis in predefined rectangle region of interest
%input parameters:
%-fixation_list: list of fixations(after fixation_detection)
%-rois: regions of interest file((x_left_up,y_left_up,x_right_down,y_right_down,ROIs ID)
%-roi_to_analyze: define the analyzed ROI from ROI ID (according to the IDs in rois file)
%export matlab matrix:
%-fixations_in_roi: fixations in the analyzed region of interest
%call function example:
%ROI_analysis(fixation_list,'ROIS.txt',2);
%fixation_list:matlab matrix as computed from fixation_detection
function fixations_in_roi=ROI_analysis(fixation_list,rois,roi_to_analyze)
rois=load(rois);
x_fix=fixation_list(:,1);
y_fix=fixation_list(:,2);
duration=fixation_list(:,7);
%number of ROIs
n_rois=size(rois);
n_rois=n_rois(1,1);
%classify fixations in ROis(0:indicates that fixation is out of ROI)
fixations_classification=zeros(length(x_fix),1);
for i=1:length(x_fix)
for j=1:n_rois
if ((x_fix(i)>=rois(j,1) && x_fix(i)<=rois(j,3)) && (y_fix(i)<=rois(j,2) && y_fix(i)>=rois(j,4)))
fixations_classification(i)=rois(j,5);
end
end
end
fixation_list(:,8)=fixations_classification;
%build the matrix with fixations in selected roi
%initialize fixations_in_roi(x_fixation,y_fixation,duration)
fixations_in_roi=zeros(1,3);
for i=1:length(x_fix)
if fixation_list(i,8)==roi_to_analyze
fixations_in_roi=[fixations_in_roi;x_fix(i),y_fix(i),duration(i)];
end
end
n_fixations=size(fixations_in_roi);
n_fixations=n_fixations(1,1);
if n_fixations>1
fixations_in_roi=fixations_in_roi(2:n_fixations,:);
%compute the number of fixations in roi
number_fixations_in_roi=size(fixations_in_roi);
number_fixations_in_roi=number_fixations_in_roi(1,1);
%compute mean duration of fixations in roi
mean_duration_roi=mean(fixations_in_roi(:,3));
%compute % number of fixations in roi
fixations_percentage_roi=number_fixations_in_roi/length(x_fix);
%compute % duration of fixations in roi
duration_percentage_roi=sum(fixations_in_roi(:,3))/sum(duration);
%print results
fprintf(' ROI Analysis\n')
fprintf('\nID of selected ROI for analysis: %.f\n',roi_to_analyze)
fprintf('Number of fixations in selected ROI: %.f\n',number_fixations_in_roi)
if n_fixations>1
fprintf('\nFixation List in ROI:\n')
fprintf(' X_Fixation-Y_Fixation-Duration\n')
for i=1:number_fixations_in_roi
fprintf(' %.4f %.4f %.1f\n',fixations_in_roi(i,1),fixations_in_roi(i,2),fixations_in_roi(i,3))
end
fprintf('\nMean duration of fixations in ROI: %.1f\n',mean_duration_roi)
fprintf('Number (%%) of fixations in ROI: %.2f%%\n',fixations_percentage_roi*100)
fprintf('Duration (%%) of fixations in ROI: %.2f%%\n',duration_percentage_roi*100)
end
%plot_ROIs
plot(x_fix,y_fix,'bo')
hold on
for i=1:n_rois
roi_region=[rois(i,1),rois(i,2);rois(i,3),rois(i,2);rois(i,3),rois(i,4);rois(i,1),rois(i,4);rois(i,1),rois(i,2)];
if i==roi_to_analyze
fill(roi_region(:,1),roi_region(:,2),'r')
alpha(0.7)
end
hold on
end
for i=1:n_rois
roi_region=[rois(i,1),rois(i,2);rois(i,3),rois(i,2);rois(i,3),rois(i,4);rois(i,1),rois(i,4);rois(i,1),rois(i,2)];
plot(roi_region(:,1),roi_region(:,2),'g-')
hold on
end
axis('equal')
title('Regions of Interest (ROIs) ','Color','k','FontSize',20)
xlabel('Horizontal Coordinate','Color','k','FontSize',20)
ylabel('Vertical Coordinate','Color','k','FontSize',20)
set(gca,'FontSize',20)
legend('Fixations','Selected ROI','ROIs','Location','SouthEastOutside')
else
number_fixations_in_roi=0;
fprintf(' ROI Analysis\n')
fprintf('\nID of selected ROI for analysis: %.f\n',roi_to_analyze)
fprintf('Number of fixations in selected ROI: %.f\n',number_fixations_in_roi)
end
fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
fprintf('\n')
fprintf(' This program is free software: you can redistribute it and/or modify\n')
fprintf(' it under the terms of the GNU General Public License as published by\n')
fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
fprintf(' (at your option) any later version.\n')
fprintf('\n')
fprintf(' This program is distributed in the hope that it will be useful,\n')
fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
fprintf(' GNU General Public License for more details.\n')
fprintf('\n')
fprintf(' You should have received a copy of the GNU General Public License\n')
fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
fprintf('\n')
fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | krasvas/LandRate-master | heatmap_generator.m | .m | LandRate-master/heatmap_generator.m | 6,654 | utf_8 | 11496414805a2ede9a65bd0da6982178 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%Heatmap generator
%Generate Heatmap Visualization computed from Raw Data
%input parameters:
%-records: list of records(x,y) from all subjects,x,y:in tracker units
%-scene: stimulus image
%-spacing: interval to define heatmap density
%-max_hor: maximum horizontal value of tracker coordinate system
%-max_ver: maximum vertical value of tracker coordinate system
%-kernel_size_gaussian: kernel size for gaussian filtering
%-s_gaussian:sigma for gaussian filtering
%export matlab matrixes:
%-heatmapRGB:heatmap values RGB
%-heatmap:heatmap grayscale
%call function example:
%heatmap_generator('data.txt','stimulus.bmp',0.0833,1.25,1.00,5,3);
function [heatmapRGB,heatmap]=heatmap_generator(records,scene,spacing,max_hor,max_ver,kernel_size_gaussian,s_gaussian)
records=load(records);
scene=imread(scene);
x=records(:,1);
y=records(:,2);
n_scene=size(scene);
n_1_scene=n_scene(1,1);
n_2_scene=n_scene(1,2);
%total number of points
n=size(records);
n=n(1,1);
%create heatmap matrix
%heatmap values: records frequency
%heatmap dimensions
heatmap_ver_values=(0:spacing:max_ver);
heatmap_hor_values=(0:spacing:max_hor);
heatmap_ver_number=size(heatmap_ver_values);
heatmap_ver_number=heatmap_ver_number(1,2)-1;%number of vertical elements in heatmap matrix
heatmap_hor_number=size(heatmap_hor_values);
heatmap_hor_number=heatmap_hor_number(1,2)-1;%number of vertical elements in heatmap matrix
%heatmap matrix initialization
heatmap=zeros(heatmap_ver_number,heatmap_hor_number);
%frequencies
f=zeros(heatmap_hor_number*heatmap_ver_number,1);
n_f=size(f);
n_f=n_f(1,1);
%initialize counters
j=0;
i=1;
for l=1:heatmap_ver_number
for k=1:heatmap_hor_number
i;
j=j+1;
heatmap(i,j)=points_in_region(x,y,heatmap_hor_values(k),heatmap_ver_values(l),heatmap_hor_values(k+1),heatmap_ver_values(l+1));
end
i=i+1;
j=0;
end
heatmap_frequencies=heatmap;
%adjust frequenies values to range 0-255
%255:max frequency
%0:no frequency
heatmap=(255/max(max(heatmap)))*heatmap;
heatmap=floor(heatmap);%integer values
%take the inverse image
%heatmap=255-heatmap;
heatmap=uint8(heatmap);
%resize heatmap to adjust to scene resolution
heatmap=imresize(heatmap,[n_1_scene n_2_scene],'bicubic');
%create RGB heatmap
heatmapRGB=zeros(n_1_scene,n_2_scene,3);
%initialize R,G,B
R=zeros(n_1_scene,n_2_scene);
G=zeros(n_1_scene,n_2_scene);
B=zeros(n_1_scene,n_2_scene);
for i=1:1024
for j=1:1280
if (heatmap(i,j)==0 || heatmap(i,j)>0) && (heatmap(i,j)==25 || heatmap(i,j)<25)
R(i,j)=10;
G(i,j)=10;
B(i,j)=10;
elseif (heatmap(i,j)==26 || heatmap(i,j)>26) && (heatmap(i,j)==50 || heatmap(i,j)<50)
R(i,j)=60;
G(i,j)=60;
B(i,j)=60;
elseif (heatmap(i,j)==51 || heatmap(i,j)>51) && (heatmap(i,j)==75 || heatmap(i,j)<75)
R(i,j)=0;
G(i,j)=0;
B(i,j)=255;
elseif (heatmap(i,j)==76 || heatmap(i,j)>76) && (heatmap(i,j)==100 || heatmap(i,j)<100)
R(i,j)=0;
G(i,j)=255;
B(i,j)=210;
elseif (heatmap(i,j)==101 || heatmap(i,j)>101) && (heatmap(i,j)==125 || heatmap(i,j)<125)
R(i,j)=0;
G(i,j)=255;
B(i,j)=75;
elseif (heatmap(i,j)==126 || heatmap(i,j)>126) && (heatmap(i,j)==150 || heatmap(i,j)<150)
R(i,j)=192;
G(i,j)=255;
B(i,j)=0;
elseif (heatmap(i,j)==151 || heatmap(i,j)>151) && (heatmap(i,j)==175 || heatmap(i,j)<175)
R(i,j)=255;
G(i,j)=240;
B(i,j)=0;
elseif (heatmap(i,j)==176 || heatmap(i,j)>176) && (heatmap(i,j)==200 || heatmap(i,j)<200)
R(i,j)=255;
G(i,j)=192;
B(i,j)=0;
elseif (heatmap(i,j)==201 || heatmap(i,j)>201) && (heatmap(i,j)==225 || heatmap(i,j)<225)
R(i,j)=255;
G(i,j)=150;
B(i,j)=0;
else
R(i,j)=255;
G(i,j)=0;
B(i,j)=0;
end
end
end
R=uint8(R);
G=uint8(G);
B=uint8(B);
heatmapRGB(:,:,1)=R;
heatmapRGB(:,:,2)=G;
heatmapRGB(:,:,3)=B;
heatmapRGB=uint8(heatmapRGB);
%show heatmap after gaussian filtering
figure
imshow(scene)
hold on
h = fspecial('gaussian',kernel_size_gaussian,s_gaussian);
imshow(imfilter(heatmapRGB,h,'replicate'));
title('Heatmap','Color','k','FontSize',14)
alpha(0.6)
fprintf('\nHeatmap Visualization is completed successfully\n')
fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
fprintf('\n')
fprintf(' This program is free software: you can redistribute it and/or modify\n')
fprintf(' it under the terms of the GNU General Public License as published by\n')
fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
fprintf(' (at your option) any later version.\n')
fprintf('\n')
fprintf(' This program is distributed in the hope that it will be useful,\n')
fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
fprintf(' GNU General Public License for more details.\n')
fprintf('\n')
fprintf(' You should have received a copy of the GNU General Public License\n')
fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
fprintf('\n')
fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | krasvas/LandRate-master | heatmap_generator_EyeMMV_modified.m | .m | LandRate-master/heatmap_generator_EyeMMV_modified.m | 6,927 | utf_8 | 5ca3103a40391da6e0a0aaf6652b4ee8 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%Heatmap generator
%Generate Heatmap Visualization computed from Raw Data
%input parameters:
%-records: list of records(x,y) from all subjects,x,y:in tracker units
%-scene: stimulus image
%-spacing: interval to define heatmap density
%-max_hor: maximum horizontal value of tracker coordinate system
%-max_ver: maximum vertical value of tracker coordinate system
%-kernel_size_gaussian: kernel size for gaussian filtering
%-s_gaussian:sigma for gaussian filtering
%export matlab matrixes:
%-heatmapRGB:heatmap values RGB
%-heatmap:heatmap grayscale
%call function example:
%heatmap_generator('data.txt','stimulus.bmp',0.0833,1.25,1.00,5,3);
%new parameters
%spacing_coefficient
%stimulus_ID
%max_hor,max_ver:in pixels
function [heatmapRGB,heatmap]=heatmap_generator(records,scene,spacing_coef,max_hor,max_ver,kernel_size_gaussian,s_gaussian,stimulus_ID)
figure ('Name','Heatmap visualization')
spacing=spacing_coef*max_hor;
%records=load(records);
scene=imread(scene);
x=records(:,1);
y=records(:,2);
n_scene=size(scene);
n_1_scene=n_scene(1,1);
n_2_scene=n_scene(1,2);
%total number of points
n=size(records);
n=n(1,1);
%create heatmap matrix
%heatmap values: records frequency
%heatmap dimensions
heatmap_ver_values=(0:spacing:max_ver);
heatmap_hor_values=(0:spacing:max_hor);
heatmap_ver_number=size(heatmap_ver_values);
heatmap_ver_number=heatmap_ver_number(1,2)-1;%number of vertical elements in heatmap matrix
heatmap_hor_number=size(heatmap_hor_values);
heatmap_hor_number=heatmap_hor_number(1,2)-1;%number of vertical elements in heatmap matrix
%heatmap matrix initialization
heatmap=zeros(heatmap_ver_number,heatmap_hor_number);
%frequencies
f=zeros(heatmap_hor_number*heatmap_ver_number,1);
n_f=size(f);
n_f=n_f(1,1);
%initialize counters
j=0;
i=1;
for l=1:heatmap_ver_number
for k=1:heatmap_hor_number
i;
j=j+1;
heatmap(i,j)=points_in_region(x,y,heatmap_hor_values(k),heatmap_ver_values(l),heatmap_hor_values(k+1),heatmap_ver_values(l+1));
end
i=i+1;
j=0;
end
heatmap_frequencies=heatmap;
%adjust frequenies values to range 0-255
%255:max frequency
%0:no frequency
heatmap=(255/max(max(heatmap)))*heatmap;
heatmap=floor(heatmap);%integer values
%take the inverse image
%heatmap=255-heatmap;
heatmap=uint8(heatmap);
%resize heatmap to adjust to scene resolution
heatmap=imresize(heatmap,[n_1_scene n_2_scene],'bicubic');
%create RGB heatmap
heatmapRGB=zeros(n_1_scene,n_2_scene,3);
%initialize R,G,B
R=zeros(n_1_scene,n_2_scene);
G=zeros(n_1_scene,n_2_scene);
B=zeros(n_1_scene,n_2_scene);
for i=1:n_1_scene
for j=1:n_2_scene
if (heatmap(i,j)==0 || heatmap(i,j)>0) && (heatmap(i,j)==25 || heatmap(i,j)<25)
R(i,j)=150;
G(i,j)=150;
B(i,j)=150;
elseif (heatmap(i,j)==26 || heatmap(i,j)>26) && (heatmap(i,j)==50 || heatmap(i,j)<50)
R(i,j)=100;
G(i,j)=100;
B(i,j)=100;
elseif (heatmap(i,j)==51 || heatmap(i,j)>51) && (heatmap(i,j)==75 || heatmap(i,j)<75)
R(i,j)=0;
G(i,j)=0;
B(i,j)=255;
elseif (heatmap(i,j)==76 || heatmap(i,j)>76) && (heatmap(i,j)==100 || heatmap(i,j)<100)
R(i,j)=0;
G(i,j)=255;
B(i,j)=210;
elseif (heatmap(i,j)==101 || heatmap(i,j)>101) && (heatmap(i,j)==125 || heatmap(i,j)<125)
R(i,j)=0;
G(i,j)=255;
B(i,j)=75;
elseif (heatmap(i,j)==126 || heatmap(i,j)>126) && (heatmap(i,j)==150 || heatmap(i,j)<150)
R(i,j)=192;
G(i,j)=255;
B(i,j)=0;
elseif (heatmap(i,j)==151 || heatmap(i,j)>151) && (heatmap(i,j)==175 || heatmap(i,j)<175)
R(i,j)=255;
G(i,j)=240;
B(i,j)=0;
elseif (heatmap(i,j)==176 || heatmap(i,j)>176) && (heatmap(i,j)==200 || heatmap(i,j)<200)
R(i,j)=255;
G(i,j)=192;
B(i,j)=0;
elseif (heatmap(i,j)==201 || heatmap(i,j)>201) && (heatmap(i,j)==225 || heatmap(i,j)<225)
R(i,j)=255;
G(i,j)=150;
B(i,j)=0;
else
R(i,j)=255;
G(i,j)=0;
B(i,j)=0;
end
end
end
R=uint8(R);
G=uint8(G);
B=uint8(B);
heatmapRGB(:,:,1)=R;
heatmapRGB(:,:,2)=G;
heatmapRGB(:,:,3)=B;
heatmapRGB=uint8(heatmapRGB);
%show heatmap after gaussian filtering
imshow(scene,'InitialMagnification','fit')
hold on
h = fspecial('gaussian',kernel_size_gaussian,s_gaussian);
imshow(imfilter(heatmapRGB,h,'replicate'));
title(['Heatmap visualization [Stimulus: ',num2str(stimulus_ID),']'])
alpha(0.6)
% fprintf('\nHeatmap Visualization is completed successfully\n')
%
%
%
% fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
% fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
% fprintf('\n')
% fprintf(' This program is free software: you can redistribute it and/or modify\n')
% fprintf(' it under the terms of the GNU General Public License as published by\n')
% fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
% fprintf(' (at your option) any later version.\n')
% fprintf('\n')
% fprintf(' This program is distributed in the hope that it will be useful,\n')
% fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
% fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
% fprintf(' GNU General Public License for more details.\n')
% fprintf('\n')
% fprintf(' You should have received a copy of the GNU General Public License\n')
% fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
% fprintf('\n')
% fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | krasvas/LandRate-master | fixations_3s.m | .m | LandRate-master/fixations_3s.m | 2,772 | utf_8 | dd807d2f0ba54a516cf1196248a718ce | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%applying 3s criterion
%import fixations list after t1 criterion, fixation id
%output:(fixx,fixy,number_t1,number_t2,duration)
%fixx,fixy: coordinates of the center
%number_t1: number of points before t2 criterion
%number_3s:number of points after 3s criterion
function [fixx,fixy,number_t1,number_3s,start_time,end_time,duration]=fixations_3s(fixations,fixation_id) %fixations after t1 criterion
n=size(fixations);
n=n(1,1); %number of all points
fixations_id=zeros(1,4);
for i=1:n
if fixations(i,4)==fixation_id
fixations_id=[fixations_id;fixations(i,:)];
end
end
n=size(fixations_id);
n=n(1,1);
fixations_id=fixations_id(2:n,:); %list of data points with the defined id
%clustering according to criterion t2
number_t1=size(fixations_id);
x=fixations_id(:,1);
y=fixations_id(:,2);
t=fixations_id(:,3);
number_t1=number_t1(1,1); %number of points before 3s criterion
%initialize mean values of center
fixx=mean(fixations_id(:,1));
fixy=mean(fixations_id(:,2));
%compute standard deviation of cluster
sx=std(x);
sy=std(y);
s=sqrt((sx^2)+(sy^2));
d=0; %distance between cluster point and mean point
for i=1:number_t1
d=distance2p(x(i),y(i),fixx,fixy);
if d>(3*s)
fixations_id(i,4)=0;
end
end
%initialize new list (data points according to 3s criterion)
fixations_list_3s=zeros(1,4);
for i=1:number_t1
if fixations_id(i,4)>0
fixations_list_3s=[fixations_list_3s;fixations_id(i,:)];
end
end
n=size(fixations_list_3s);
n=n(1,1);
fixations_list_3s=fixations_list_3s(2:n,:);
number_3s=size(fixations_list_3s);
number_3s=number_3s(1,1);
fixx=mean(fixations_list_3s(:,1));
fixy=mean(fixations_list_3s(:,2));
start_time=fixations_list_3s(1,3);
end_time=fixations_list_3s(number_3s,3);
duration=fixations_list_3s(number_3s,3)-fixations_list_3s(1,3);
end
|
github | krasvas/LandRate-master | metrics_analysis.m | .m | LandRate-master/metrics_analysis.m | 10,253 | utf_8 | b519fe7acad925cc6d0c0035d27752b8 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function metrics_analysis
%eye movement metrics computations
%input parameters:
%-fixation_list: list of fixations(after fixation_detection)
%-repeat_fixation_threshold: threshold in tracker units for repeat fixations
%-spacing_scanpath: interval in tracker units to compute scanpath density
%-spacing_transition: interval in tracker units to compute transition matrix density
%-maxx: maximum horizontal coordinate in tracker coordinate system
%-maxy: maximum vertical coordinate in tracker coordinate system
%export matlab matrixes:
%-repeat_fixations: list of repeat fixations
%-saccades: list of saccadic movements
%-transition_matrix: transition matrix according the giving sapcing
%call function example:
%metrics_analysis(fixation_list,0.10,0.25,0.25,1.25,1.00);
%fixation_list:matlab matrix as computed from fixation_detection
function [repeat_fixations,saccades,transition_matrix]=metrics_analysis(fixation_list,repeat_fixation_threshold,spacing_scanpath,spacing_transition,maxx,maxy)
%Fixation analysis
%compute total number of fixations
total_number_fixations=size(fixation_list);
total_number_fixations=total_number_fixations(1,1);
%compute mean duration of fixations
mean_durations_fixations=mean(fixation_list(:,7));
%compute time to first fixation
time_to_first_fixation=fixation_list(1,5);
%compute repeat fixations
%initialize distances between fixations(fixation1,fixation2,distance_between_two_fixations)
distances_between_fixations=zeros(1,3);
for i=1:total_number_fixations
for j=1:total_number_fixations
if i~=j && i<j
distances_between_fixations=[distances_between_fixations;[i,j,(distance2p(fixation_list(i,1),fixation_list(i,2),fixation_list(j,1),fixation_list(j,2)))]];
end
end
end
n_distances_between_fixations=size(distances_between_fixations);
n_distances_between_fixations=n_distances_between_fixations(1,1);
distances_between_fixations=distances_between_fixations(2:n_distances_between_fixations,:);
%initialize matrix of repeat fixations
repeat_fixations=zeros(1,3);
for i=1:(n_distances_between_fixations-1)
if distances_between_fixations(i,3)<repeat_fixation_threshold
repeat_fixations=[repeat_fixations;distances_between_fixations(i,:)];
end
end
n_repeat_fixations=size(repeat_fixations);
n_repeat_fixations=n_repeat_fixations(1,1);
if n_repeat_fixations>1
repeat_fixations=repeat_fixations(2:n_repeat_fixations,:);
end
%compute total duration of fixations
total_duration_fixations=sum(fixation_list(:,7));
%Saccade analysis
%build saccades list (x_start_point,y_start_point,x_end_point,y_end_point, duration, amplitude, direction angle,start_fixation,end_fixation)
if total_number_fixations>2 || total_number_fixations==2
total_number_saccades=total_number_fixations-1;
%initialize saccades list
saccades=zeros(total_number_saccades,9);
j=2;%pointer
for i=1:(total_number_fixations-1)
%import start and end points in list
saccades(i,1)=fixation_list(i,1);
saccades(i,2)=fixation_list(i,2);
saccades(i,3)=fixation_list(j,1);
saccades(i,4)=fixation_list(j,2);
%compute saccades durations
saccades(i,5)=fixation_list(j,5)-fixation_list(i,6);
%compute amplitude
saccades(i,6)=distance2p(saccades(i,1),saccades(i,2),saccades(i,3),saccades(i,4));
%compute direction angle
saccades(i,7)=direction_angle(saccades(i,1),saccades(i,2),saccades(i,3),saccades(i,4));
%name start and end fixations in each saccade
saccades(i,8)=i;
saccades(i,9)=j;
j=j+1;
end
%compute mean duration of saccades
mean_durations_saccades=mean(saccades(:,5));
else
total_number_saccades=0;
end
%Scanpath analysis
%compute scanpath length
scanpath_length=sum(saccades(:,6));
%compute scanpath duration
scanpath_duration=fixation_list(total_number_fixations,6)-fixation_list(1,5);
%compute saccade/fixation ratio
ratio_sf=sum(saccades(:,5))/sum(fixation_list(:,7));
%compute scanpath spatial density
%build points_areas_matrix(x,y,area_id)
%initialize
points_areas_matrix=zeros(1,3);
for i=1:total_number_fixations
area=find_point_area(fixation_list(i,1),fixation_list(i,2),maxx,maxy,spacing_scanpath);
points_areas_matrix(i,1)=area(1);
points_areas_matrix(i,2)=area(2);
points_areas_matrix(i,3)=area(3);
end
n_scanpath_areas=area(4);
%compute the number of unique areas between points areas
number_different_areas=length(unique(points_areas_matrix(:,3)));
%scanpath_density
scanpath_density=number_different_areas/n_scanpath_areas;
%create transition matrix
%build fixation_transition_areas(x_fixation,y_fixation,x_center,y_center,transition_area)
%initialize fixation_transition areas
fixation_transition_areas=zeros(1,5);
for i=1:total_number_fixations
fixation_transition_areas(i,1)=fixation_list(i,1);
fixation_transition_areas(i,2)=fixation_list(i,2);
area=find_point_area(fixation_list(i,1),fixation_list(i,2),maxx,maxy,spacing_transition);
fixation_transition_areas(i,3:5)=area(1:3);
end
%transitions
transitions=fixation_transition_areas(:,5);
%transition dimension corresponds to maximun number of areas
transition_dimension=area(4);
%build transition matrix(>=1:indicates transition, 0: indicates no transition)
%initialize
transition_matrix=zeros(transition_dimension);
for i=1:(total_number_fixations-1)
for j=1:transition_dimension
if j==transitions(i)
transition_matrix(transitions(i+1),j)=transition_matrix(transitions(i+1),j)+1;
end
end
end
%compute the number of transitions
%initialize number
number_transitions=0;
for i=1:transition_dimension
for j=1:transition_dimension
if transition_matrix(i,j)>0
number_transitions=number_transitions+1;
end
end
end
%compute transition density
transition_density=number_transitions/(transition_dimension^2);
%print results
fprintf('Eye Movement metrics analysis\n\n')
fprintf('Input Parameters: \n')
fprintf(' Threshold for repeat fixations: %.3f\n',repeat_fixation_threshold)
fprintf(' Scanpath spacing (spatial density computation): %.3f\n',spacing_scanpath)
fprintf(' Transition matrix spacing: %.3f\n',spacing_transition)
fprintf('\nFixation Metrics Analysis:\n')
fprintf(' Total number of fixations: %.f\n',total_number_fixations)
fprintf(' Mean duration of fixations: %.1f\n',mean_durations_fixations)
fprintf(' Time to first fixation: %.1f\n',time_to_first_fixation)
if n_repeat_fixations>1
fprintf(' Repeat Fixations:\n')
fprintf(' (Fixation_1_id-Fixation_2_id-Distance)\n')
for i=1:(n_repeat_fixations-1)
fprintf(' %.f %.f %.3f \n',repeat_fixations(i,1),repeat_fixations(i,2),repeat_fixations(i,3))
end
end
fprintf(' Total duration of all fixations: %.1f\n',total_duration_fixations)
fprintf('\nSaccades Analysis:\n')
fprintf(' Total number of saccades: %.f\n',total_number_saccades)
if total_number_saccades>1
fprintf(' Saccades list:\n')
fprintf(' (ID-X_Start_Point-Y_Start_Point-X_End_Point-Y_End_Point-\n Duration-Amplitude-Direction_angle-Start_Fixation-End_Fixation)\n')
for i=1:total_number_saccades
fprintf(' %.f %.4f %.4f %.4f %.4f %.1f %.3f %.3f %.f %.f\n',i,saccades(i,1),saccades(i,2),saccades(i,3),saccades(i,4),saccades(i,5),saccades(i,6),saccades(i,7),saccades(i,8),saccades(i,9))
end
end
fprintf('\nScanpath Analysis:\n')
fprintf(' Scanpath length: %.3f\n',scanpath_length)
fprintf(' Scanpath duration: %.1f\n',scanpath_duration)
fprintf(' Saccades/Fixations Ratio: %.3f\n',ratio_sf)
fprintf(' Scanpath Spatial Density: %.3f\n',scanpath_density)
fprintf(' Transition Matrix:\n')
fprintf(' ')
for i=1:transition_dimension
fprintf('-%.f',i)
end
fprintf('\n')
for i=1:transition_dimension
fprintf(' %.f-',i)
for j=1:transition_dimension
fprintf(' %.f',transition_matrix(i,j))
end
fprintf('\n')
end
fprintf('Transition Density: %.3f\n',transition_density)
fprintf('________________________________________________________\n')
fprintf('\nEnd of Metrics Analysis Report\n')
fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
fprintf('\n')
fprintf(' This program is free software: you can redistribute it and/or modify\n')
fprintf(' it under the terms of the GNU General Public License as published by\n')
fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
fprintf(' (at your option) any later version.\n')
fprintf('\n')
fprintf(' This program is distributed in the hope that it will be useful,\n')
fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
fprintf(' GNU General Public License for more details.\n')
fprintf('\n')
fprintf(' You should have received a copy of the GNU General Public License\n')
fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
fprintf('\n')
fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end |
github | krasvas/LandRate-master | visualizations.m | .m | LandRate-master/visualizations.m | 4,618 | utf_8 | b86cb5e5590444b6dd3ba5d7f54d2128 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function visualizations
%export different visualizations in tracker units
%input parameters:
%-data: raw data corresponded to one stimuli
%-fixation_list: list of fixations(after fixation_detection)
%-maxr: maximum value of radius in tracker units to represent fixations durations
%call function example
%visualizations('data.txt',fixations_list,0.1)
function visualizations(data,fixations_list,maxr)
data=load(data);
%x,y,t
x=data(:,1);
y=data(:,2);
t=data(:,3);
%x_fix,y_fix,duration
x_fix=fixations_list(:,1);
y_fix=fixations_list(:,2);
duration=fixations_list(:,7);
n_fix=length(x_fix);
%x(t),y(t) visualizations
figure
plot(t,x,'r-')
hold on
plot(t,y,'b-')
title('Horizontal and Vertical Coordinates along Time','Color','k','FontSize',14)
xlabel('Time','Color','k','FontSize',12)
ylabel('Coordinates','Color','k','FontSize',12)
legend('x(t)','y(t)','Location','SouthEastOutside')
grid on
%raw data visualization
figure
plot(x,y,'r+')
title('Raw Data Distribution','Color','k','FontSize',14)
xlabel('Horizontal Coordinate','Color','k','FontSize',12)
ylabel('Vertical Coordinate','Color','k','FontSize',12)
hold on
plot(x,y,'b--')
axis('equal')
legend('Record Point','Records Trace','Location','SouthEastOutside')
grid on
%space-time-cube
figure
plot3(x,y,t,'r','LineWidth',1.5)
hold on
plot3(x,y,t,'b+')
title('Space-Time-Cube','Color','k','FontSize',14)
xlabel('Horizontal Coordinate','Color','k','FontSize',12)
ylabel('Vertical Coordinate','Color','k','FontSize',12)
zlabel('Time','Color','k','FontSize',12)
legend('Records Trace','Record Point','Location','SouthEastOutside')
grid on
%Scanpath visualization
figure
plot(x_fix,y_fix,'gs')
hold on
plot(x_fix,y_fix,'-b')
title('Scanpath (Fixations Duration & Saccades) ','Color','k','FontSize',14)
axis('equal')
%create circle points
c=linspace(0,2*pi);
%compute maxr_par
maxr_par=maxr/max(sqrt(duration)); %max r corresponds to max duration
for i=1:n_fix
hold on
%create circle with duration
x_center=x_fix(i);
y_center=y_fix(i);
xc=(maxr_par*sqrt(duration(i)))*cos(c);
yc=(maxr_par*sqrt(duration(i)))*sin(c);
fill(x_center+xc,y_center+yc,'r');
text(x_center,y_center,num2str(i),'HorizontalAlignment','Left','VerticalAlignment','Bottom','Color','m')
end
alpha(0.6)
legend('Fixation Center','Saccade','Radius represents the duration','Location','SouthEastOutside')
xlabel('Horizontal Coordinate','Color','k','FontSize',10)
ylabel('Vertical Coordinate','Color','k','FontSize',10)
fprintf('\nVisualizations are plotted successfully\n')
fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
fprintf('\n')
fprintf(' This program is free software: you can redistribute it and/or modify\n')
fprintf(' it under the terms of the GNU General Public License as published by\n')
fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
fprintf(' (at your option) any later version.\n')
fprintf('\n')
fprintf(' This program is distributed in the hope that it will be useful,\n')
fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
fprintf(' GNU General Public License for more details.\n')
fprintf('\n')
fprintf(' You should have received a copy of the GNU General Public License\n')
fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
fprintf('\n')
fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | krasvas/LandRate-master | saccade_analysis_EyeMMV_modified.m | .m | LandRate-master/saccade_analysis_EyeMMV_modified.m | 10,726 | utf_8 | da79190df4a2472a20a0d9e862b846b2 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function metrics_analysis
%eye movement metrics computations
%input parameters:
%-fixation_list: list of fixations(after fixation_detection)
%-repeat_fixation_threshold: threshold in tracker units for repeat fixations
%-spacing_scanpath: interval in tracker units to compute scanpath density
%-spacing_transition: interval in tracker units to compute transition matrix density
%-maxx: maximum horizontal coordinate in tracker coordinate system
%-maxy: maximum vertical coordinate in tracker coordinate system
%export matlab matrixes:
%-repeat_fixations: list of repeat fixations
%-saccades: list of saccadic movements
%-transition_matrix: transition matrix according the giving sapcing
%call function example:
%metrics_analysis(fixation_list,0.10,0.25,0.25,1.25,1.00);
%fixation_list:matlab matrix as computed from fixation_detection
%export saccade_list:[X_Start_Point][Y_Start_Point][X_End_Point][Y_End_Point][Duration][Amplitude][Direction_angle][Start_Fixation][End_Fixation])
function saccades=saccade_analysis_EyeMMV_modified(fixation_list)%,repeat_fixation_threshold,spacing_scanpath,spacing_transition,maxx,maxy)
%Fixation analysis
%compute total number of fixations
total_number_fixations=size(fixation_list);
total_number_fixations=total_number_fixations(1,1);
% %compute mean duration of fixations
% mean_durations_fixations=mean(fixation_list(:,7));
%
% %compute time to first fixation
% time_to_first_fixation=fixation_list(1,5);
% %compute repeat fixations
% %initialize distances between fixations(fixation1,fixation2,distance_between_two_fixations)
% distances_between_fixations=zeros(1,3);
% for i=1:total_number_fixations
% for j=1:total_number_fixations
% if i~=j && i<j
% distances_between_fixations=[distances_between_fixations;[i,j,(distance2p(fixation_list(i,1),fixation_list(i,2),fixation_list(j,1),fixation_list(j,2)))]];
% end
% end
% end
% n_distances_between_fixations=size(distances_between_fixations);
% n_distances_between_fixations=n_distances_between_fixations(1,1);
% distances_between_fixations=distances_between_fixations(2:n_distances_between_fixations,:);
% %initialize matrix of repeat fixations
% repeat_fixations=zeros(1,3);
% for i=1:(n_distances_between_fixations-1)
% if distances_between_fixations(i,3)<repeat_fixation_threshold
% repeat_fixations=[repeat_fixations;distances_between_fixations(i,:)];
% end
% end
%
% n_repeat_fixations=size(repeat_fixations);
% n_repeat_fixations=n_repeat_fixations(1,1);
% if n_repeat_fixations>1
% repeat_fixations=repeat_fixations(2:n_repeat_fixations,:);
% end
%
% %compute total duration of fixations
% total_duration_fixations=sum(fixation_list(:,7));
%Saccade analysis
%build saccades list (x_start_point,y_start_point,x_end_point,y_end_point, duration, amplitude, direction angle,start_fixation,end_fixation)
if total_number_fixations>2 || total_number_fixations==2
total_number_saccades=total_number_fixations-1;
%initialize saccades list
saccades=zeros(total_number_saccades,9);
j=2;%pointer
for i=1:(total_number_fixations-1)
%import start and end points in list
saccades(i,1)=fixation_list(i,1);
saccades(i,2)=fixation_list(i,2);
saccades(i,3)=fixation_list(j,1);
saccades(i,4)=fixation_list(j,2);
%compute saccades durations
saccades(i,5)=fixation_list(j,5)-fixation_list(i,6);
%compute amplitude
saccades(i,6)=distance2p(saccades(i,1),saccades(i,2),saccades(i,3),saccades(i,4));
%compute direction angle
saccades(i,7)=direction_angle(saccades(i,1),saccades(i,2),saccades(i,3),saccades(i,4));
%name start and end fixations in each saccade
saccades(i,8)=i;
saccades(i,9)=j;
j=j+1;
end
%compute mean duration of saccades
mean_durations_saccades=mean(saccades(:,5));
else
total_number_saccades=0;
end
% %Scanpath analysis
% %compute scanpath length
% scanpath_length=sum(saccades(:,6));
%
% %compute scanpath duration
% scanpath_duration=fixation_list(total_number_fixations,6)-fixation_list(1,5);
%
% %compute saccade/fixation ratio
% ratio_sf=sum(saccades(:,5))/sum(fixation_list(:,7));
%
% %compute scanpath spatial density
% %build points_areas_matrix(x,y,area_id)
% %initialize
% points_areas_matrix=zeros(1,3);
% for i=1:total_number_fixations
% area=find_point_area(fixation_list(i,1),fixation_list(i,2),maxx,maxy,spacing_scanpath);
% points_areas_matrix(i,1)=area(1);
% points_areas_matrix(i,2)=area(2);
% points_areas_matrix(i,3)=area(3);
%
% end
% n_scanpath_areas=area(4);
% %compute the number of unique areas between points areas
% number_different_areas=length(unique(points_areas_matrix(:,3)));
% %scanpath_density
% scanpath_density=number_different_areas/n_scanpath_areas;
%
% %create transition matrix
% %build fixation_transition_areas(x_fixation,y_fixation,x_center,y_center,transition_area)
% %initialize fixation_transition areas
% fixation_transition_areas=zeros(1,5);
% for i=1:total_number_fixations
% fixation_transition_areas(i,1)=fixation_list(i,1);
% fixation_transition_areas(i,2)=fixation_list(i,2);
% area=find_point_area(fixation_list(i,1),fixation_list(i,2),maxx,maxy,spacing_transition);
% fixation_transition_areas(i,3:5)=area(1:3);
% end
% %transitions
% transitions=fixation_transition_areas(:,5);
% %transition dimension corresponds to maximun number of areas
% transition_dimension=area(4);
% %build transition matrix(>=1:indicates transition, 0: indicates no transition)
% %initialize
% transition_matrix=zeros(transition_dimension);
%
% for i=1:(total_number_fixations-1)
% for j=1:transition_dimension
% if j==transitions(i)
% transition_matrix(transitions(i+1),j)=transition_matrix(transitions(i+1),j)+1;
% end
% end
% end
%
% %compute the number of transitions
% %initialize number
% number_transitions=0;
% for i=1:transition_dimension
% for j=1:transition_dimension
% if transition_matrix(i,j)>0
% number_transitions=number_transitions+1;
% end
% end
% end
%
% %compute transition density
% transition_density=number_transitions/(transition_dimension^2);
%
%
% %print results
% fprintf('Eye Movement metrics analysis\n\n')
% fprintf('Input Parameters: \n')
% fprintf(' Threshold for repeat fixations: %.3f\n',repeat_fixation_threshold)
% fprintf(' Scanpath spacing (spatial density computation): %.3f\n',spacing_scanpath)
% fprintf(' Transition matrix spacing: %.3f\n',spacing_transition)
%
% fprintf('\nFixation Metrics Analysis:\n')
% fprintf(' Total number of fixations: %.f\n',total_number_fixations)
% fprintf(' Mean duration of fixations: %.1f\n',mean_durations_fixations)
% fprintf(' Time to first fixation: %.1f\n',time_to_first_fixation)
% if n_repeat_fixations>1
% fprintf(' Repeat Fixations:\n')
% fprintf(' (Fixation_1_id-Fixation_2_id-Distance)\n')
% for i=1:(n_repeat_fixations-1)
% fprintf(' %.f %.f %.3f \n',repeat_fixations(i,1),repeat_fixations(i,2),repeat_fixations(i,3))
% end
% end
% fprintf(' Total duration of all fixations: %.1f\n',total_duration_fixations)
%
% fprintf('\nSaccades Analysis:\n')
% fprintf(' Total number of saccades: %.f\n',total_number_saccades)
% if total_number_saccades>1
% fprintf(' Saccades list:\n')
% fprintf(' (ID-X_Start_Point-Y_Start_Point-X_End_Point-Y_End_Point-\n Duration-Amplitude-Direction_angle-Start_Fixation-End_Fixation)\n')
% for i=1:total_number_saccades
% fprintf(' %.f %.4f %.4f %.4f %.4f %.1f %.3f %.3f %.f %.f\n',i,saccades(i,1),saccades(i,2),saccades(i,3),saccades(i,4),saccades(i,5),saccades(i,6),saccades(i,7),saccades(i,8),saccades(i,9))
% end
% end
%
% fprintf('\nScanpath Analysis:\n')
% fprintf(' Scanpath length: %.3f\n',scanpath_length)
% fprintf(' Scanpath duration: %.1f\n',scanpath_duration)
% fprintf(' Saccades/Fixations Ratio: %.3f\n',ratio_sf)
% fprintf(' Scanpath Spatial Density: %.3f\n',scanpath_density)
% fprintf(' Transition Matrix:\n')
% fprintf(' ')
% for i=1:transition_dimension
% fprintf('-%.f',i)
% end
% fprintf('\n')
% for i=1:transition_dimension
% fprintf(' %.f-',i)
% for j=1:transition_dimension
% fprintf(' %.f',transition_matrix(i,j))
% end
% fprintf('\n')
% end
% fprintf('Transition Density: %.3f\n',transition_density)
% fprintf('________________________________________________________\n')
% fprintf('\nEnd of Metrics Analysis Report\n')
%
%
% fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
% fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
% fprintf('\n')
% fprintf(' This program is free software: you can redistribute it and/or modify\n')
% fprintf(' it under the terms of the GNU General Public License as published by\n')
% fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
% fprintf(' (at your option) any later version.\n')
% fprintf('\n')
% fprintf(' This program is distributed in the hope that it will be useful,\n')
% fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
% fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
% fprintf(' GNU General Public License for more details.\n')
% fprintf('\n')
% fprintf(' You should have received a copy of the GNU General Public License\n')
% fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
% fprintf('\n')
% fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end |
github | krasvas/LandRate-master | find_point_area.m | .m | LandRate-master/find_point_area.m | 2,943 | utf_8 | bf1a31dbfba11e00783fb8c1b8ad7345 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function find_point_area
%input parameters
%(x,y): coordinates of point
%max_hor: maximum horizontal dimension of coordinate system
%max_ver: maximum vertical dimension of coordinate system
%spacing: spacing parameter to create transition matrix
%export Point_area(x_center,y_center,area,maximum_number_of_areas)
function Point_area=find_point_area(x,y,max_hor,max_ver,spacing)
hor_spacing=[0:spacing:max_hor];
ver_spacing=[0:spacing:max_ver];
%build matrix with the coordinates of centers of transition matrix squares
%initialization (x,y,ID)
centers=zeros((length(hor_spacing)-1)*(length(ver_spacing)-1),3);
centers(1,1)=spacing/2;
centers(1,2)=spacing/2;
for i=2:(length(hor_spacing)-1)
centers(i,1)=centers(i-1,1)+spacing;
centers(i,2)=centers(1,2);
end
for i=length(hor_spacing):length(hor_spacing)-1:((length(hor_spacing)-1)*(length(ver_spacing)-1))
centers(i:(i-2+length(hor_spacing)),1)=centers(1:(length(hor_spacing)-1),1);
centers(i:(i-2+length(hor_spacing)),2)=centers((i-((length(hor_spacing)-1))):(i-1),2)+spacing;
end
%create areas id
%the matrix centers contains the square areas (x_center,y_center,id) of transition matrix
for i=1:(length(hor_spacing)-1)*(length(ver_spacing)-1)
centers(i,3)=i;
end
%compute number of areas
n_areas=(length(hor_spacing)-1)*(length(ver_spacing)-1);
%find in which area the point is located
%compute distances between point and centers
%initialize distances(distance center from point,x_center,y_center,area)
distances=zeros(n_areas,4);
for i=1:n_areas
distances(i,1)=distance2p(x,y,centers(i,1),centers(i,2));
distances(i,2)=centers(i,1);
distances(i,3)=centers(i,2);
distances(i,4)=centers(i,3);
end
%the area corresponds to the minimum value of distance
min_value=min(distances(:,1));
%find point corresponded center
for i=1:n_areas
if distances(i,1)==min_value
Point_area=distances(i,2:4);
end
end
%maximun number of areas
Point_area=[Point_area,n_areas];
end
|
github | krasvas/LandRate-master | scan_path_visualization_EyeMMV_modified.m | .m | LandRate-master/scan_path_visualization_EyeMMV_modified.m | 5,064 | utf_8 | b33ae032caf71d2aec57f5b53ebe1667 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function visualizations
%export different visualizations in tracker units
%input parameters:
%-data: raw data corresponded to one stimuli
%-fixation_list: list of fixations(after fixation_detection)
%-maxr: maximum value of radius in tracker units to represent fixations durations
%call function example
%visualizations('data.txt',fixations_list,0.1)
function scan_path_visualization_EyeMMV_modified(fixations_list, maxr)
% data=load(data);
% %x,y,t
% x=data(:,1);
% y=data(:,2);
% t=data(:,3);
%x_fix,y_fix,duration
x_fix=fixations_list(:,1);
y_fix=fixations_list(:,2);
duration=fixations_list(:,7);
n_fix=length(x_fix);
% %x(t),y(t) visualizations
% figure
% plot(t,x,'r-')
% hold on
% plot(t,y,'b-')
% title('Horizontal and Vertical Coordinates along Time','Color','k','FontSize',14)
% xlabel('Time','Color','k','FontSize',12)
% ylabel('Coordinates','Color','k','FontSize',12)
% legend('x(t)','y(t)','Location','SouthEastOutside')
% grid on
%
% %raw data visualization
% figure
% plot(x,y,'r+')
% title('Raw Data Distribution','Color','k','FontSize',14)
% xlabel('Horizontal Coordinate','Color','k','FontSize',12)
% ylabel('Vertical Coordinate','Color','k','FontSize',12)
% hold on
% plot(x,y,'b--')
% axis('equal')
% legend('Record Point','Records Trace','Location','SouthEastOutside')
% grid on
%
% %space-time-cube
% figure
% plot3(x,y,t,'r','LineWidth',1.5)
% hold on
% plot3(x,y,t,'b+')
% title('Space-Time-Cube','Color','k','FontSize',14)
% xlabel('Horizontal Coordinate','Color','k','FontSize',12)
% ylabel('Vertical Coordinate','Color','k','FontSize',12)
% zlabel('Time','Color','k','FontSize',12)
% legend('Records Trace','Record Point','Location','SouthEastOutside')
% grid on
%imshow(stimulus,'InitialMagnification','fit')
hold on
%Scanpath visualization
plot(x_fix,y_fix,'gs')
hold on
plot(x_fix,y_fix,'-b')
%title('Scanpath (Fixations Duration & Saccades) ','Color','k','FontSize',14)
%create circle points
c=linspace(0,2*pi);
%compute maxr_par
maxr_par=maxr/max(sqrt(duration)); %max r corresponds to max duration
for i=1:n_fix
hold on
%create circle with duration
x_center=x_fix(i);
y_center=y_fix(i);
xc=(maxr_par*sqrt(duration(i)))*cos(c);
yc=(maxr_par*sqrt(duration(i)))*sin(c);
fill(x_center+xc,y_center+yc,'r');
text(x_center,y_center,num2str(duration(i)),'HorizontalAlignment','Left','VerticalAlignment','Bottom','Color','y')
end
alpha(0.8)
hold on
%show start and end fixation point
text(x_fix(1),y_fix(1),'START','HorizontalAlignment','Left','VerticalAlignment','top','Color','c')
hold on
text(x_fix(n_fix),y_fix(n_fix),'END','HorizontalAlignment','Left','VerticalAlignment','top','Color','c')
% legend('Fixation Center','Saccade','Radius represents the duration','Location','SouthEastOutside')
% xlabel('Horizontal Coordinate','Color','k','FontSize',10)
% ylabel('Vertical Coordinate','Color','k','FontSize',10)
% fprintf('\nVisualizations are plotted successfully\n')
% fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
% fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
% fprintf('\n')
% fprintf(' This program is free software: you can redistribute it and/or modify\n')
% fprintf(' it under the terms of the GNU General Public License as published by\n')
% fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
% fprintf(' (at your option) any later version.\n')
% fprintf('\n')
% fprintf(' This program is distributed in the hope that it will be useful,\n')
% fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
% fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
% fprintf(' GNU General Public License for more details.\n')
% fprintf('\n')
% fprintf(' You should have received a copy of the GNU General Public License\n')
% fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
% fprintf('\n')
% fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | krasvas/LandRate-master | distance2p.m | .m | LandRate-master/distance2p.m | 1,124 | utf_8 | cd76c27ed4b3f0855a9ff19c2bddc429 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%distance between 2 points
%point 1(x1,y1)
%point 2(x2,y2)
function distance2p=distance2p(x1,y1,x2,y2)
dx=x2-x1;
dy=y2-y1;
distance2p=sqrt((dx^2)+(dy^2));
end |
github | krasvas/LandRate-master | values_normalization.m | .m | LandRate-master/values_normalization.m | 148 | utf_8 | dff1706d74406c28b86fb02ac727bfc4 | %Values normalization function between 0 and 1
function normalized_values=values_normalization(values)
normalized_values=values./max(values);
end |
github | krasvas/LandRate-master | direction_angle.m | .m | LandRate-master/direction_angle.m | 1,372 | utf_8 | 36805f28c8d3616a761d5db8a6e1dfe7 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%calculate direction angle(grads & degrees)
%export direction angle in degrees
function a12=direction_angle(x1,y1,x2,y2)
dx=x2-x1;
dy=y2-y1;
a=(200/pi())*atan(abs(dx)/abs(dy));
a=abs(a);
a12=a;
if dx>0 & dy>0
a12=a;
elseif dx>0 & dy<0
a12=200-a;
elseif dx<0 & dy<0
a12=200+a;
elseif dx<0 & dy>0
a12=400-a;
else
a12=a;
end
if a12>400
a12=a12-400;
end
if a12<0
a12=a12+400;
end
a12=(360/400)*a12;
end |
github | krasvas/LandRate-master | fixation_detection_EyeMMV_modified.m | .m | LandRate-master/fixation_detection_EyeMMV_modified.m | 8,663 | utf_8 | c5aff6169465d2a52873e3049320b768 | % This is a modified version of EyeMMV's toolbox fixation detection
% algorithm
% EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function fixation_detection
%detect fixations from raw data
%input parameters:
%-data:raw data (x y t),x,y: in tracker units(cartesian coordinate system),t: time in ms
%-t1: spatial parameter t1 in tracker units
%-t2: spatial parameter t2 in tracker units
%-minDur: minimum value of fixation duration in ms
%-maxx: maximum horizontal coordinate in tracker coordinate system
%-maxy: maximum vertical coordinate in tracker coordinate system
%export matlab matrixes:
%-fixation_list_t2:list of fixations info computed with t1,t2,minDur criteria
%-fixation_list_3s:list of fixations info computed with t1,3s,minDur criteria
%call function example:
%fixation_detection('data.txt',0.250,0.100,150,1.25,1.00);
function final_fixation_list=fixation_detection_EyeMMV_modified(data,t1,t2,minDur,maxx,maxy,fixation_method)
%read data according to the new format
x=data(:,3);
y=data(:,4);
t=data(:,2);
%adapt new format in EyeMMV's required format
data=[x y t];
x=data(:,1);
y=data(:,2);
t=data(:,3);
n=length(t);
%build initial fixations list
%categorize each data point to a fixation cluster according to tolerance 1
fixations=[data,zeros(n,1)];
%initialize pointers
fixid=1; %fixation id
mx=0; %mean coordinate x
my=0; %mean coordinate y
d=0; %dinstance between data point and mean point
fixpointer=1; %fixations pointer
for i=1:n
mx=mean(x(fixpointer:i));
my=mean(y(fixpointer:i));
d=distance2p(mx,my,x(i),y(i));
if d>t1
fixid=fixid+1;
fixpointer=i;
end
fixations(i,4)=fixid;
end
%end of clustering according to tolerance 1
%number of fixation after clustering (t1)
number_fixations=fixations(n,4);
%initialize fixations list according spatial criteria
%(Center x, Center y, Number of data points after t1, Number of data points
%after second criterion, Start time, End time, Duration)
fixation_list_t2=zeros(1,7);
fixation_list_3s=zeros(1,7);
%initialize the list of points which are not participate in fixation analysis
list_of_out_points=[0 0 0 -1];
%print fixation list according to spatial criteria
for i=1:number_fixations
[centerx_t2,centery_t2,n_t1_t2,n_t2,t1_t2,t2_t2,d_t2,out_points]=fixations_t2(fixations,i,t2);
[centerx_3s,centery_3s,n_t1_3s,n_3s,t1_3s,t2_3s,d_3s]=fixations_3s(fixations,i);
%build list(t2)
fixation_list_t2(i,1)=centerx_t2;
fixation_list_t2(i,2)=centery_t2;
fixation_list_t2(i,3)=n_t1_t2;
fixation_list_t2(i,4)=n_t2;
fixation_list_t2(i,5)=t1_t2;
fixation_list_t2(i,6)=t2_t2;
fixation_list_t2(i,7)=d_t2;
%build list(3s)
fixation_list_3s(i,1)=centerx_3s;
fixation_list_3s(i,2)=centery_3s;
fixation_list_3s(i,3)=n_t1_3s;
fixation_list_3s(i,4)=n_3s;
fixation_list_3s(i,5)=t1_3s;
fixation_list_3s(i,6)=t2_3s;
fixation_list_3s(i,7)=d_3s;
%build list of points which are not used
list_of_out_points=[list_of_out_points;out_points];
end
%remove from list of out points the zeros records
n_out=size(list_of_out_points);
n_out=n_out(1,1);
list=zeros(1,4);
for i=1:n_out
if list_of_out_points(i,4)==0
list=[list;list_of_out_points(i,:)];
end
end
n_list=size(list);
n_list=n_list(1,1);
if n_out>1
list_of_out_points=list(2:n_list,:);
else
list_of_out_points=0;
end
%applying duration threshold
fixation_list_t2=min_duration(fixation_list_t2,minDur);
fixation_list_3s=min_duration(fixation_list_3s,minDur);
%export results
n_t2=size(fixation_list_t2);
n_t2=n_t2(1,1);
n_3s=size(fixation_list_3s);
n_3s=n_3s(1,1);
if fixation_method=='t2'
final_fixation_list=fixation_list_t2;
elseif fixation_method=='3s'
final_fixation_list=fixation_list_3s;
end
% fprintf(' Fixation Detection Report \n\n')
% fprintf('Import Parameters: \n')
% fprintf(' Spatial Parameter t1: %.3f\n',t1)
% fprintf(' Spatial Parameter t2: %.3f\n',t2)
% fprintf(' Minimum Fixation Duration: %.2f\n',minDur)
% fprintf(' Maximum Coordinate in Horizontal Dimension: %.2f\n',maxx)
% fprintf(' Maximum Coordinate in Vertical Dimension: %.2f\n\n',maxy)
%
% fprintf('Number of Raw Data: %.f\n',n)
% fprintf('Number of Data used in the analysis(t1,t2,minDur): %.f\n',sum(fixation_list_t2(:,4)))
% fprintf('Number of Data used in the analysis(t1,3s,minDur): %.f\n',sum(fixation_list_t2(:,4)))
%
% fprintf('\nFixations: \n')
% fprintf(' Total Number of Fixations(t1,t2,minDur): %.f\n',n_t2)
% fprintf(' Total Number of Fixations(t1,3s,minDur): %.f\n',n_3s)
%
% fprintf('\nt1,t2,minDur:\n')
% fprintf(' ID-Xcenter-Ycenter-Nt1-Nt2-StartTime-EndTime-Duration\n')
% for i=1:n_t2
% fprintf(' %.f %.4f %.4f %.f %.f %.4f %.4f %.4f\n',i,fixation_list_t2(i,1),fixation_list_t2(i,2),fixation_list_t2(i,3),fixation_list_t2(i,4),fixation_list_t2(i,5),fixation_list_t2(i,6),fixation_list_t2(i,7))
% end
% fprintf('\n')
% fprintf('t1,3s,minDur:\n')
% fprintf(' ID-Xcenter-Ycenter-Nt1-N3s-StartTime-EndTime-Duration\n')
% for i=1:n_3s
% fprintf(' %.f %.4f %.4f %.f %.f %.4f %.4f %.4f\n',i,fixation_list_3s(i,1),fixation_list_3s(i,2),fixation_list_3s(i,3),fixation_list_3s(i,4),fixation_list_3s(i,5),fixation_list_3s(i,6),fixation_list_3s(i,7))
% end
%
%
% %plot records and fixations
% figure
% plot(x,y,'co')
% set(gca,'Fontsize',20)
% hold on
% plot(fixation_list_t2(:,1),fixation_list_t2(:,2),'r+')
% text(fixation_list_t2(:,1),fixation_list_t2(:,2),num2str(fixation_list_t2(:,7)),'HorizontalAlignment','Left','VerticalAlignment','Bottom','FontSize',20,'Color','r')
% hold on
% plot(fixation_list_3s(:,1),fixation_list_3s(:,2),'bs')
% text(fixation_list_3s(:,1),fixation_list_3s(:,2),num2str(fixation_list_3s(:,7)),'HorizontalAlignment','Right','VerticalAlignment','Top','FontSize',20,'Color','b')
% hold on
% plot(list_of_out_points(:,1),list_of_out_points(:,2),'go')
% legend('Raw Data','Fixations (t1, t2, minDur)','Fixations (t1, 3s, minDur)','Points out of analysis (t1,t2,minDur)','Location','Best')
% title(['Raw Data and Fixations (t1=',num2str(t1),', t2=',num2str(t2),', minDur=',num2str(minDur),')'],'FontSize',20)
% xlabel('Horizontal Coordinate','Color','k','FontSize',20)
% ylabel('Vertical Coordinate','Color','k','FontSize',20)
% axis('equal')
% %plot screen outline
% screen=[0,0;maxx,0;maxx,maxy;0,maxy;0,0]; %sreen region
% hold on
% plot(screen(:,1),screen(:,2),'-r')
%
% fprintf('\n Raw Data and Fixations are visualized successfully\n')
% fprintf('________________________________________________________\n')
%
% fprintf('End of Fixation Detection report\n')
%
%
% fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
% fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
% fprintf('\n')
% fprintf(' This program is free software: you can redistribute it and/or modify\n')
% fprintf(' it under the terms of the GNU General Public License as published by\n')
% fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
% fprintf(' (at your option) any later version.\n')
% fprintf('\n')
% fprintf(' This program is distributed in the hope that it will be useful,\n')
% fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
% fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
% fprintf(' GNU General Public License for more details.\n')
% fprintf('\n')
% fprintf(' You should have received a copy of the GNU General Public License\n')
% fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
% fprintf('\n')
% fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | krasvas/LandRate-master | visualizations_stimulus.m | .m | LandRate-master/visualizations_stimulus.m | 4,473 | utf_8 | f29efbcf0b0c5b77cde3750f23f30b48 | % EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool.
% Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens)
%
% 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 <http://www.gnu.org/licenses/>.
%
% For further information, please email me: [email protected] or [email protected]
%function visualizations_stimulus
%export different visualizations with stimulus image
%input parameters:
%-data: raw data corresponded to one stimuli
%-stimulus: stimulus image
%-fixation_list: list of fixations(after fixation_detection)
%-maxr: maximum value of radius in pixels to represent fixations durations
%call function example
%visualizations_stimulus('data.txt','stimulus.bmp',fixations_list,100)
function visualizations_stimulus(data,stimulus,fixations_list,maxr);
data=load(data);
stimulus=imread(stimulus);
%x,y,t
x=data(:,1);
y=data(:,2);
t=data(:,3);
%x_fix,y_fix,duration
x_fix=fixations_list(:,1);
y_fix=fixations_list(:,2);
duration=fixations_list(:,7);
n_fix=length(x_fix);
%stimulus_size
stimulus_size=size(stimulus);
stimulus_vertical_size=stimulus_size(1,1);
stimulus_horizontal_size=stimulus_size(1,2);
%transform data to pixel coordinate system
x=stimulus_vertical_size*x;
y=stimulus_vertical_size*(1-y);
x_fix=stimulus_vertical_size*x_fix;
y_fix=stimulus_vertical_size*(1-y_fix);
%raw data visualization
figure
imshow(stimulus)
hold on
plot(x,y,'r+')
title('Raw Data Distribution','Color','k','FontSize',14)
xlabel('Horizontal Coordinate','Color','k','FontSize',12)
ylabel('Vertical Coordinate','Color','k','FontSize',12)
hold on
plot(x,y,'b--')
axis('equal')
legend('Record Point','Records Trace','Location','SouthEastOutside')
%Scanpath visualization
figure
imshow(stimulus)
hold on
plot(x_fix,y_fix,'gs')
hold on
plot(x_fix,y_fix,'-b')
title('Scanpath (Fixations Duration & Saccades) ','Color','k','FontSize',14)
axis('equal')
%create circle points
c=linspace(0,2*pi);
%compute maxr_par
maxr_par=maxr/max(sqrt(duration)); %max r corresponds to max duration
for i=1:n_fix
hold on
%create circle with duration
x_center=x_fix(i);
y_center=y_fix(i);
xc=(maxr_par*sqrt(duration(i)))*cos(c);
yc=(maxr_par*sqrt(duration(i)))*sin(c);
fill(x_center+xc,y_center+yc,'r');
text(x_center,y_center,num2str(i),'HorizontalAlignment','Left','VerticalAlignment','Bottom','Color','m')
end
alpha(0.6)
legend('Fixation Center','Saccade','Radius represents the duration','Location','SouthEastOutside')
xlabel('Horizontal Coordinate','Color','k','FontSize',10)
ylabel('Vertical Coordinate','Color','k','FontSize',10)
fprintf('\nVisualizations are plotted successfully\n')
fprintf('\nVisualizations with stimulus are plotted successfully\n')
fprintf('\n EyeMMV toolbox (Eye Movements Metrics & Visualizations): An eye movement post-analysis tool. \n')
fprintf(' Copyright (C) 2014 Vassilios Krassanakis (National Technical University of Athens) \n')
fprintf('\n')
fprintf(' This program is free software: you can redistribute it and/or modify\n')
fprintf(' it under the terms of the GNU General Public License as published by\n')
fprintf(' the Free Software Foundation, either version 3 of the License, or\n')
fprintf(' (at your option) any later version.\n')
fprintf('\n')
fprintf(' This program is distributed in the hope that it will be useful,\n')
fprintf(' but WITHOUT ANY WARRANTY; without even the implied warranty of\n')
fprintf(' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n')
fprintf(' GNU General Public License for more details.\n')
fprintf('\n')
fprintf(' You should have received a copy of the GNU General Public License\n')
fprintf(' along with this program. If not, see <http://www.gnu.org/licenses/>.\n')
fprintf('\n')
fprintf(' For further information, please email me: [email protected] or [email protected]\n')
end
|
github | tomluc/Pinax-camera-model-master | RayTrace.m | .m | Pinax-camera-model-master/MATLAB/Optimal_d_0/RayTrace.m | 1,672 | utf_8 | cf6dfb029293b40cc5f65303955b0b07 | %
% Copyright (c) 2017 Jacobs University Robotics Group
% All rights reserved.
%
%
% Unless specified otherwise this code examples are released under
% Creative Commons CC BY-NC-ND 4.0 license (free for non-commercial use).
% Details may be found here: https://creativecommons.org/licenses/by-nc-nd/4.0/
%
%
% If you are interested in using this code commercially,
% please contact us.
%
% THIS SOFTWARE IS PROVIDED BY Jacobs Robotics ``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 Jacobs Robotics 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.
%
% Contact: [email protected]
%
function [refPts]=RayTrace (ray0, normal, mu, mu2, d0, d1,zero)
v0=ray0/norm(ray0);
normal=normal/norm(normal);
pi=zero+ d0*v0/(v0'*normal);
normal=-normal;
c=-normal'*v0;
rglass=1/mu;
rwater=1/mu2;
v1=rglass*v0+(rglass*c -sqrt(1-rglass^2*(1-c^2)))*normal;
v2=rwater*v0+(rwater*c -sqrt(1-rwater^2*(1-c^2)))*normal;
normal=-normal;
po=pi+ d1*v1/(v1'*normal);
v1=v1/norm(v1);
v2=v2/norm(v2);
refPts=[v0;pi;v1;po;v2];
end |
github | tomluc/Pinax-camera-model-master | optim_d_0.m | .m | Pinax-camera-model-master/MATLAB/Optimal_d_0/optim_d_0.m | 1,848 | utf_8 | f357020570d91223d794d7378da9c884 | %
% Copyright (c) 2017 Jacobs University Robotics Group
% All rights reserved.
%
%
% Unless specified otherwise this code examples are released under
% Creative Commons CC BY-NC-ND 4.0 license (free for non-commercial use).
% Details may be found here: https://creativecommons.org/licenses/by-nc-nd/4.0/
%
%
% If you are interested in using this code commercially,
% please contact us.
%
% THIS SOFTWARE IS PROVIDED BY Jacobs Robotics ``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 Jacobs Robotics 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.
%
% Contact: [email protected]
function [diff] = optim_d_0(x)
global dmax dmin K d1 ng nw dif
d0=x;
ImgPts=zeros(3,300);
for i=1:20
for j=1:15
ImgPts(1,(j-1)*20+i)=50*i;
ImgPts(2,(j-1)*20+i)=50*j;
ImgPts(3,(j-1)*20+i)=1;
end
end
ZeroRays=inv(K)*ImgPts;
normal=[0;0;1];
t=[0;0;0];
dmin=9999;
dmax=-9999;
for i=1:300
xl= RayTrace (ZeroRays(:,i), normal, ng, nw, d0, d1,t);
xl=xl(:);
po=[xl(10);xl(11);xl(12)];
v2=[xl(13);xl(14);xl(15)];
pom=abs(po(3)-v2(3)*(po(1)/(2*v2(1)) + po(2)/(2*v2(2))));
dmin=min(dmin,pom);
dmax=max(dmax,pom);
end
dif=dmax-dmin;
diff=dif;
|
github | tomluc/Pinax-camera-model-master | SolveForwardProjectionCase3.m | .m | Pinax-camera-model-master/MATLAB/Find_correction_map/SolveForwardProjectionCase3.m | 5,661 | utf_8 | 7d7e2e3c69273bfc11e9f03096a468ec |
% Copyright 2009 Mitsubishi Electric Research Laboratories All Rights Reserved.
%
% Permission to use, copy and modify this software and its documentation without fee for educational, research and non-profit purposes, is hereby granted, provided that the above copyright notice and the following three paragraphs appear in all copies.
%
% To request permission to incorporate this software into commercial products contact: Vice President of Marketing and Business Development; Mitsubishi Electric Research Laboratories (MERL), 201 Broadway, Cambridge, MA 02139 or <[email protected]>.
%
% IN NO EVENT SHALL MERL BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF MERL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
%
% MERL SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND MERL HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS OR MODIFICATIONS.
%
% Solve Forward projection equation for Case 3 (two layer) (Air-Medium1-Medium2)
% d is the distance of medium1 from camera
% d2 is the total distance of medium2 from camera
% p is given 3D point
% n is the normal
% mu is refractive index vector
% M is the 3D point on the layer closest to camera where the first
% refraction happens
function [M] = SolveForwardProjectionCase3(d,d2,n,mu,p)
mu1 = mu(1,1);
mu2 = mu(2,1);
M = [0;0;1];
%find POR the plane of refraction
POR = cross(n,p);
POR = POR/norm(POR);
% [z1,z2] defines a coordinate system on POR
% axis is away from the camera. z1 is along the axis
z1 = -n;
z1 = z1/norm(z1);
% find z2
z2 = cross(POR,z1);
z2 = z2/norm(z2);
% find the projection of given 3D point on POR
v = p'*z1;
u = p'*z2;
%solve 12thth degree equation
s1 = (mu1^2 - 1)^2*(mu2^2 - 1)^2;
s2 = (-4)*u*(mu1^2 - 1)^2*(mu2^2 - 1)^2;
s3 = 4*u^2*(mu1^2 - 1)^2*(mu2^2 - 1)^2 + 2*(mu1^2 - 1)*(mu2^2 - 1)*((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1));
s4 = - 2*(mu1^2 - 1)*(mu2^2 - 1)*(2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1)) - 4*u*(mu1^2 - 1)*(mu2^2 - 1)*((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1));
s5 = ((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1))^2 + 2*(mu1^2 - 1)*(mu2^2 - 1)*(d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1)) - 4*(mu1^2 - 1)*(mu2^2 - 1)*(d - d2)^2*(d2 - v)^2 + 4*u*(mu1^2 - 1)*(mu2^2 - 1)*(2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1));
s6 = -2*(2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1))*((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1)) - 4*u*(mu1^2 - 1)*(mu2^2 - 1)*(d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1)) - 4*d^4*mu1^2*mu2^2*u*(mu1^2 - 1)*(mu2^2 - 1);
s7 = 2*((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1))*(d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1)) + (2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1))^2 - 4*(d - d2)^2*(d^2*mu1^2*(mu2^2 - 1) + d^2*mu2^2*(mu1^2 - 1))*(d2 - v)^2 + 10*d^4*mu1^2*mu2^2*u^2*(mu1^2 - 1)*(mu2^2 - 1);
s8 = -2*(2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1))*(d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1)) - 4*d^4*mu1^2*mu2^2*u*((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1)) - 4*d^4*mu1^2*mu2^2*u^3*(mu1^2 - 1)*(mu2^2 - 1);
s9 = (d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1))^2 + 2*d^4*mu1^2*mu2^2*u^2*((mu2^2 - 1)*(u^2*(mu1^2 - 1) + d^2*mu1^2) - (mu2^2 - 1)*(d - d2)^2 - (mu1^2 - 1)*(d2 - v)^2 + d^2*mu2^2*(mu1^2 - 1)) - 4*d^4*mu1^2*mu2^2*(d - d2)^2*(d2 - v)^2 + 4*d^4*mu1^2*mu2^2*u*(2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1));
s10 = - 2*d^4*mu1^2*mu2^2*u^2*(2*d^2*mu1^2*u*(mu2^2 - 1) + 2*d^2*mu2^2*u*(mu1^2 - 1)) - 4*d^4*mu1^2*mu2^2*u*(d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1));
s11 = 4*d^8*mu1^4*mu2^4*u^2 + 2*d^4*mu1^2*mu2^2*u^2*(d^2*mu2^2*(u^2*(mu1^2 - 1) + d^2*mu1^2) - d^2*mu2^2*(d - d2)^2 - d^2*mu1^2*(d2 - v)^2 + d^2*mu1^2*u^2*(mu2^2 - 1));
s12 = (-4)*d^8*mu1^4*mu2^4*u^3;
s13 = d^8*mu1^4*mu2^4*u^4;
%[s1;s2;s3;s4;s5;s6;s7;s8;s9;s10;s11;s12;s13]
sol = roots([s1;s2;s3;s4;s5;s6;s7;s8;s9;s10;s11;s12;s13]);
idx = find(abs(imag(sol)) < 1e-6);
if(isempty(idx))
disp('no solution');
return
end
sol1 = sol(idx);
nn = size(sol1,1);
Normal = [0;-1];
for ii = 1:nn
x = sol1(ii,1);
vi = [x;d];
v2 = RefractedRay(vi,Normal,1,mu1);
q2 = vi + (d-d2)*v2/(v2'*Normal);
v3 = RefractedRay(v2,Normal,mu1,mu2);
vrd = [u;v] - q2;
e = abs(vrd(1)*v3(2) - vrd(2)*v3(1));
if(e < 1e-4)
M = x*z2 + d*z1;
return
end
end
|
github | tomluc/Pinax-camera-model-master | RayTrace.m | .m | Pinax-camera-model-master/MATLAB/Find_correction_map/RayTrace.m | 1,681 | utf_8 | 9a53429738aea5dd3b07e1a43324ac47 | %
% Copyright (c) 2017 Jacobs University Robotics Group
% All rights reserved.
%
%
% Unless specified otherwise this code examples are released under
% Creative Commons CC BY-NC-ND 4.0 license (free for non-commercial use).
% Details may be found here: https://creativecommons.org/licenses/by-nc-nd/4.0/
%
%
% If you are interested in using this code commercially,
% please contact us.
%
% THIS SOFTWARE IS PROVIDED BY Jacobs Robotics ``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 Jacobs Robotics 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.
%
% Contact: [email protected]
%
function [refPts]=RayTrace (ray0, normal, mu, mu2, d0, d1,zero)
v0=ray0/norm(ray0);
normal=normal/norm(normal);
pi=zero+ d0*v0/(v0'*normal);
normal=-normal;
c=-normal'*v0;
rglass=1/mu;
rwater=1/mu2;
v1=rglass*v0+(rglass*c -sqrt(1-rglass^2*(1-c^2)))*normal;
v2=rwater*v0+(rwater*c -sqrt(1-rwater^2*(1-c^2)))*normal;
normal=-normal;
po=pi+ d1*v1/(v1'*normal);
v1=v1/norm(v1);
v2=v2/norm(v2);
refPts=[v0;pi;v1;po;v2];
end |
github | tomluc/Pinax-camera-model-master | RefractedRay.m | .m | Pinax-camera-model-master/MATLAB/Find_correction_map/RefractedRay.m | 614 | utf_8 | 603b41ff3d8a155e43e94de324e462b9 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) MERL 2012
% CVPR 2012 Paper Title: A Theory of Multi-Layer Flat Refractive Geometry
% Author: Amit Agrawal
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Compute refracted ray direction at a refraction boundary
function [vr,a,b,tir] = RefractedRay(vi,n,mu1,mu2)
tir = 0;
n = n/norm(n);
kk = mu1^2*(vi'*n)^2 - (mu1^2-mu2^2)*(vi'*vi);
if(kk < 0)
% total internal reflection
tir = 1;
a = 0;
b = 0;
vr = zeros(3,1);
return
end
a = mu1/mu2;
b = -mu1*(vi'*n) - sqrt(kk);
b = b/mu2;
vr = a*vi + b*n;
|
github | V170SC/ESN-homeokinesis-master | mackeyglass_rk4.m | .m | ESN-homeokinesis-master/ESNConceptorsTest/MackeyGlassGenerator/mackeyglass_rk4.m | 1,157 | utf_8 | aab166beab25f407a8396d0149f4f480 | %% mackeyglass_rk4
% This function computes the numerical solution of the Mackey-Glass
% delayed differential equation using the 4-th order Runge-Kutta method
%%
% $$k_1=\Delta t \cdot mackeyglass\_eq(x(t), x(t-\tau), a, b)$$
%%
% $$k_2=\Delta t \cdot mackeyglass\_eq(x(t+\frac{1}{2}k_1), x(t-\tau), a, b)$$
%%
% $$k_3=\Delta t \cdot mackeyglass\_eq(x(t+\frac{1}{2}k_2), x(t-\tau), a, b)$$
%%
% $$k_4=\Delta t \cdot mackeyglass\_eq(x(t+k_3), x(t-\tau), a, b)$$
%%
% $$x(t+\Delta t) = x(t) + \frac{k_1}{6}+ \frac{k_2}{3} + \frac{k_3}{6} + \frac{k_4}{6}$$
%%
% Here is the code for <mackeyglass_eq.html mackeyglass_eq>,
% the Mackey-Glass delayed differential equation
%%
% *Matlab code:*
function x_t_plus_deltat = mackeyglass_rk4(x_t, x_t_minus_tau, deltat, a, b, n)
k1 = deltat*mackeyglass_eq(x_t, x_t_minus_tau, a, b, n);
k2 = deltat*mackeyglass_eq(x_t+0.5*k1, x_t_minus_tau, a, b, n);
k3 = deltat*mackeyglass_eq(x_t+0.5*k2, x_t_minus_tau, a, b, n);
k4 = deltat*mackeyglass_eq(x_t+k3, x_t_minus_tau, a, b, n);
x_t_plus_deltat = (x_t + k1/6 + k2/3 + k3/3 + k4/6);
end
%%
%
% <mackeyglass.html _back to main_>
|
github | V170SC/ESN-homeokinesis-master | mackeyglass_eq.m | .m | ESN-homeokinesis-master/ESNConceptorsTest/MackeyGlassGenerator/mackeyglass_eq.m | 357 | utf_8 | 7ee7c2d23205ea0883eaa806816697e7 | %% makeyglass_eq
% This function returns dx/dt of Mackey-Glass delayed differential equation
%%
%
% $$\frac{dx(t)}{dt}=\frac{ax(t-\tau)}{1+x(t-\tau)^{10}}-bx(t)$$
%
%%
% *Matlab code:*
function x_dot = mackeyglass_eq(x_t, x_t_minus_tau, a, b, n)
x_dot = -b*x_t + a*x_t_minus_tau/(1 + x_t_minus_tau^n);
end
%%
%
% <mackeyglass.html _back to main_>
|
github | Regon94/Smooth-Particle-Hydrodynamics-master | Post_multifluid_energy.m | .m | Smooth-Particle-Hydrodynamics-master/Post_multifluid_energy.m | 4,422 | utf_8 | 02c1a46f09d25f338dddf38fd7a2d0c0 | %% Function to calculate the energy of each fluid in a multi-fluid system
function [KE_alpha, KE_beta, PE_alpha, PE_beta] = Post_multifluid_energy()
%% initialisation
clear particles
%close all
clc
time = save_pos_t;
n = length(time);
E_kin_alpha = zeros(n,1);
E_kin_beta = zeros(n,1);
E_pot_alpha = zeros(n,1);
E_pot_beta = zeros(n,1);
E_pV_alpha = zeros(n,1);
E_pV_beta = zeros(n,1);
E_tot1_alpha = zeros(n,1);
E_tot2_alpha = zeros(n,1);
E_tot1_beta = zeros(n,1);
E_tot2_beta = zeros(n,1);
% particles = []
%% loop over timesteps
for t = 2:n
% particle data of current timestep
particles(:,:) = save_pos(int_fluid,:,t);
% kinetic Energy
mass = particles(:,4);
vel_sq = (particles(:,6).^2 + particles(:,7).^2); % v^2
kin = mass .* vel_sq / 2;
kin(isnan(kin)) = 0;
% summing the KE of all the particles of each fluid
% E_kin_alpha is going to rewrite the value at t for every iteration in
% this loop
i=1;
for i = 1:int_fluid
if particles(i,3) == 2
E_kin_alpha(t) = E_kin_alpha(t) + kin(i);
elseif particles(i,3) == 3
E_kin_beta(t) = E_kin_beta(t) + kin(i);
end
end
if (time(t) - t_damp) <= 1e-3
% transient gravity force
g = 0.5 * (sin((-0.5 + time(t)/t_damp) * pi) + 1 ) * abs(G(2));
% potential Energy
pot = mass .* g .* particles(:,2);
pot(isnan(pot)) = 0;
% Summing PE of all particles of each fluid at this timestep
i=1;
for i = 1:int_fluid
if particles(i,3) == 2
E_pot_alpha(t) = E_pot_alpha(t) + pot(i);
elseif particles(i,3) == 3
E_pot_beta(t) = E_pot_beta(t) + pot(i);
end
end
% E_pot(t) = sum(pot);
% E_pot_ref = E_pot(t);
% pressure volume work
volume = particles(:,4)./ particles(:,5);
rho = particles(:,5);
volume_0 = dx * dx;
pV = mass .* c_0(2).^2./(7.*(7-1)).*((rho./rho_0(2)).^(7-1) + (7-1).*rho_0(2)./rho - 7);
%pV = volume .* particles(:,8);
%pV = p_0(2) ./ (1-gamma(2)) .* volume_0.^(gamma(2)) .* ( volume.^(1-gamma(2)) - volume_0.^(1-gamma(2))) + (Xi(2) - p_0(2)) .* (volume - volume_0);
pV(isnan(pV)) = 0;
i=1;
for i = 1:int_fluid
if particles(i,3) == 2
E_pV_alpha(t) = E_pV_alpha(t) + pV(i);
elseif particles(i,3) == 3
E_pV_beta(t) = E_pV_beta(t) + pV(i);
end
end
% E_pV(t) = sum(pV);
% E_pV_ref = E_pV(t);
elseif time(t) >= t_damp
g = abs(G(2));
% potential Energy
pot = mass .* g .* particles(:,2);
pot(isnan(pot)) = 0;
% Summing PE of all particles of each fluid at this timestep
j=0;
for j = 1:int_fluid
if particles(j,3) == 2
E_pot_alpha(t) = E_pot_alpha(t) + pot(j);
elseif particles(j,3) == 3
E_pot_beta(t) = E_pot_beta(t) + pot(j);
end
end
% E_pot(t) = sum(pot) - E_pot_ref;
% pressure volume work
volume = particles(:,4)./ particles(:,5);
rho = particles(:,5);
volume_0 = dx * dx;
pV = mass .* c_0(2).^2./(7.*(7-1)).*((rho./rho_0(2)).^(7-1) + (7-1).*rho_0(2)./rho - 7);
%pV = volume .* particles(:,8);
%pV = p_0(2) ./ (1-gamma(2)) .* volume_0.^(gamma(2)) .* ( volume.^(1-gamma(2)) - volume_0.^(1-gamma(2))) + (Xi(2) - p_0(2)) .* (volume - volume_0);
pV(isnan(pV)) = 0;
% Summing PE of all particles of each fluid at this timestep
i=1;
for i = 1:int_fluid
if particles(i,3) == 2
E_pV_alpha(t) = E_pV_alpha(t) + pV(i);
elseif particles(i,3) == 3
E_pV_beta(t) = E_pV_beta(t) + pV(i);
end
end
% E_pV(t) = sum(pV) - E_pV_ref;
end
% total Energy
E_tot1_alpha(t) = E_kin_alpha(t) + E_pot_alpha(t);
E_tot2_alpha(t) = E_kin_alpha(t) + E_pot_alpha(t) + E_pV_alpha(t);
E_tot1_beta(t) = E_kin_beta(t) + E_pot_beta(t);
E_tot2_beta(t) = E_kin_beta(t) + E_pot_beta(t) + E_pV_beta(t);
end
end
|
github | Regon94/Smooth-Particle-Hydrodynamics-master | Free_Bubble.m | .m | Smooth-Particle-Hydrodynamics-master/Free_Bubble.m | 3,971 | utf_8 | 2017ecdee885e0b5d75c900aa7fa6c45 | %% Bubble Formation Dynamic Test Case
% Roger Gonzalez
% 12/06/17
function [particles, rho_0,gamma,c_0,p_0,Xi,my,alpha, a_wall, int_fluid, int_boundary] = Free_Bubble(kernel, dx, d, v_max, alpha)
% Square domain
origin = [0 0];
% first fluid phase
% specify coordinates of edges for fluid
f_lowleft = [-0.1 0.0]+origin;
f_lowright = [ 0.1 0.0]+origin;
f_upleft = [-0.1 0.2]+origin;
f_upright = [ 0.1 0.2]+origin;
% properties of fluid (will be stored)
flag = 2;
rho_0(flag) = 1; % density
gamma(flag) = 7; % pressure exponent
% artificial speed of sound, c_0 = 10 * v_max = 10 * sqrt(g*H)
c_0(flag) = 10*v_max;
p_0(flag) = rho_0(flag) * c_0(flag)^2 / gamma(flag);% reference pressure
Xi(flag) = 0.0 * p_0(flag); % background pressure
my(flag) = 0.01; % viscosity
alpha(flag) = 0.02; % artificial visc factor
% initial velocities
vel = [0,0];
% create particle matrix
fluid = create_fluid(dx, f_lowleft, f_lowright, f_upleft, f_upright);
particles = [];
[particles, int_f1] = initialisation(particles, fluid, flag, rho_0(flag), dx, d, vel);
%% second fluid phase
multi_ph = 0;
if multi_ph == 1
f_lowleft = [-0.1 0.0]+origin;
f_lowright = [ 0.1 0.0]+origin;
f_upleft = [-0.1 0.2]+origin;
f_upright = [ 0.1 0.2]+origin;
% properties of fluid (will be stored)
flag = 3;
rho_0(flag) = 1; % density
gamma(flag) = 7; % pressure exponent
% artificial speed of sound, c_0 = 10 * v_max = 10 * sqrt(g*H)
c_0(flag) = 10*v_max;
p_0(flag) = rho_0(flag) * c_0(flag)^2 / gamma(flag); % reference pressure
Xi(flag) = 0 * p_0(flag); % background pressure
my(flag) = 0.01; % viscosity
alpha(flag) = 0.02; % artificial visc factor
% initial velocities
vel = [0,0];
% create particle matrix
%fluid = create_fluid(dx, f_lowleft, f_lowright, f_upleft, f_upright);
fluid = create_boundary(3, dx, f_lowleft, f_lowright, f_upleft, f_upright);
[particles, int_f2] = initialisation(particles, fluid, flag, rho_0(flag), dx, d, vel);
% integer of fluid particles in matrix
int_fluid = 1:max(int_f2);
else
int_fluid = 1:max(int_f1);
end
%% specify coordinates of edges for boundary
% b_lowleft = [-0.25 0.0]+origin;
% b_lowright = [ 0.25 0.0]+origin;
% b_upleft = [-0.25 0.5]+origin;
% b_upright = [ 0.25 0.5]+origin;
%properties
v_wall = [0,0]; % prescribed wall velocity
a_wall = [0,0]; % wall acceleration
int_boundary = 0;
% flag = 1; % for boundary
% %set artificial viscosity of boundary to 0
% alpha(flag) = 0;
% % create boundary matrix
% boundary = create_boundary(kernel, dx, b_lowleft, b_lowright, b_upleft, b_upright);
% [particles, int_boundary] = initialisation(particles, boundary, flag, 0, dx, d, [0,0]);
% particles(int_boundary,4) = v_wall(1);
% particles(int_boundary,5) = v_wall(2);
%
%% plot initial positions of particles
figure(1)
hold on
plot(particles(int_f1,1), particles(int_f1,2), '.')
axis([-.4 0.4 -0.2 0.6])
if multi_ph == 1
plot(particles(int_f2,1), particles(int_f2,2), 'g.')
end
% plot(particles(int_boundary,1), particles(int_boundary,2), 'r.')
% plot([b_upleft(1,1), b_lowleft(1,1), b_lowright(1,1), b_upright(1,1)],...
% [b_upleft(1,2), b_lowleft(1,2), b_lowright(1,2), b_upright(1,2)], 'r', 'linewidth', 2)
axis('equal')
end |
github | Regon94/Smooth-Particle-Hydrodynamics-master | der_color_field.m | .m | Smooth-Particle-Hydrodynamics-master/der_color_field.m | 1,449 | utf_8 | 5ce0f648cfe22f24743494652a876eb1 | %% Calculating the gradient of the smoothed color field
%part of the Surface area minimization in Akinci Surface tension model
%
% Roger Gonzalez
% 04/07/2017
function [boundary_der_color_field] = der_color_field(particles, a, b, r_c, h, rho_0, p_0, Xi, gamma, eqn_of_state, range)
%
% a - fluid particle wrt which boundary values will be calculated
% b - particle in question
% r_c - kernel sampling range
% h - initial distance between particles = dx
boundary_der_color_field = 0;
for k = range{b}(2:end)
if particles(k,3) == 1
rho_b = boundary_rho(particles, a, rho_0, p_0, Xi, gamma,eqn_of_state);
m_b = rho_0(particles(a,3)) * h*h;
else
rho_b = particles(k,5);
m_b = particles(k,4);
end
%distance between particles
drx = particles(b,1) - particles(k,1);
dry = particles(b,2) - particles(k,2);
rad = sqrt(drx^2 + dry^2);
W_der = kernel_der(1, 2, h, rad)/h;
boundary_der_color_field = boundary_der_color_field + (m_b/rho_b) *W_der;
end
% Serves to make the term scale independent
boundary_der_color_field = r_c * boundary_der_color_field;
%Warning Signs
if isnan(boundary_der_color_field)
fprintf('Mass \n',m_b);
fprintf('desity \n',rho_b);
error('derivative of the color field is NaN')
end
end |
github | Regon94/Smooth-Particle-Hydrodynamics-master | Meniscus.m | .m | Smooth-Particle-Hydrodynamics-master/Meniscus.m | 3,808 | utf_8 | 78b1db669f26941672c04687dafe35fd | %% Surface Tension Force model
% Roger Gonzalez
% 21/06/17
function [particles, rho_0,gamma,c_0,p_0,Xi,my,alpha, a_wall, int_fluid, int_boundary] = Meniscus(kernel, dx, d, v_max, alpha)
% rectangular domain
origin = [0 0];
% first fluid phase
% specify coordinates of edges for fluid
f_lowleft = [-1.5 0.0]+origin;
f_lowright = [ 1.5 0.0]+origin;
f_upleft = [-1.5 0.5]+origin;
f_upright = [ 1.5 0.5]+origin;
% properties of fluid (will be stored)
flag = 2;
rho_0(flag) = 1000; % density
gamma(flag) = 7; % pressure exponent
% artificial speed of sound, c_0 = 10 * v_max = 10 * sqrt(g*H)
c_0(flag) = 10*v_max;
p_0(flag) = rho_0(flag) * c_0(flag)^2 / gamma(flag);% reference pressure
Xi(flag) = 0.0 * p_0(flag); % background pressure
my(flag) = 0.01; % viscosity
alpha(flag) = 0.02; % artificial visc factor
% initial velocities
vel = [0,0];
% create particle matrix
fluid = create_fluid(dx, f_lowleft, f_lowright, f_upleft, f_upright);
particles = [];
[particles, int_f1] = initialisation(particles, fluid, flag, rho_0(flag), dx, d, vel);
%% second fluid phase
multi_ph = 0;
if multi_ph == 1
f_lowleft = [-0.2 0.0]+origin;
f_lowright = [ 0.0 0.0]+origin;
f_upleft = [-0.2 1.2]+origin;
f_upright = [ 0.0 1.2]+origin;
% properties of fluid (will be stored)
flag = 3;
rho_0(flag) = 1; % density
gamma(flag) = 7; % pressure exponent
% artificial speed of sound, c_0 = 10 * v_max = 10 * sqrt(g*H)
c_0(flag) = 10*v_max;
p_0(flag) = rho_0(flag) * c_0(flag)^2 / gamma(flag); % reference pressure
Xi(flag) = 0 * p_0(flag); % background pressure
my(flag) = 0.01; % viscosity
alpha(flag) = alpha; % artificial visc factor
% initial velocities
vel = [0,0];
% create particle matrix
fluid = create_fluid(dx, f_lowleft, f_lowright, f_upleft, f_upright);
[particles, int_f2] = initialisation(particles, fluid, flag, rho_0(flag), dx, d, vel);
% integer of fluid particles in matrix
int_fluid = 1:max(int_f2);
else
int_fluid = 1:max(int_f1);
end
%% specify coordinates of edges for boundary
b_lowleft = [-1.5 0.0]+origin;
b_lowright = [ 1.5 0.0]+origin;
b_upleft = [-1.5 1.0]+origin;
b_upright = [ 1.5 1.0]+origin;
% properties
v_wall = [0,0]; % prescribed wall velocity
a_wall = [0,0]; % wall acceleration
flag = 1; % for boundary
%set artificial viscosity of boundary to 0
alpha(flag) = 0;
% create boundary matrix
boundary = create_boundary(kernel, dx, b_lowleft, b_lowright, b_upleft, b_upright);
[particles, int_boundary] = initialisation(particles, boundary, flag, 0, dx, d, [0,0]);
particles(int_boundary,4) = v_wall(1);
particles(int_boundary,5) = v_wall(2);
%% plot initial positions of particles
figure(1)
hold on
plot(particles(int_f1,1), particles(int_f1,2), '.')
if multi_ph == 1
plot(particles(int_f2,1), particles(int_f2,2), 'g.')
end
plot(particles(int_boundary,1), particles(int_boundary,2), 'r.')
plot([b_upleft(1,1), b_lowleft(1,1), b_lowright(1,1), b_upright(1,1)],...
[b_upleft(1,2), b_lowleft(1,2), b_lowright(1,2), b_upright(1,2)], 'r', 'linewidth', 2)
axis('equal')
end
|
github | Regon94/Smooth-Particle-Hydrodynamics-master | PairwiseForce.m | .m | Smooth-Particle-Hydrodynamics-master/PairwiseForce.m | 5,508 | utf_8 | 79c32e9db906e42ecb4c0644cbf4e43a | %% Surface Tension Force model
% Roger Gonzalez
% 30/05/17
function [PF, Virial_Pressure, adhesion_F, der_color_field_i] = PairwiseForce(ST_model, particles, h, dist, a, b, domain, rho_0, p_0, r_c, rho_b, m_b, Xi, gamma, eqn_of_state, int_boundary,idx_all)
% Have to individually import mass and density for the boundary particle
%% Cosine Pairwise Force
if ST_model == 1
phase_flag = abs(particles(a,3) - particles(b,3));
%Calibration constants for surface tension
if length(domain{a}) < 27 || phase_flag ~= 0
S_ab = (16^2)*0.00001; %different fluid phases or surface particle
VP_switch = 0;
elseif phase_flag == 0
S_ab = (16^2)*0.1; %same fluid phase or bulk particle
VP_switch = 1; % To ensure virial pressure only adds when all particles are in same phase
end
if dist < h
PF = -100*S_ab*cos(1.5*pi*dist / (3*h));
Virial_Pressure = 0;
else
PF = 0;
xi = (h^3) *(-8 +9*pi^2) / (27*pi^2);
Virial_Pressure = - xi*(particles(a,5)^2)*S_ab * VP_switch;
end
%Specific energy due to the pairwise force model
% PF_spec_E = (8/81) * ((h^4)/(pi^4)) * (9/4*pi^3 - 6*pi -4) * particles(a,5) * particles(b,5) * S_ab;
% assignin(ws, 'PF_spec_E', PF_spec_E);
end
%% PF-3
if ST_model ==3
phase_flag = abs(particles(a,3) - particles(b,3));
if length(domain{a}) < 27 || phase_flag ~= 0
S_ab = (16^2)*2; %same fluid phase
VP_switch = 1; % To ensure virial pressure only adds when all particles are in same phase
else
S_ab = (16^2)*0.00001; %different fluid phases
VP_switch = 0;
end
if dist <= r_c
eps=r_c/3.5;
eps_0 = eps/2;
A = (eps/eps_0)^3;
psi_eps = exp(-(dist^2)/(2*(eps^2)));
psi_eps_0 = exp(-(dist^2)/(2*(eps_0^2)));
PF = S_ab*dist*(-A*psi_eps_0 + psi_eps);
Virial_Pressure = 0;
else
PF = 0;
xi = (r_c^3) *(-8 +9*pi^2) / (27*pi^2);
Virial_Pressure = - xi*(particles(a,5)^2)*S_ab * VP_switch;
end
end
%% Kernel Weighted Attraction (Becker & Teschner)
% - Upon further consideration this model is pointless
% - It is not useful with the kernel that we are using and less accurate
% than Cohesion Force (Akinci)
if ST_model == 4
W = kernel_fct(1, 2, h, dist/h);
PF = -( particles(b,4) / particles(a,4) ) * W;
Virial_Pressure = 0;
PF_spec_E = 0;
if dist < 0.5*r_c
PF=0;
end
end
%% Cohesion Force model
if ST_model == 5
% NS = particles(:,1:2); %List of all particles
% idx_all = rangesearch(NS,NS,r_c); %List of all particles within range of each fluid particle
cohesion_spline = 0;
adhesion_spline = 0;
adhesion_F = 0;
%Cohesion Force
if dist <= r_c && dist > 0.5*r_c
cohesion_spline = ((r_c-dist)^3)*(dist^3);
elseif dist >= 0 && dist <= 0.5*r_c
cohesion_spline = 2*((r_c-dist)^3)*(dist^3) - (r_c^6)/64;
end
cohesion_spline = (32/(pi*r_c^9))*cohesion_spline;
cohesion_F = -particles(a,4) * particles(b,4) * cohesion_spline;
%Surface Area Minimization
%derivative of the color field for a fluid particle: particle in
%question
der_color_field_i = der_color_field(particles, a, a, r_c, h, rho_0, p_0, Xi, gamma, eqn_of_state, idx_all);
% derivative of the color field of second particle
der_color_field_j = der_color_field(particles, a, b, r_c, h, rho_0, p_0, Xi, gamma, eqn_of_state, idx_all);
surf_area_min_F = -particles(a,4) * (der_color_field_i - der_color_field_j);
if isnan(surf_area_min_F) || isnan(der_color_field_i) || isnan(der_color_field_i)
fprintf('mass of fluid particle: %d \n ',particles(a,4));
fprintf('derivative of color field of a: %d \n', der_color_field_i);
fprintf('derivative of color field of b: %d \n', der_color_field_j);
error('Surface Area Minimization force is NaN')
end
%Adhesion Force
if particles(b,3) == 1
sum_boundary_vol = Boundary_Sampling_density(particles, 2, h, r_c, int_boundary, 1);
temp_index = b - int_boundary(1)+1;
BSD = sum_boundary_vol(temp_index);
if dist > 0.5*r_c && dist <= r_c
adhesion_spline = (0.007/(r_c^3.25)) * (-(4*dist^2)/r_c + 6*dist - 2*r_c)^(1/4);
end
adhesion_F = - particles(a,4) * rho_0(particles(a,3)) * BSD * adhesion_spline;
end
% Correction Factor to amplify forces of the particles with
% neighbourhood deficiency
corr_factor=(2*rho_0(particles(a,3))) / ( particles(a,5) + particles(b,5) );
contact_angle = 120;
gamma = 1-0.75*cosd(contact_angle);
beta = 1+abs(0.5*cosd(contact_angle));
% gamma=0.1;
% beta=1.5;
PF = corr_factor * gamma * (cohesion_F) + beta * adhesion_F;
% % virial Pressure
% Cosine Force Virial Pressure
% eps = (h^3 *(9*(pi^2)-8))/(27*(pi^2));
% Virial_Pressure = -eps * (particles(a,5)^2) * gamma
% %Derived Virial Pressure Term
% if dist <= r_c && dist > 0.5*r_c
% eps = 1/1260;
% elseif dist >= 0 && dist <= 0.5*r_c
% eps = 61/645120;
% end
% Virial_Pressure = - pi * particles(a,5)^2 * gamma * particles(a,4) * particles(b,4) * r_c^3 * eps;
end
Virial_Pressure=0;
end |
github | Regon94/Smooth-Particle-Hydrodynamics-master | save_vtu.m | .m | Smooth-Particle-Hydrodynamics-master/save_vtu.m | 4,555 | utf_8 | 20ab9ee84fcea2f326bfb92a45538c04 | % Script to plot data from SPH slosh simulation
function [] = save_vtu(particles,n_save, dirname)
% specify n_save = 0 for boundary particles
%% saving directory
% check for existence of paraviewfiles/vtu directory. this is the directory where
% the .vtu files will be stored. if it does not exist create it
% dirname='VTU_Results';
dirstatus=exist(dirname,'dir');
if(dirstatus==0)
mkdir(dirname)
end
%% test vtu output (ascii)
i = n_save;
%for i = 1:size(save_pos,3)
% specify file name
if n_save ~= 0
name = strcat('slosh',num2str(i,'%3.3d'),'.dat');
fid=eval(['fopen(''',dirname,'/PART' num2str(i,'%3.3d') '.vtu' ''',''w'' );']);
else % for boundary particles
%name = strcat('slosh',num2str(i,'%3.3d'),'.dat');
fid=eval(['fopen(''',dirname,'/BOUND' num2str(i,'%3.3d') '.vtu' ''',''w'' );']);
i = 1;
end
% specify data to store/ output
% particles(:,:) = save_pos(:,:,i);
np = size(particles,1);
xp=particles(:,1); % position
zp=particles(:,2);
up=particles(:,6); % velocity
wp=particles(:,7);
rhop=particles(:,5); % density
P=particles(:,8); % pressure
% numbering
idiv=2;
nbeg1=1;
nb=0;
nend1=nb;
nbeg2=nb+1;
nend2=np;
% output to file in vtu format
fprintf(fid,'<?xml version="1.0"?>\r\n');
fprintf(fid,'<VTKFile type= "UnstructuredGrid" version= "0.1" byte_order= "BigEndian">\r\n');
fprintf(fid,' <UnstructuredGrid>\r\n');
fprintf(fid,' <Piece NumberOfPoints="%d" NumberOfCells="%d">\r\n',np,np);
% write in pressure data
fprintf(fid,' <PointData Scalars="Pressure" Vectors="Velocity">\r\n');
fprintf(fid,' <DataArray type="Float32" Name="Pressures" format="ascii">\r\n');
for ii=1:np
fprintf(fid,'%f\t',P(ii));
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
% write density data
fprintf(fid,' <DataArray type="Float32" Name="Density" format="ascii">\r\n');
for ii=1:np
fprintf(fid,'%f\t',rhop(ii));
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
% this section is used to color different particles based the input idiv specified above.
fprintf(fid,' <DataArray type="Float32" Name="Scalarplot" format="ascii">\r\n');
for ii=1:idiv
eval(['nbeg=nbeg' int2str(ii) ';'])
eval(['nend=nend' int2str(ii) ';'])
for jj=nbeg:nend
fprintf(fid,'%f\t',ii);
fprintf(fid,'\n');
end
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
% write velocity data
fprintf(fid,' <DataArray type="Float32" Name="Velocity" NumberOfComponents="3" format="ascii">\r\n');
for ii=1:np
vel=[up(ii) 0 wp(ii)];
fprintf(fid,'%f\t %f\t %f\t',vel);
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
fprintf(fid,' </PointData>\r\n');
% write particle position data
fprintf(fid,' <Points>\r\n');
fprintf(fid,' <DataArray type="Float32" NumberOfComponents="3" format="ascii">\r\n');
for ii=1:np
pos=[xp(ii) 0 zp(ii)];
fprintf(fid,'%f\t %f\t %f\t',pos);
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
fprintf(fid,' </Points>\r\n');
% write cell data. cell is of type vertex.
fprintf(fid,' <Cells>\r\n');
fprintf(fid,' <DataArray type="Int32" Name="connectivity" format="ascii">\r\n');
for ii=1:np
fprintf(fid,'%d\t',ii-1);
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
fprintf(fid,'\r\n');
fprintf(fid,' <DataArray type="Int32" Name="offsets" format="ascii">\r\n');
for ii=1:np
fprintf(fid,'%d\t',ii);
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
fprintf(fid,'\r\n');
fprintf(fid,' <DataArray type="Int32" Name="types" format="ascii">\r\n');
for ii=1:np
fprintf(fid,'%d\t',1);
fprintf(fid,'\n');
end
fprintf(fid,'\r\n');
fprintf(fid,' </DataArray>\r\n');
fprintf(fid,' </Cells>\r\n');
fprintf(fid,' </Piece>\r\n');
fprintf(fid,' </UnstructuredGrid>\r\n');
fprintf(fid,'</VTKFile>');
fclose(fid);
%end
|
github | Regon94/Smooth-Particle-Hydrodynamics-master | Drop.m | .m | Smooth-Particle-Hydrodynamics-master/Drop.m | 3,806 | utf_8 | e800b4320755500092ff36b0628c2c6c | %% Surface Tension Force model
% Roger Gonzalez
% 03/07/2017
function [particles, rho_0,gamma,c_0,p_0,Xi,my,alpha, a_wall, int_fluid, int_boundary] = Drop(kernel, dx, d, v_max, alpha)
% rectangular domain
origin = [0 0];
% first fluid phase
% specify coordinates of edges for fluid
f_lowleft = [-0.1 0.0]+origin;
f_lowright = [ 0.1 0.0]+origin;
f_upleft = [-0.1 0.1]+origin;
f_upright = [ 0.1 0.1]+origin;
% properties of fluid (will be stored)
flag = 2;
rho_0(flag) = 1000; % density
gamma(flag) = 7; % pressure exponent
% artificial speed of sound, c_0 = 10 * v_max = 10 * sqrt(g*H)
c_0(flag) = 10*v_max;
p_0(flag) = rho_0(flag) * c_0(flag)^2 / gamma(flag);% reference pressure
Xi(flag) = 0.0 * p_0(flag); % background pressure
my(flag) = 0.01; % viscosity
alpha(flag) = 0.02; % artificial visc factor
% initial velocities
vel = [0,0];
% create particle matrix
fluid = create_fluid(dx, f_lowleft, f_lowright, f_upleft, f_upright);
particles = [];
[particles, int_f1] = initialisation(particles, fluid, flag, rho_0(flag), dx, d, vel);
%% second fluid phase
multi_ph = 0;
if multi_ph == 1
f_lowleft = [-0.2 0.0]+origin;
f_lowright = [ 0.0 0.0]+origin;
f_upleft = [-0.2 1.2]+origin;
f_upright = [ 0.0 1.2]+origin;
% properties of fluid (will be stored)
flag = 3;
rho_0(flag) = 1; % density
gamma(flag) = 7; % pressure exponent
% artificial speed of sound, c_0 = 10 * v_max = 10 * sqrt(g*H)
c_0(flag) = 10*v_max;
p_0(flag) = rho_0(flag) * c_0(flag)^2 / gamma(flag); % reference pressure
Xi(flag) = 0 * p_0(flag); % background pressure
my(flag) = 0.01; % viscosity
alpha(flag) = alpha; % artificial visc factor
% initial velocities
vel = [0,0];
% create particle matrix
fluid = create_fluid(dx, f_lowleft, f_lowright, f_upleft, f_upright);
[particles, int_f2] = initialisation(particles, fluid, flag, rho_0(flag), dx, d, vel);
% integer of fluid particles in matrix
int_fluid = 1:max(int_f2);
else
int_fluid = 1:max(int_f1);
end
%% specify coordinates of edges for boundary
b_lowleft = [-0.2 0.0]+origin;
b_lowright = [ 0.2 0.0]+origin;
b_upleft = [-0.2 0.0]+origin;
b_upright = [ 0.2 0.0]+origin;
% properties
v_wall = [0,0]; % prescribed wall velocity
a_wall = [0,0]; % wall acceleration
flag = 1; % for boundary
%set artificial viscosity of boundary to 0
alpha(flag) = 0;
% create boundary matrix
boundary = create_boundary(kernel, dx, b_lowleft, b_lowright, b_upleft, b_upright);
[particles, int_boundary] = initialisation(particles, boundary, flag, 0, dx, d, [0,0]);
particles(int_boundary,4) = v_wall(1);
particles(int_boundary,5) = v_wall(2);
%% plot initial positions of particles
figure(1)
hold on
plot(particles(int_f1,1), particles(int_f1,2), '.')
if multi_ph == 1
plot(particles(int_f2,1), particles(int_f2,2), 'g.')
end
plot(particles(int_boundary,1), particles(int_boundary,2), 'r.')
plot([b_upleft(1,1), b_lowleft(1,1), b_lowright(1,1), b_upright(1,1)],...
[b_upleft(1,2), b_lowleft(1,2), b_lowright(1,2), b_upright(1,2)], 'r', 'linewidth', 2)
axis('equal')
end
|
github | fan9193/exercise2-master | trandn.m | .m | exercise2-master/trandn.m | 3,549 | utf_8 | 307219e197d890623614a7c90eb2bef8 | function x=trandn(l,u)
%% truncated normal generator
% * efficient generator of a vector of length(l)=length(u)
% from the standard multivariate normal distribution,
% truncated over the region [l,u];
% infinite values for 'u' and 'l' are accepted;
% * Remark:
% If you wish to simulate a random variable
% 'Z' from the non-standard Gaussian N(m,s^2)
% conditional on l<Z<u, then first simulate
% X=trandn((l-m)/s,(u-m)/s) and set Z=m+s*X;
% Reference:
% Botev, Z. I. (2016). "The normal law under linear restrictions:
% simulation and estimation via minimax tilting". Journal of the
% Royal Statistical Society: Series B (Statistical Methodology).
% doi:10.1111/rssb.12162
l=l(:);u=u(:); % make 'l' and 'u' column vectors
if length(l)~=length(u)
error('Truncation limits have to be vectors of the same length')
end
x=nan(size(l));
a=.66; % treshold for switching between methods
% threshold can be tuned for maximum speed for each Matlab version
% three cases to consider:
% case 1: a<l<u
I=l>a;
if any(I)
tl=l(I); tu=u(I); x(I)=ntail(tl,tu);
end
% case 2: l<u<-a
J=u<-a;
if any(J)
tl=-u(J); tu=-l(J); x(J)=-ntail(tl,tu);
end
% case 3: otherwise use inverse transform or accept-reject
I=~(I|J);
if any(I)
tl=l(I); tu=u(I); x(I)=tn(tl,tu);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=ntail(l,u)
% samples a column vector of length=length(l)=length(u)
% from the standard multivariate normal distribution,
% truncated over the region [l,u], where l>0 and
% l and u are column vectors;
% uses acceptance-rejection from Rayleigh distr.
% similar to Marsaglia (1964);
c=l.^2/2; n=length(l); f=expm1(c-u.^2/2);
x=c-reallog(1+rand(n,1).*f); % sample using Rayleigh
% keep list of rejected
I=find(rand(n,1).^2.*x>c); d=length(I);
while d>0 % while there are rejections
cy=c(I); % find the thresholds of rejected
y=cy-reallog(1+rand(d,1).*f(I));
idx=rand(d,1).^2.*y<cy; % accepted
x(I(idx))=y(idx); % store the accepted
I=I(~idx); % remove accepted from list
d=length(I); % number of rejected
end
x=sqrt(2*x); % this Rayleigh transform can be delayed till the end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=tn(l,u)
% samples a column vector of length=length(l)=length(u)
% from the standard multivariate normal distribution,
% truncated over the region [l,u], where -a<l<u<a for some
% 'a' and l and u are column vectors;
% uses acceptance rejection and inverse-transform method;
tol=2; % controls switch between methods
% threshold can be tuned for maximum speed for each platform
% case: abs(u-l)>tol, uses accept-reject from randn
I=abs(u-l)>tol; x=l;
if any(I)
tl=l(I); tu=u(I); x(I)=trnd(tl,tu);
end
% case: abs(u-l)<tol, uses inverse-transform
I=~I;
if any(I)
tl=l(I); tu=u(I); pl=erfc(tl/sqrt(2))/2; pu=erfc(tu/sqrt(2))/2;
x(I)=sqrt(2)*erfcinv(2*(pl-(pl-pu).*rand(size(tl))));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x=trnd(l,u)
% uses acceptance rejection to simulate from truncated normal
x=randn(size(l)); % sample normal
% keep list of rejected
I=find(x<l|x>u); d=length(I);
while d>0 % while there are rejections
ly=l(I); % find the thresholds of rejected
uy=u(I);
y=randn(size(ly));
idx=y>ly&y<uy; % accepted
x(I(idx))=y(idx); % store the accepted
I=I(~idx); % remove accepted from list
d=length(I); % number of rejected
end
end
|
github | cvjena/caffe_pp2-master | classification_demo.m | .m | caffe_pp2-master/matlab/demo/classification_demo.m | 5,466 | utf_8 | 45745fb7cfe37ef723c307dfa06f1b97 | function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github | USF-IMARS/wv-land-cover-master | DT_Filter.m | .m | wv-land-cover-master/3d_wetlands/DT_Filter.m | 2,287 | utf_8 | 7c137152cbf1babe3afba4c1bd3106a5 | %% DT_Filter.M
%% Written by Matt McCarthy 8/29/2016
function dt_filt = DT_Filter(file,x,sz2,sz3,dev,FW,FU,UG,WA);
filt = x;
sz_sm(1) = sz2; % Size of unwarped(smaller) file
sz_sm(2) = sz3;
fwfilt = 75
wafilt = 50
sz1 = size(file);
dt_filt =zeros(sz1(1),sz1(2),'uint8');
for a = filt+1:sz_sm(1)-filt-1; % Mode filter or median filter: 3x3 or 5x5
for b = filt+1:sz_sm(2)-filt-1;
if file(a,b) == dev;
dt_filt(a,b) = dev;
elseif file(a,b) == FW && a > fwfilt && b > fwfilt && a < sz_sm(1)-100 && b < sz_sm(2)-100; % For FW, use larger window to eliminate erroneous urban misclassifications
C = file(a-fwfilt:a+fwfilt,b-fwfilt:b+fwfilt);
idx = find(C == 0); % If any pixels in C are shadows, they are not included in the mode function
C(idx) = [];
mod = mode(mode(C)); % Mode of window (by definition, lower value is selected if more than one mode value)
if isnan(mod) == 1;
dt_filt(a,b) = 0; % If NaN, assign zero because Arc won't load DT tiffs w/ NaNs
elseif mod == FW; % Check if mode FW is actually urban tree shadow
idxfor = find(C == dev | C == FU); % Find upland forest, grass, and developed nearby
if size(idxfor,1)>0.10*size(C,1)*size(C,2); % > 10% is upland, grass, or developed
dt_filt(a,b) = FU; % Assumed to be non-wetland forest
else dt_filt(a,b) = FW;
end
else dt_filt(a,b) = FU;
end
elseif isnan(file(a,b)) == 0;
C = file(a-filt:a+filt,b-filt:b+filt);
idx = find(C == 0); % If any pixels in C are shadows, they are not included in the mode function
C(idx) = [];
mod = mode(mode(C)); % Identify most common value (if more than one value, lower value is selected automatically)
if isnan(mod) == 1; % Check if mode of box is NaN (redundancy)
dt_filt(a,b) = 0; % If NaN, assign zero (Arc won't load DT tiffs w/ NaNs)
elseif mod == FW;
D = dt_filt(a-filt:a,b-filt:b);
modD = mode(mode(D));
dt_filt(a,b) = modD;
else dt_filt(a,b) = mod; % If mod is upland, marsh, water or bare/developed, assign it as such
end
else
dt_filt(a,b) = 0;
end
end
end
end
|
github | USF-IMARS/wv-land-cover-master | wv_classify.m | .m | wv-land-cover-master/3d_wetlands/wv_classify.m | 37,674 | utf_8 | a528dc999ab6d7c2903872339d10beb3 | %% WV2 Processing
% Loads TIFF WorldView-2 image files preprocessed through Polar Geospatial
% Laboratory python code, which orthorectifies and projects .NTF files and outputs as
% TIFF files
% Radiometrically calibrates digital count data
% Atmospherically corrects images by subtracting Rayleigh Path Radiance
% Converts image to surface reflectance by accounting for Earth-Sun
% distance, solar zenith angle, and average spectral irradiance
% Tests and optionally corrects for sunglint
% Corrects for water column attenuation
% Runs Decision Tree classification on each image
% Optionally smooths results through moving-window filter
% Outputs images as GEOTIFF files with geospatial information.
function dt_filt = WV_Processing(images,id,met,crd_sys,dt,filt,loc,idnumber,rrs_out,class_out);
tic
d_t = str2num(dt);
n = num2str(idnumber);
id
met
coor_sys = crd_sys; % Change coordinate system code here
filter = str2num(filt);
loc_out = rrs_out;
% Assign constants for all images
ebw1 = 0.001*[47.3 54.3 63.0 37.4 57.4 39.3 98.9 99.6]; % Effective Bandwidth per WV2 band (nm converted to um units; from IMD metadata files)
ebw2 = 0.001*[40.5 54.0 61.8 38.1 58.5 38.7 100.4 88.9]; % WV3
irr1 = [1758.2229 1974.2416 1856.4104 1738.4791 1559.4555 1342.0695 1069.7302 861.2866]; % Band-averaged Solar Spectral Irradiance (W/m2/um units)
irr2 = [1757.89 2004.61 1830.18 1712.07 1535.33 1348.08 1055.94 858.77]; % WV3 (from Radiometric Use of WorldView-3 Imagery, Thuiller 2003 column Table 3)
cw1 = [.4273 .4779 .5462 .6078 .6588 .7237 .8313 .9080]; % Center wavelength (used for Rayleigh correction; from Radiometric Use of WorldView-2 Imagery)
cw2 = [.4274 .4819 .5471 .6043 .6601 .7227 .8240 .9136]; % WV3
gamma = 0.01*[1.499 1.471 1.442 1.413 1.413 1.413 1.384 1.384]; % Factor used in Rayleigh Phase Function equation (Bucholtz 1995)
[A, R] = geotiffread(images);
szA = size(A);
s = xml2struct(met);
% save XMLtest.mat s
% Extract calibration factors and acquisition time from metadata for each band
if isfield(s,'IMD') == 1
szB(1) = str2num(s.IMD.SOURCE_IMD.IMD.NUMROWS.Text); %#ok<*ST2NM>
szB(2) = str2num(s.IMD.SOURCE_IMD.IMD.NUMCOLUMNS.Text);
kf(1,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_C.ABSCALFACTOR.Text);
kf(2,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_B.ABSCALFACTOR.Text);
kf(3,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_G.ABSCALFACTOR.Text);
kf(4,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_Y.ABSCALFACTOR.Text);
kf(5,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_R.ABSCALFACTOR.Text);
kf(6,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_RE.ABSCALFACTOR.Text);
kf(7,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_N.ABSCALFACTOR.Text);
kf(8,1) = str2num(s.IMD.SOURCE_IMD.IMD.BAND_N2.ABSCALFACTOR.Text);
aqyear = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.FIRSTLINETIME.Text(12:15)); % Extract Acquisition Time from metadata
aqmonth = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.FIRSTLINETIME.Text(17:18)); % Extract Acquisition Time from metadata
aqday = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.FIRSTLINETIME.Text(20:21)); % Extract Acquisition Time from metadata
aqhour = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.FIRSTLINETIME.Text(23:24)); % Extract Acquisition Time from metadata
aqminute = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.FIRSTLINETIME.Text(26:27)); % Extract Acquisition Time from metadata
aqsecond = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.FIRSTLINETIME.Text(29:37)); % Extract Acquisition Time from metadata
sunel = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.MEANSUNEL.Text); % Extract Mean Sun Elevation angle from metadata
satview = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.MEANOFFNADIRVIEWANGLE.Text); % Extract Mean Off Nadir View angle from metadata
sunaz = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.MEANSUNAZ.Text);
sensaz = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.MEANSATAZ.Text);
satel = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.MEANSATEL.Text);
cl_cov = str2num(s.IMD.SOURCE_IMD.IMD.IMAGE.CLOUDCOVER.Text);
elseif isfield(s,'isd') == 1
szB(1) = str2num(s.isd.IMD.NUMROWS.Text);
szB(2) = str2num(s.isd.IMD.NUMCOLUMNS.Text);
kf(1,1) = str2num(s.isd.IMD.BAND_C.ABSCALFACTOR.Text);
kf(2,1) = str2num(s.isd.IMD.BAND_B.ABSCALFACTOR.Text);
kf(3,1) = str2num(s.isd.IMD.BAND_G.ABSCALFACTOR.Text);
kf(4,1) = str2num(s.isd.IMD.BAND_Y.ABSCALFACTOR.Text);
kf(5,1) = str2num(s.isd.IMD.BAND_R.ABSCALFACTOR.Text);
kf(6,1) = str2num(s.isd.IMD.BAND_RE.ABSCALFACTOR.Text);
kf(7,1) = str2num(s.isd.IMD.BAND_N.ABSCALFACTOR.Text);
kf(8,1) = str2num(s.isd.IMD.BAND_N2.ABSCALFACTOR.Text);
aqyear = str2num(s.isd.IMD.IMAGE.FIRSTLINETIME.Text(1:4)); % Extract Acquisition Time from metadata
aqmonth = str2num(s.isd.IMD.IMAGE.FIRSTLINETIME.Text(6:7)); % Extract Acquisition Time from metadata
aqday = str2num(s.isd.IMD.IMAGE.FIRSTLINETIME.Text(9:10)); % Extract Acquisition Time from metadata
aqhour = str2num(s.isd.IMD.IMAGE.FIRSTLINETIME.Text(12:13)); % Extract Acquisition Time from metadata
aqminute = str2num(s.isd.IMD.IMAGE.FIRSTLINETIME.Text(15:16)); % Extract Acquisition Time from metadata
aqsecond = str2num(s.isd.IMD.IMAGE.FIRSTLINETIME.Text(18:26)); % Extract Acquisition Time from metadata
sunel = str2num(s.isd.IMD.IMAGE.MEANSUNEL.Text); % Extract Mean Sun Elevation angle from metadata
satview = str2num(s.isd.IMD.IMAGE.MEANOFFNADIRVIEWANGLE.Text); % Extract Mean Off Nadir View angle from metadata
sunaz = str2num(s.isd.IMD.IMAGE.MEANSUNAZ.Text);
sensaz = str2num(s.isd.IMD.IMAGE.MEANSATAZ.Text);
satel = str2num(s.isd.IMD.IMAGE.MEANSATEL.Text);
cl_cov = str2num(s.isd.IMD.IMAGE.CLOUDCOVER.Text);
else
c = struct2cell(s.Children(2).Children(:));
idx{1} = strfind(c(1,:),'NUMROWS');
idx{2} = strfind(c(1,:),'NUMCOLUMNS');
idx{3} = strfind(c(1,:),'BAND_C');
idx{4} = strfind(c(1,:),'BAND_B');
idx{5} = strfind(c(1,:),'BAND_G');
idx{6} = strfind(c(1,:),'BAND_Y');
idx{7} = strfind(c(1,:),'BAND_R');
idx{8} = strfind(c(1,:),'BAND_RE');
idx{9} = strfind(c(1,:),'BAND_N');
idx{10} = strfind(c(1,:),'BAND_N2');
idx{11} = strfind(c(1,:),'IMAGE');
for i = 1:11;
idxb(i,1:2) = find(not(cellfun('isempty',idx{i})));
end
szB(1) = str2num(s.Children(2).Children(idxb(1)).Children.Data);
szB(2) = str2num(s.Children(2).Children(idxb(2)).Children.Data);
kf(1,1) = str2num(s.Children(2).Children(idxb(3)).Children(26).Children.Data);
kf(2,1) = str2num(s.Children(2).Children(idxb(4)).Children(26).Children.Data);
kf(3,1) = str2num(s.Children(2).Children(idxb(5)).Children(26).Children.Data);
kf(4,1) = str2num(s.Children(2).Children(idxb(6)).Children(26).Children.Data);
kf(5,1) = str2num(s.Children(2).Children(idxb(7,1)).Children(26).Children.Data);
kf(6,1) = str2num(s.Children(2).Children(idxb(8)).Children(26).Children.Data);
kf(7,1) = str2num(s.Children(2).Children(idxb(9,1)).Children(26).Children.Data);
kf(8,1) = str2num(s.Children(2).Children(idxb(10)).Children(26).Children.Data);
aqyear = str2num(s.Children(2).Children(idxb(11,2)).Children(16).Children.Data(1:4));
aqmonth = str2num(s.Children(2).Children(idxb(11,2)).Children(16).Children.Data(6:7));
aqday = str2num(s.Children(2).Children(idxb(11,2)).Children(16).Children.Data(9:10));
aqhour = str2num(s.Children(2).Children(idxb(11,2)).Children(16).Children.Data(12:13));
aqminute = str2num(s.Children(2).Children(idxb(11,2)).Children(16).Children.Data(15:16));
aqsecond = str2num(s.Children(2).Children(idxb(11,2)).Children(16).Children.Data(18:26));
sunel = str2num(s.Children(2).Children(idxb(11,2)).Children(56).Children.Data);
sunaz = str2num(s.Children(2).Children(idxb(11,2)).Children(50).Children.Data);
satview = str2num(s.Children(2).Children(idxb(11,2)).Children(86).Children.Data);
sensaz = str2num(s.Children(2).Children(idxb(11,2)).Children(62).Children.Data);
satel = str2num(s.Children(2).Children(idxb(11,2)).Children(68).Children.Data);
cl_cov = str2num(s.Children(2).Children(idxb(11,2)).Children(90).Children.Data);
end
szB(3) = 8;
% Assign WV2 vs WV3 constant calibration factors
if id(4) == '3'
ebw = ebw2;
irr = irr2;
cw = cw2;
else ebw = ebw1;
irr = irr1;
cw = cw1;
end
% Identify growing season vs senesced
if aqmonth == 11 || aqmonth == 12 || aqmonth == 1 || aqmonth == 2
season = 0;
else season = 1;
end
%% Calculate Earth-Sun distance and relevant geometry
if aqmonth == 1 || aqmonth == 2;
year = aqyear -1;
month = aqmonth + 12;
else year = aqyear;
month = aqmonth;
end
UT = aqhour + (aqminute/60.0) + (aqsecond/3600.0); % Convert time to UT
B1 = int64(year/100);
B2 = 2-B1+int64(B1/4);
JD = (int64(365.25*(year+4716)) +int64(30.6001*(month+1)) + aqday + UT/24.0 + B2 - 1524.5); % Julian date
D = JD - 2451545.0;
degs = double(357.529 + 0.98560028*D); % Degrees
ESd = 1.00014 - 0.01671*cosd(degs) - 0.00014*cosd(2*degs); % Earth-Sun distance at given date (should be between 0.983 and 1.017)
inc_ang = 90.0 - sunel;
TZ = cosd(inc_ang); % Atmospheric spectral transmittance in solar path with solar zenith angle
TV = cosd(satview); % Atmospheric spectral transmittance in view path with satellite view angle
%% Calculate Rayleigh Path Radiance (Dash et al. 2012 and references therein)
if sunaz > 180 % For the following equations, azimuths should be between -180 and +180 degrees
sunaz = sunaz - 360;
end
if sensaz > 180
sensaz = sensaz - 360;
end
az = abs(sensaz - 180 - sunaz); % Relative azimuth angle
thetaplus = acosd(cosd(90-sunel)*cosd(90-satel) - sind(90-sunel)*sind(90-satel)*cosd(az)); % Scattering angles
for d = 1:8;
Pr(d) = (3/(4*(1+2*gamma(d))))*((1+3*gamma(d))+(1-gamma(d))*cosd(thetaplus)^2); % Rayleigh scattering phase function (described in Bucholtz 1995)
end
for d = 1:8;
tau(d) =(0.008569*(cw(d)^-4)*(1 + 0.0113*(cw(d)^-2) + 0.00013*cw(d)^-4)); % Rayleigh optical thickness (assume standard pressure of 1013.25 mb)
end
% Rayleigh calculation (Dash et al., 2012)
for d = 1:8;
ray_rad{1,1}(d) = ((irr(1,d)/ESd)*1*tau(d)*Pr(d))/(4*pi*cosd(90-satel)); % Assume standard pressure (1013.25 mb)
end
% rrs constant calculation (Kerr et al. 2018 and Mobley 1994)
G = single(1.7); % constant Li et al. 2019
na = 1.00029; % Refractive index of air
nw = 1.34; % Refractive index seawater
inc_ang2 = real(asind(sind(90-satel)*nw/na)); % Incident angle for water-air from Snell's Law
trans_aw = real(asind(sind(inc_ang)*na/nw)); % Transmission angle for air-water incident light from Snell's Law
trans_wa = 90-satel; % Transmission angle for water-air incident light from Snell's Law
pf1 = real(0.5*((sind(inc_ang - trans_aw)/(sind(inc_ang + trans_aw)))^2 + (tand(inc_ang - trans_aw)/(tand(inc_ang + trans_aw)))^2)); % Fresnel reflectance for air-water incident light (Mobley 1994)
pf2 = real(0.5*((sind(inc_ang2 - trans_wa)/(sind(inc_ang2 + trans_wa)))^2 + (tand(inc_ang2 - trans_wa)/(tand(inc_ang2 + trans_wa)))^2));
zeta = real(single((1-pf1)*(1-pf2)/(nw^2))); % rrs constant (~0.52) from Mobley 1994
% Adjust file size: Input file (A) warped may contain more or fewer columns/rows than original NITF file, and some may be corrupt.
sz(1) = min(szA(1),szB(1));
sz(2) = min(szA(2),szB(2));
sz(3) = 8;
%% Assign NaN to no-data pixels and radiometrically calibrate and convert to Rrs
Rrs = single(zeros(szA(1),szA(2),8)); % Create empty matrix for Rrs output
for j = 1:sz(1); % Assign NaN to pixels of no data
for k = 1:sz(2); % If a pixel contains data values other than "zero" or "two thousand and forty seven" in any band, it is calibrated; otherwise, it is considered "no-data" - this avoids a problem created during the orthorectification process wherein reprojecting the image may resample data
if (A(j,k,1)) ~= 0 && (A(j,k,1)) ~= 2047 || (A(j,k,2)) ~= 0 && (A(j,k,2)) ~= 2047 || (A(j,k,3)) ~= 0 && (A(j,k,3)) ~= 2047 || (A(j,k,4)) ~= 0 && (A(j,k,4)) ~= 2047 || (A(j,k,5)) ~= 0 && (A(j,k,5)) ~= 2047 || (A(j,k,6)) ~= 0 && (A(j,k,6)) ~= 2047 || (A(j,k,7)) ~= 0 && (A(j,k,7)) ~= 2047 || (A(j,k,8)) ~= 0 && (A(j,k,8)) ~= 2047;
for d = 1:8;
Rrs(j,k,d) = single((pi*((single(A(j,k,d))*kf(d,1)/ebw(1,d)) - ray_rad{1,1}(1,d))*ESd^2)/(irr(1,d)*TZ*TV)); % Radiometrically calibrate and convert to Rrs (adapted from Radiometric Use of WorldView-2 Imagery(
end
else Rrs(j,k,:) = NaN;
end
end
end
clear A
%% Output reflectance image
% if Rrs_write == 1;
% if id(4) == '3'
% info = geotiffinfo(images);
% geoTags = info.GeoTIFFTags.GeoKeyDirectoryTag;
% tiffTags = struct('TileLength',1024,'TileWidth',1024);
% Z = [loc_out,id,'_',loc,'_RrsBT']
% geotiffwrite(Z,Rrs,R(1,1),'GeoKeyDirectoryTag',geoTags,'TiffType','bigtiff','TiffTags',tiffTags);
% else
% Z = [loc_out,id,'_',loc,'_Rrs']
% geotiffwrite(Z,Rrs,R(1,1),'CoordRefSysCode',coor_sys);
% end
% end
if d_t > 0; % Run DT and/or rrs conversion; otherwise end
%% Setup for Deglint, Bathymetry, and Decision Tree
b = 1;
t = 1;
u = 1;
y = 0;
v = 0;
num_pix = 0;
sum_SD(b) = 0;
sum_veg(t) = 0;
sum_veg2(t) = 0;
dead_veg(t) = 0;
sum_water_rrs(u) = 0;
sz_ar = sz(1)*sz(2);
water = zeros(sz_ar,9);
for j = 1:sz(1);
for k = 1:sz(2);
if isnan(Rrs(j,k,1)) == 0
num_pix = num_pix +1; % Count number of non-NaN pixels
c_val(num_pix) = Rrs(j,k,1); % Record coastal band value for use in cloud mask prediction
if (Rrs(j,k,7) - Rrs(j,k,2))/(Rrs(j,k,7) + Rrs(j,k,2)) < 0.65 && Rrs(j,k,5) > Rrs(j,k,4) && Rrs(j,k,4) > Rrs(j,k,3) % Sand & Developed
sum_SD(b) = sum(Rrs(j,k,6:8));
b = b+1;
elseif (Rrs(j,k,8) - Rrs(j,k,5))/(Rrs(j,k,8) + Rrs(j,k,5)) > 0.65 && Rrs(j,k,7) > Rrs(j,k,3); % Identify vegetation (excluding grass)
if ((Rrs(j,k,7) - Rrs(j,k,2))/(Rrs(j,k,7) + Rrs(j,k,2))) > 0.20; % Shadow filter
sum_veg(t) = sum(Rrs(j,k,3:5)); % Sum bands 3-5 for selected veg to distinguish wetland from upland
sum_veg2(t) = sum(Rrs(j,k,7:8));
dead_veg(t) = (((Rrs(j,k,7) - Rrs(j,k,4))/3) + Rrs(j,k,4)) - Rrs(j,k,5); % Compute difference of predicted B5 value from actual valute
t = t+1;
end
elseif Rrs(j,k,8) < 0.11 && Rrs(j,k,1) > 0 && Rrs(j,k,2) > 0 && Rrs(j,k,3) > 0 && Rrs(j,k,4) > 0 && Rrs(j,k,5) > 0 && Rrs(j,k,6) > 0 && Rrs(j,k,7) > 0 && Rrs(j,k,8) > 0; % Identify glint-free water
water(u,1:8) = double(Rrs(j,k,:));
water_rrs(1:6) = Rrs(j,k,1:6)./(zeta + G.*Rrs(j,k,1:6));
if water_rrs(4) > water_rrs(2) && water_rrs(4) < 0.12 && water_rrs(5) < water_rrs(3)
sum_water_rrs(u) = sum(water_rrs(3:5));
end
u = u+1;
if Rrs(j,k,8)<Rrs(j,k,7) && Rrs(j,k,6)<Rrs(j,k,7) && Rrs(j,k,6)<Rrs(j,k,5) && Rrs(j,k,4)<Rrs(j,k,5) && Rrs(j,k,4)<Rrs(j,k,3)% NDGI to identify glinted water pixels (some confusion w/ clouds)
v = v+1;
water(u,9) = 2; % Mark array2<array1 glinted pixels
elseif Rrs(j,k,8)>Rrs(j,k,7) && Rrs(j,k,6)>Rrs(j,k,7) && Rrs(j,k,6)>Rrs(j,k,5) && Rrs(j,k,4)>Rrs(j,k,5) && Rrs(j,k,4)>Rrs(j,k,3)
v = v+1;
water(u,9) = 3; % Mark array2>array1 glinted pixels
else water(u,9) = 1; % Mark records of glint-free water
end
elseif Rrs(j,k,8)<Rrs(j,k,7) && Rrs(j,k,6)<Rrs(j,k,7) && Rrs(j,k,6)<Rrs(j,k,5) && Rrs(j,k,4)<Rrs(j,k,5) && Rrs(j,k,4)<Rrs(j,k,3)
water(u,1:8) = double(Rrs(j,k,:));
water(u,9) = 2; % Mark array2<array1 glinted pixels
u = u+1;
v = v+1;
elseif Rrs(j,k,8)>Rrs(j,k,7) && Rrs(j,k,6)>Rrs(j,k,7) && Rrs(j,k,6)>Rrs(j,k,5) && Rrs(j,k,4)>Rrs(j,k,5) && Rrs(j,k,4)>Rrs(j,k,3)
water(u,9) = 3; % Mark array2>array1 glinted pixels
water(u,1:8) = double(Rrs(j,k,:));
u = u+1;
v = v+1;
% elseif (Rrs(j,k,4)-Rrs(j,k,8))/(Rrs(j,k,4)+Rrs(j,k,8)) < 0.55 && Rrs(j,k,8) < 0.2 && (Rrs(j,k,7)-Rrs(j,k,2))/(Rrs(j,k,7)+Rrs(j,k,2)) < 0.1 && (Rrs(j,k,8)-Rrs(j,k,5))/(Rrs(j,k,8)+Rrs(j,k,5)) < 0.3 && Rrs(j,k,1) > 0 && Rrs(j,k,2) > 0 && Rrs(j,k,3) > 0 && Rrs(j,k,4) > 0 && Rrs(j,k,5) > 0 && Rrs(j,k,6) > 0 && Rrs(j,k,7) > 0 && Rrs(j,k,8) > 0; % Identify glinted water
% water(u,1:8) = double(Rrs(j,k,:));
% u = u+1;
% v = v+1;
end
end
end
end
n_water = u; % Number of water pixels used to derive E_glint relationships
n_glinted = v; % Number of glinted water pixels
idx = find(water(:,1) == 0);
water(idx,:) = [];
water7 = water(:,7);
water8 = water(:,8);
mnNIR1 = min(water7(water7>0)); % Positive minimum Band 7 value used for deglinting
mnNIR2 = min(water8(water8>0)); % Positive minimum Band 8 value used for deglinting
idx_gf = find(water(:,9)==1); % Glint-free water
water_gf = water(idx_gf,1:8);
% Identify optically deep water average spectrum
bn = 7; % Band number
pctl_l = 5; % Percentile (5th percentile value of glint-free water n-band values chosen based on visual analysis of density slicing of Rrs image)
pctl_u = 15;
clear water_gfidx water_odw m0 m1
water_gfidx = find(water_gf(:,bn) == prctile(water_gf(:,bn),pctl_l) & water_gf(:,bn) <= prctile(water_gf(:,bn),pctl_u));
water_odw(:,1:8) = (water_gf(water_gfidx(1:end),1:8)); % Li et al. Dove BGR corresponds to WV2 BGY center wavelengths
% Equations from Li et al. 2019 & Hu et al. 2012
for h = 1:size(water_odw,1)
% w1(h) = water_odw(h,3) - (water_odw(h,1) + (546-427)/(659-427)*(water_odw(h,5) - water_odw(h,1))); % Hu et al. 2012
w2(h) = water_odw(h,3) - 0.46*water_odw(h,4) - 0.54*water_odw(h,1); % Li et al. 2019
end
if exist('w2')==1
w = median(w2(w2<0));
else w = 0;
end
if w > -0.0005
m0 = 0;
m1 = 0;
Update = 'Too Turbid for Benthic Mapping'
else
chla = 10^(-0.4909 + 191.659*w) % Hu et al. 2012 (Kerr limited chla to 1.0mg/m3; 0.1 mg/m3 WV Cay Sal most accurate value used)
m0 = 52.083*exp(2.711*chla) % Revised from Li et al. 2019 with exponential scalar derived from Kerr FK WV image field data tuning parameters
m1 = 50.156*exp(2.711*chla) % TARGET: 64.3 +/- 0.5 & 62.6 +/- 0.5, Predicted: 67.2 & 64.7
end
Kd = [0.036 0.037 0.075 0.25 0.415]; %1.416]; %(Based on Kerr 2018 Fig 7a chl-conc 0.1 mg/m3 i.e. lowest RMSE water-depth predictor values)
if v > 0.25*u
Update = 'Deglinting'
id2 = 'deglinted';
for b = 1:6 %% Calculate linear fitting of all MS bands vs NIR1 & NIR2 for deglinting in DT (Hedley et al. 2005)
if b == 1 || b == 4 || b == 6
slope1 = water(:,b)\water(:,8);
else slope1 = water(:,b)\water(:,7);
end
E_glint(1,b) = single(slope1);
end
E_glint % = [0.8075 0.7356 0.8697 0.7236 0.9482 0.7902]
else Update = 'Glint-free'
id2 = 'glintfree';
end
%% Edge Detection via Morphological Index (improved over Huang & Zhang 2011, Ma et al. 2019)
waterind = uint16((Rrs(:,:,3)-Rrs(:,:,8))./(Rrs(:,:,3)+Rrs(:,:,8)) > 0.15);
img_sub2 = Rrs(:,:,2);
img_sub5 = Rrs(:,:,5);
img_sub7 = Rrs(:,:,7);
Rrs_cloud = img_sub2./img_sub7;
Rrs_cl2 = Rrs_cloud;
Rrs_cl3 = Rrs_cloud;
Rrs_cl2(Rrs_cloud >= 0.7) = 1;
Rrs_cl2(Rrs_cloud < 0.7) = 0;
Rrs_cl3(Rrs_cloud <= 0.9) = 1;
Rrs_cl3(Rrs_cloud > 0.9) = 0;
Rrs_clf = Rrs_cl2 + Rrs_cl3;
Rrs_clf(Rrs_clf < 2) = 0;
CLrrs = imbinarize(Rrs_clf);
CL1 = uint16(imtophat(CLrrs,strel('disk',100))) - waterind;
CL1(CL1<0) = 0;
CLe = imerode(CL1,strel('disk',20));
CLed = imdilate(CLe,strel('disk',150));
Cloud = imfill(CLed,'holes');
clear Rrs_cl2 Rrs_cl3 Rrs_clf CLrrs CL1 CLe CLed
Rrs_sh1 = Rrs_cloud;
Rrs_sh2 = Rrs_cloud;
Rrs_sh1(Rrs_cloud >= 1.3) = 1;
Rrs_sh1(Rrs_cloud < 1.3) = 0;
Rrs_sh2(Rrs_cloud <= 1.7) = 1;
Rrs_sh2(Rrs_cloud > 1.7) = 0;
Rrs_shf = Rrs_sh1 + Rrs_sh2;
Rrs_shf(Rrs_shf < 2) = 0;
SHrrs = imbinarize(Rrs_shf);
Shadow = uint16(imtophat(SHrrs,strel('square',20)));
clear Rrs_sh1 Rrs_sh2 Rrs_shf SHrrs
Rrs_map = img_sub5./img_sub7;
Rrs_map2 = Rrs_map;
Rrs_map3 = Rrs_map;
Rrs_map2(Rrs_map >= 0.7) = 1;
Rrs_map2(Rrs_map < 0.7) = 0;
Rrs_map3(Rrs_map <= 1.1) = 1;
Rrs_map3(Rrs_map > 1.1) = 0;
Rrs_mapf = Rrs_map2 + Rrs_map3;
Rrs_mapf(Rrs_mapf < 2) = 0;
BWrrs = imbinarize(Rrs_mapf);
BW1 = uint16(imtophat(BWrrs,strel('square',30))) - waterind;
BW1 = imdilate(BW1,strel('square',5)); % Expand developed to include shadows
BW1(BW1<0) = 0;
Cloud = Cloud - BW1;
Cloud(Cloud<0) = 0;
cld_idx = 0;
if size(find(Cloud ==1),1) > 0.060*szA(1)*szA(2)
cld_idx = 1;
end
% ns = 2000;
% BW = uint16(imtophat(BWrrs,strel('square',ns)));
% CC = bwconncomp(BW);
% numPixels = cellfun(@numel,CC.PixelIdxList);
% BW1idx = find(numPixels > 1000);
% CC.PixelIdxList = CC.PixelIdxList(BW1idx);
% CC.NumObjects = size(BW1idx,2);
% BW3 = uint16(labelmatrix(CC));
% BW3(BW3>0) = 1;
% BW3e = uint16(imerode(BW3,strel('disk',100)));
% BW3ed = uint16(imdilate(BW3e,strel('square',200)));
% BW4 = imfill(BW3ed,'holes');
BAI = (img_sub2 - img_sub7)./(img_sub2 + img_sub7); % Built Area Index
BAI = BAI * -1; % Dev & soil negative, soil more negative (water high positive)
BAI = imbinarize(BAI);
BAI = imerode(BAI,strel('square',5));
clear BW3 BW3e BW3ed BW2 BWrrs BWnew BWnewe BW1idx
Ztest = [loc_out,id,'_',loc,'_BW1']
geotiffwrite(Ztest,BW1,R(1,1),'CoordRefSysCode',coor_sys);
Ztest = [loc_out,id,'_',loc,'_BAI']
geotiffwrite(Ztest,BAI,R(1,1),'CoordRefSysCode',coor_sys);
%% Determine Rrs-infinite from glint-free water pixels
rrs_inf = [0.00512 0.00686 0.008898 0.002553 0.001506 0.000403]; % Derived from Rrs_Kd_Model.xlsx for Default values
%% Calculate target class metrics
avg_SD_sum = mean(sum_SD(:));
stdev_SD_sum = std(sum_SD(:));
avg_veg_sum = mean(sum_veg(:))
avg_dead_veg = mean(dead_veg(:));
avg_mang_sum = mean(sum_veg2(:));
idx_water2 = find(sum_water_rrs==0);
sum_water_rrs(idx_water2) = [];
avg_water_sum = mean(sum_water_rrs(:));
if cl_cov > 0
num_cld_pix = round(num_pix*cl_cov*0.01); % Number of cloud pixels (rounded down to nearest integer) based on metadata-reported percent cloud cover
srt_c = sort(c_val,'descend'); % Sort all pixel blue-values in descending order. Cloud mask threshold will be num_cld_pix'th highest value
cld_mask = srt_c(num_cld_pix); % Set cloud mask threshold
else cld_mask = max(c_val)+1;
end
Bathy = single(zeros(szA(1),szA(2))); % Preallocate for Bathymetry
Rrs_deglint = single(zeros(5,1)); % Preallocate for deglinted Rrs
Rrs_0 = single(zeros(5,1)); %Preallocation for water-column corrected Rrs
map = zeros(szA(1),szA(2),'uint8'); % Create empty matrix for classification output
if d_t == 1; % Execute Deglinting, rrs, Bathymetry
if v > u*0.25
for j = 1:szA(1)
for k = 1:szA(2)
if isnan(Rrs(j,k,1)) == 0 && Rrs(j,k,8)<0.2
% Deglint equation
Rrs_deglint(1,1) = (Rrs(j,k,1) - (E_glint(1)*(Rrs(j,k,8) - mnNIR2)));
Rrs_deglint(2,1) = (Rrs(j,k,2) - (E_glint(2)*(Rrs(j,k,7) - mnNIR1)));
Rrs_deglint(3,1) = (Rrs(j,k,3) - (E_glint(3)*(Rrs(j,k,7) - mnNIR1)));
Rrs_deglint(4,1) = (Rrs(j,k,4) - (E_glint(4)*(Rrs(j,k,8) - mnNIR2)));
Rrs_deglint(5,1) = (Rrs(j,k,5) - (E_glint(5)*(Rrs(j,k,7) - mnNIR1)));
Rrs_deglint(6,1) = (Rrs(j,k,6) - (E_glint(6)*(Rrs(j,k,8) - mnNIR2)));
% Convert above-surface Rrs to below-surface rrs (Kerr et al. 2018)
Rrs_0(1:5) = Rrs_deglint(j,k,1:5)./(zeta + G.*Rrs_deglint(j,k,1:5)); % Convert above-surface Rrs to subsurface rrs (Kerr et al. 2018, Lee et al. 1998)
b1 = 63.6; % Turning parameters (Kerr 2018)
b0 = -60.25;
dp = b1*real(log(1000*Rrs_0(2))/log(1000*Rrs_0(3))) + b0; % Calculate depth (Stumpf 2003 ratio transform with Kerr et al. 2018 coefficients)
if dp < 15 && dp > 0 % Parameters based on Kerr 2018 RMSE-based recommended constraints (depths greater than 15m inaccurate)
Bathy(j,k) = dp;
end
for d = 1:5
Rrs(j,k,d) = real(((Rrs_0(d)-rrs_inf(d))/exp(-2*Kd(1,d)*dp))+rrs_inf(d)); % Calculate water-column corrected benthic reflectance (Traganos 2017 & Maritorena 1994)
end
end
end
end
else % For glint-free/low-glint images
for j = 1:szA(1)
for k = 1:szA(2)
if isnan(Rrs(j,k,1)) == 0 && Rrs(j,k,8)<0.2
Rrs_0(1:5) = Rrs(j,k,1:5)./(zeta + G.*Rrs(j,k,1:5)); % Convert above-surface Rrs to subsurface rrs (Kerr et al. 2018, Lee et al. 1998)
b1 = 63.6; % Turning parameters (Kerr 2018 Table 6 average of 2 forward-modeling WorldView-2 results)
b0 = -60.25;
dp = b1*real(log(1000*Rrs_0(2))/log(1000*Rrs_0(3))) + b0; % Calculate depth (Stumpf 2003 ratio transform with Kerr et al. 2018 coefficients)
if dp < 15 && dp > 0 % Parameters based on Kerr 2018 RMSE-based recommended constraints (depths greater than 15m inaccurate)
Bathy(j,k) = dp;
else dp = 0;
end
for d = 1:5
Rrs(j,k,d) = real(((Rrs_0(d)-rrs_inf(d))/exp(-2*Kd(1,d)*dp))+rrs_inf(d)); % Calculate water-column corrected benthic reflectance (Traganos 2017 & Maritorena 1994)
end
end
end
end
end
elseif d_t == 2; % Only run for Deglinted Rrs and Bathymetry, not Decision Tree
update = 'Running DT'
BS = 2;
WA = 3;
DG = 5;
MA = 6;
SC = 7;
FW = 10;
FU = 9;
UG = 8;
dev = 11;
p = 1;
for j = 1:szA(1)
for k = 1:szA(2)
if isnan(Rrs(j,k,1)) == 0
%% Cloud Cover
if Cloud(j,k) == 1 && BW1(j,k) ~= 1
map(j,k) = 1; % Cloud
%% Vegetation
elseif (Rrs(j,k,7) - Rrs(j,k,5))/(Rrs(j,k,7) + Rrs(j,k,5)) > 0.20 && Rrs(j,k,7) > Rrs(j,k,3) % Vegetation pixels (NDVI)
if ((Rrs(j,k,7) - Rrs(j,k,2))/(Rrs(j,k,7) + Rrs(j,k,2))) < 0.20 && (Rrs(j,k,7) - Rrs(j,k,8))/(Rrs(j,k,7) + Rrs(j,k,8)) > 0.01; % Shadowed-vegetation filter (B7/B8 ratio excludes marsh, which tends to have very similar values here)
map(j,k) = 0; % Shadow
elseif sum(Rrs(j,k,3:5)) < avg_veg_sum
if (Rrs(j,k,3) - Rrs(j,k,8))/(Rrs(j,k,3) + Rrs(j,k,8)) > -0.75 % ML
if (Rrs(j,k,7) - Rrs(j,k,5))/(Rrs(j,k,7) + Rrs(j,k,5)) > 0.75 % M
map(j,k) = FW; % Forested Wetland
elseif sum(Rrs(j,k,3:5)) > 0.12 && sum(Rrs(j,k,7:8)) > 0.45 % ML
map(j,k) = FU; % FORESTED UPLAND
elseif (Rrs(j,k,7) - Rrs(j,k,5))/(Rrs(j,k,7) + Rrs(j,k,5)) > 0.60
map(j,k) = FW; % Forested Wetland
elseif Rrs(j,k,7) < 0.3 && sum(Rrs(j,k,7:8)) > 0.25
if (Rrs(j,k,5) - Rrs(j,k,3))/(Rrs(j,k,5) + Rrs(j,k,3)) > 0.1
map(j,k) = DG; % Dead Grass
elseif Rrs(j,k,7) < 0.27 && sum(Rrs(j,k,7:8)) < 0.5
map(j,k) = MA; % Marsh
else map(j,k) = FU; % Forested Upland
end
end
elseif (Rrs(j,k,4) - Rrs(j,k,5))/(Rrs(j,k,4) + Rrs(j,k,5)) > 0.08
map(j,k) = 6; % Marsh (was algal flat)
else map(j,k) = FU; % Forested Upland
end
elseif (Rrs(j,k,8) - Rrs(j,k,5))/(Rrs(j,k,8) + Rrs(j,k,5)) > 0.65
map(j,k) = FU; % Forested Upland
elseif Rrs(j,k,7) < 0.4 % Marsh, Scrub, Grass, Dead Veg
if (Rrs(j,k,4) - Rrs(j,k,5))/(Rrs(j,k,4) + Rrs(j,k,5)) > 0.08
map(j,k) = 6; % Marsh (was algal flat)
elseif (Rrs(j,k,5) - Rrs(j,k,3))/(Rrs(j,k,5) + Rrs(j,k,3)) > 0.05 %&& Rrs(j,k,7) < 0.27 % Agriculture or senesced veg/grass
map(j,k) = DG; % Dead veg
else map(j,k) = UG; % Grass
end
% elseif sum(Rrs(j,k,7:8)) < 0.8 && sum(Rrs(j,k,7:8)) > 0.65 % Live grass high, dead grass low
% map(j,k) = 10; % Upland Forest
else map(j,k) = SC; % Scrub/shrub
end
%% Developed and Soil
elseif (Rrs(j,k,7) - Rrs(j,k,2))/(Rrs(j,k,7) + Rrs(j,k,2)) < 0.60 && Rrs(j,k,5) > Rrs(j,k,4) && waterind(j,k) == 0 %Rrs(j,k,8) > 0.1 % && Rrs(j,k,4) > Rrs(j,k,3)
if Rrs(j,k,5)/Rrs(j,k,7) > 0.7 && Rrs(j,k,5)/Rrs(j,k,7) < 1.1
if BAI(j,k) == 0 && BW1(j,k) == 1 %BW4(j,k) == 1
map(j,k) = dev; %Developed. Was: BS; % Soil (fallow field)
elseif BAI(j,k) == 1 && BW1(j,k) == 0
map(j,k) = BS; % Soil
elseif BW1(j,k) == 1
if sum(Rrs(j,k,1:2))<0.35
if sum(Rrs(j,k,6:8)) < 0.85%avg_SD_sum
map(j,k) = dev; % Developed
else map(j,k) = BS; % Soil
end
elseif sum(Rrs(j,k,1:2)) > 0.6
map(j,k) = dev;
else map(j,k) = dev;
end
elseif sum(Rrs(j,k,6:8)) < avg_SD_sum
map(j,k) = dev;
else map(j,k) = dev; % Developed
end
else map(j,k) = BS; % Soil
end
%% Water
elseif Rrs(j,k,8)<0.2 && Rrs(j,k,8)>0|| Rrs(j,k,8)<Rrs(j,k,7) && Rrs(j,k,6)<Rrs(j,k,7) && Rrs(j,k,6)<Rrs(j,k,5) && Rrs(j,k,4)<Rrs(j,k,5) && Rrs(j,k,4)<Rrs(j,k,3) && Rrs(j,k,8)>0 || Rrs(j,k,8)>Rrs(j,k,7) && Rrs(j,k,6)>Rrs(j,k,7) && Rrs(j,k,6)>Rrs(j,k,5) && Rrs(j,k,4)>Rrs(j,k,5) && Rrs(j,k,4)>Rrs(j,k,3) && Rrs(j,k,8)>0% Identify all water (glinted and glint-free)
if v > u*0.25 && u>0.1*num_pix
% Deglint equation
Rrs_deglint(1,1) = (Rrs(j,k,1) - (E_glint(1)*(Rrs(j,k,8) - mnNIR2)));
Rrs_deglint(2,1) = (Rrs(j,k,2) - (E_glint(2)*(Rrs(j,k,7) - mnNIR1)));
Rrs_deglint(3,1) = (Rrs(j,k,3) - (E_glint(3)*(Rrs(j,k,7) - mnNIR1)));
Rrs_deglint(4,1) = (Rrs(j,k,4) - (E_glint(4)*(Rrs(j,k,8) - mnNIR2)));
Rrs_deglint(5,1) = (Rrs(j,k,5) - (E_glint(5)*(Rrs(j,k,7) - mnNIR1)));
Rrs_deglint(6,1) = (Rrs(j,k,6) - (E_glint(6)*(Rrs(j,k,8) - mnNIR2)));
% Convert above-surface Rrs to below-surface rrs (Kerr et al. 2018)
Rrs_0(1:5) = Rrs_deglint(1:5)./(zeta + G.*Rrs_deglint(1:5)); % Was Rrs_0=
% Relative depth estimate
dp = m0*real(log(1000*Rrs_0(1))/log(1000*Rrs_0(3))) - m1; % Calculate depth (Stumpf 2003 ratio transform with Kerr et al. 2018 coefficients)
if dp < 15 && dp > 0 % Parameters based on Kerr 2018 RMSE-based recommended constraints (depths greater than 15m inaccurate)
Bathy(j,k) = dp;
else dp = 0;
end
% for d = 1:5
% Rrs(j,k,d) = real(((Rrs_0(d)-rrs_inf(d))/exp(-2*Kd(1,d)*dp))+rrs_inf(d)); % Calculate water-column corrected benthic reflectance (Traganos 2017 & Maritorena 1994)
% end
%% DT
if Shadow(j,k) == 1 && max(Rrs(j,k,:)) == Rrs(j,k,2) % Max band3-6 = turbid/shallow water
map(j,k) = 0; % Shadow
else map(j,k) = WA; % Deep water
end
else % For glint-free/low-glint images
Rrs_0(1:5) = Rrs(j,k,1:5)./(zeta + G.*Rrs(j,k,1:5)); % Convert above-surface Rrs to subsurface rrs (Kerr et al. 2018, Lee et al. 1998)
dp = m0*real(log(1000*Rrs_0(2))/log(1000*Rrs_0(3))) - m1; % Calculate depth (Stumpf 2003 ratio transform with Kerr et al. 2018 coefficients)
if dp < 15 && dp > 0 % Parameters based on Kerr 2018 RMSE-based recommended constraints (depths greater than 15m inaccurate)
Bathy(j,k) = dp;
else dp = 0;
end
%% DT
if Shadow(j,k) == 1 && max(Rrs(j,k,:)) == Rrs(j,k,2) % Max band3-6 = turbid/shallow water
map(j,k) = 0; % Shadow/Unclassified
else map(j,k) = WA; % Deep water
% end
end
end % if v>u
end % If water/land
end % If isnan
end % k
end % j
end
%% DT Filter
if filter > 0
update = 'Filtering'
dt_filt = DT_Filter(map,filter,sz(1),sz(2),dev,FW,FU,UG,WA);
if cld_idx == 1
AA = [loc_out,id,'_',loc,'_SOALCHI_filt_',num2str(filter),'_Cloudy'];
else AA = [loc_out,id,'_',loc,'_SOALCHI_filt_',num2str(filter)];
end
geotiffwrite(AA,dt_filt,R(1,1),'CoordRefSysCode',coor_sys);
else
Z1 = [loc_out,id,'_',loc,'_Map_nofilt'];
geotiffwrite(Z1,map,R(1,1),'CoordRefSysCode',coor_sys);
end
% TP(z,1) = m0;
% TP(z,2) = m1;
% TP(z,3) = chla;
%% Output images
% Z = [loc_out,id,'_',loc,'_Bathy_MAv1'];
% geotiffwrite(Z,Bathy,R(1,1),'CoordRefSysCode',coor_sys);
% Z2 = [Rrs_out,id,'_',loc,'_Rrs']; % last=52
% geotiffwrite(Z2,Rrs,R(1,1),'CoordRefSysCode',coor_sys);
%
end % If dt>0
wtime = toc;
time_min = wtime/60;
fprintf(1,'Matlab CPU time (minutes) = %f\n', time_min);
end
|
github | ruihou/caffe-3d-master | classification_demo.m | .m | caffe-3d-master/matlab/demo/classification_demo.m | 5,466 | utf_8 | 45745fb7cfe37ef723c307dfa06f1b97 | function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github | shainova/EMLN-master | bipartite_modularity_diag_coupling.m | .m | EMLN-master/NEE2017/Modularity/bipartite_modularity_diag_coupling.m | 2,782 | utf_8 | 9feea2fb0a17cc601ebb4f1774696b75 | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
% This function lays out the B matirx which can be fed to the Louvain
% algorithm to calculate Q. It is programmed SPECIFICALLY for a a multilayer
% network with 2 bipartite layers connected via one common set of nodes
% (diagonal coupling).
function [B_multilayer,twomu] = bipartite_modularity_diag_coupling(A1,A2,gamma,omega,show_Bmax)
twomu=0; % Initialize twomu
%==== Set up the modularity matrix for layer 1: B_1ayer1
% This is simply modularity for a bipartite single-layer network
%====
[m,n]=size(A1);
N1=m+n;
k=sum(A1,2);
d=sum(A1,1);
mm=sum(k);
B_bip=A1-gamma*k*d/mm;
B=zeros(N1,N1);
% One should be VERY careful in how the B matrix is composed.
B(1:m,m+1:N1)=B_bip;
B(m+1:N1,1:m)=B_bip';
B_layer1=B;
twomu=twomu+2*mm; % Add the 2*mm contributions:
%==== Set up the modularity matrix for layer 2: B_1ayer2
% This is simply modularity for a bipartite single-layer network
%====
[p,q]=size(A2);
N2=p+q;
k=sum(A2,2);
d=sum(A2,1);
mm=sum(k);
B_bip=A2-gamma*k*d/mm;
B=zeros(N2,N2);
B(1:p,p+1:N2)=B_bip;
B(p+1:N2,1:p)=B_bip';
B_layer2=B;
twomu=twomu+2*mm; % Add the 2*mm contributions:
%The second term in twomu should be the total weight of all interlayer
%edges, i.e.,since we only have interlayer edges between nodes in set1,
%which is on the matrices rows, we use m:
twomu=twomu+2*omega*m;
%==== Now set up the B matrix of the multilayer
% by combining the individual B matrices
%====
B_multilayer=zeros(N1+N2,N1+N2); % create the matrix, filled with zeros
B_multilayer(1:N1,1:N1)=B_layer1; % Modularity matrix of layer 1 (set1 and set2)
B_multilayer(N1+1:N1+N2,N1+1:N1+N2)=B_layer2; % Modularity matrix of layer 2 (set1 and set3)
B_multilayer(N1+1:N1+m,1:m)=omega*diag(ones(m,1),0); % Interlayer interactions between the nodes which are in the rows (and hence the use of m)
B_multilayer(1:m,N1+1:N1+m)=omega*diag(ones(m,1),0); % Interlayer interactions between the nodes which are in the rows (and hence the use of m)
if ~issymmetric(B_multilayer)
disp('The modularity matrix is NOT symmetric!!')
end
% The value above which there will be an abrupt drop in intra-layer
% merges (see Bazzi et al 2015, pg. 32):
if show_Bmax==1
m1=max(max(B_layer1));
m2=max(max(B_layer2));
disp(max(m1,m2));
end
end
|
github | shainova/EMLN-master | modularity_weighted_multilayer_null2.m | .m | EMLN-master/NEE2017/Modularity/modularity_weighted_multilayer_null2.m | 4,423 | utf_8 | a439e7f70710149743c202654e640b2b | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
% This function is for the second null model from the publication
% (reshuffling node identities)
% The function takes as input if to permute the order of rows (=hosts) or
% columns(=parasites) by entering 1 or 2, respectively. It also receives
% the number of realizations to perform and the output folder to where
% results are written. It writes as output a vector (Q) with the maximum
% modularity values calculated by the function and a matrix (S) with module
% affiliations of the state nodes. The number of columns in S corresponds
% to the number of realizations (reshuffled networks) and the number of
% rows is of length num_layers*num_nodes. The post processing of the output
% is done in R and expalined in the R code. The number of modules is
% calculated from S during the post processing.
function []=modularity_weighted_multilayer_null2(hosts_or_parasites,runs,outputfolder)
%% initialize
gamma=1;
Q_runs=[];
S_runs=[];
files=dir('host_parasite_abundance_weighted_layer_*.csv');
omega=importdata('interlayer_relative_abundance_matrix.csv');
%% Run main loop
for r=1:runs
r
%% Load layers and permute
A=cell(1,length(files));
for i = 1:length(files)
bip_data=importdata(files(i).name);
[p,q]=size(bip_data);
%% Reshuffle the node order
% The "nodal" null model (sensu Bassett et al., 2011 PNAS)
% reshuffles the interlayer edges between nodes and their
% counterparts in two consecutive layers by permuting the node
% labels separately in each layer so that node identity is not
% preserved. In the bipartite networks, this is akin to permuting
% the order of rows (or columns) for every given layer. You can
% permute by rows for hosts or by columsns for parasites by
% commenting/uncommenting the following lines:
if hosts_or_parasites==1
rowPermutations=randperm(p);
bip_data=bip_data(rowPermutations,:);
end
if hosts_or_parasites==2
colPermutations=randperm(q);
bip_data=bip_data(:,colPermutations);
end
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=bip_data;
onemode((p+1):(p+q), 1:p)=bip_data';
A{i}=onemode;
if ~issymmetric(A{i})
disp(['layer ',num2str(i),' is NOT symmetric'])
end
end
N=length(A{1});
T=length(A);
%% Create the modularity matrix
B=spalloc(N*T,N*T,N*N*T+2*N*T);
twomu=0;
for s=1:T
k=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
k=k(1:p); % This is just the first set
d=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
d=d((p+1):(p+q)); % This is just the 2nd set
m=sum(k); % Note the m instead of twom as in unipartite
twomu=twomu+m; % Note that we add m and not 2m to the mu. In the unipartite version this is twomu=twomu+twom
indx=[1:N]+(s-1)*N;
% This calculates the matrix of probabilities accroding to eq. 15 in
% Barber 2007
P_ij=zeros(p,q);
for i=1:p
for j=1:q
P_ij(i,j)=k(i)*d(j);
end
end
% Here again we have to create a symmetric adjacency matrix out of the
% bipartite.
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=P_ij;
onemode((p+1):(p+q), 1:p)=P_ij';
P_ij=onemode;
B(indx,indx)=A{s}-gamma*P_ij/m; % Note the P_ij instead of k*k' as in the unipartite version. also the m in stead of 2m
end
twomu=twomu+2*sum(sum(omega));
%% Run modularity
[S,Q] = genlouvain(B,10000,0,1,1);
Q_runs = [Q_runs Q/twomu];
S_runs = [S_runs S];
end
%% Write results
if hosts_or_parasites==1
dlmwrite([outputfolder,'/Q_null2_hosts.csv'],full(Q_runs)',',');
dlmwrite([outputfolder,'/S_null2_hosts.csv'],S_runs,',');
end
if hosts_or_parasites==2
dlmwrite([outputfolder,'/Q_null2_parasites.csv'],full(Q_runs)',',');
dlmwrite([outputfolder,'/S_null2_parasites.csv'],S_runs,',');
end
end
|
github | shainova/EMLN-master | modularity_interlayer_infinity.m | .m | EMLN-master/NEE2017/Modularity/modularity_interlayer_infinity.m | 4,086 | utf_8 | 1fa8825e8c7b6600a5d00d009e204c44 | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
% This function analyses the modular structure of the observed temporal
% multilayer networkwhen interlayer edges are infinity.
% The input is the number of realizations (runs) the function should
% perform due to the heuristic nature of the general Louvain algorithm, and
% the folder to which to write the results. It writes as output a vector
% (Q) with the maximum modularity values calculated by the function and a
% matrix (S) with module affiliations of the state nodes. The number of
% columns in S corresponds to the number of realizations and the number of
% rows is of length num_layers*num_nodes. The post processing of the output
% is done in R and expalined in the R code. The number of modules is
% calculated from S during the post processing.
function []=modularity_interlayer_infinity(runs,outputfolder)
% initialize
gamma=1;
Q_runs=[];
S_runs=[];
files=dir('host_parasite_abundance_weighted_layer_*.csv'); % These are the different layers of the network, produced with the R code supplied.
% Bipartite networks have to be transformed to unipartite (square matrix).
A=cell(1,length(files));
for i = 1:length(files)
bip_data=importdata(files(i).name);
% Transform the pxq matrix into (p+q)x(p+q)
[p,q]=size(bip_data);
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=bip_data;
onemode((p+1):(p+q), 1:p)=bip_data';
A{i}=onemode;
if ~issymmetric(A{i})
disp(['layer ',num2str(i),' is NOT symmetric'])
end
end
N=length(A{1}); % Number of nodes (hosts+parasites)
T=length(A); % Number of layers
for r=1:runs
r
B=spalloc(N*T,N*T,N*N*T+2*N*T); % create an empty modularity matrix
twomu=0;
for s=1:T
%%%%%% BIPARTITE:
% In case of unipartite undirected networks the probability P of an edge exisiting between two nodes
% is proportional to the product of node degrees. This is
% k_is*k_js/2m_s in eq. 1 in the SI of the paper. Note the 2*m_s because it is an
% undirected unipartite network.
% In the bipartite case, P is k_is*d_js/m_s. and the division is over
% the number of edges m (see Barber 2007, eq. 15 for reasoning).
% When networks are weighted this explanation refers to the strength
% instead of degrees.
k=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
k=k(1:p); % This is just the first set
d=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
d=d((p+1):(p+q)); % This is just the 2nd set
m=sum(k); % Note the m instead of twom as in unipartite
twomu=twomu+m; % Note that we add m and not 2m to the mu. In the unipartite version this is twomu=twomu+twom
indx=[1:N]+(s-1)*N;
% This calculates the matrix of probabilities accroding to eq. 15 in
% Barber 2007
P_ij=zeros(p,q);
for i=1:p
for j=1:q
P_ij(i,j)=k(i)*d(j);
end
end
% Here again we have to create a smymetric adjacency matrix out of the bipartite.
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=P_ij;
onemode((p+1):(p+q), 1:p)=P_ij';
P_ij=onemode;
B(indx,indx)=A{s}-gamma*P_ij/m; % Note the P_ij instead of k*k' as in the unipartite version. also the m instead of 2m
end
% This makes all the interlayer edges with a value of 10000 which
% mimics infinity
omega=10000;
twomu=twomu+2*omega*N*(T-1);
B = B + omega*spdiags(ones(N*T,2),[-N,N],N*T,N*T);
[S,Q] = genlouvain(B,10000,0,1,1);
Q_runs = [Q_runs Q/twomu];
S_runs = [S_runs S];
end
dlmwrite([outputfolder,'/Q_obs_infinity.csv'],full(Q_runs)',',');
dlmwrite([outputfolder,'/S_obs_infinity.csv'],S_runs,',');
end
|
github | shainova/EMLN-master | modularity_weighted_multilayer_obs.m | .m | EMLN-master/NEE2017/Modularity/modularity_weighted_multilayer_obs.m | 4,156 | utf_8 | 266904c5c388af9b8be6e1a43d0732ab | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
% This function analyses the modular structure of the observed temporal
% multilayer network with quantitative interlayer AND intralyer edges. The
% input is the number of realizations (runs) the function should perform
% due to the heuristic nature of the general Louvain algorithm, and the
% folder to which to write the results. It writes as output a vector (Q)
% with the maximum modularity values calculated by the function and a
% matrix (S) with module affiliations of the state nodes. The number of
% columns in S corresponds to the number of realizations and the number of
% rows is of length num_layers*num_nodes. The post processing of the output
% is done in R and expalined in the R code. The number of modules is
% calculated from S during the post processing.
function []=modularity_weighted_multilayer_obs(runs,outputfolder)
% initialize
gamma=1;
Q_runs=[];
S_runs=[];
files=dir('host_parasite_abundance_weighted_layer_*.csv'); % These are the different layers of the network, produced with the R code supplied.
% Bipartite networks have to be transformed to unipartite (square matrix).
A=cell(1,length(files));
for i = 1:length(files)
bip_data=importdata(files(i).name);
% Transform the pxq matrix into (p+q)x(p+q)
[p,q]=size(bip_data);
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=bip_data;
onemode((p+1):(p+q), 1:p)=bip_data';
A{i}=onemode;
if ~issymmetric(A{i})
disp(['layer ',num2str(i),' is NOT symmetric'])
end
end
N=length(A{1}); % Number of nodes (hosts+parasites)
T=length(A); % Number of layers
for r=1:runs
r
B=spalloc(N*T,N*T,N*N*T+2*N*T); % create an empty modularity matrix
twomu=0;
for s=1:T
%%%%%% BIPARTITE:
% In case of unipartite undirected networks the probability P of an edge exisiting between two nodes
% is proportional to the product of node degrees. This is
% k_is*k_js/2m_s in eq. 1 in the SI of the paper. Note the 2*m_s because it is an
% undirected unipartite network.
% In the bipartite case, P is k_is*d_js/m_s. and the division is over
% the number of edges m (see Barber 2007, eq. 15 for reasoning).
% When networks are weighted this explanation refers to the strength
% instead of degrees.
k=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
k=k(1:p); % This is just the first set
d=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
d=d((p+1):(p+q)); % This is just the 2nd set
m=sum(k); % Note the m instead of twom as in unipartite
twomu=twomu+m; % Note that we add m and not 2m to the mu. In the unipartite version this is twomu=twomu+twom
indx=[1:N]+(s-1)*N;
% This calculates the matrix of probabilities accroding to eq. 15 in
% Barber 2007
P_ij=zeros(p,q);
for i=1:p
for j=1:q
P_ij(i,j)=k(i)*d(j);
end
end
% Here again we have to create a smymetric adjacency matrix out of the bipartite.
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=P_ij;
onemode((p+1):(p+q), 1:p)=P_ij';
P_ij=onemode;
B(indx,indx)=A{s}-gamma*P_ij/m; % Note the P_ij instead of k*k' as in the unipartite version. also the m instead of 2m
end
% Because all interlayer edges have different values, OMEGA IS A MATRIX.
% This matrix was produced using the accompanying R code.
omega=importdata('interlayer_relative_abundance_matrix.csv');
twomu=twomu+2*sum(sum(omega));
B = B+omega;
[S,Q] = genlouvain(B,10000,0,1,1);
Q_runs = [Q_runs Q/twomu];
S_runs = [S_runs S];
end
dlmwrite([outputfolder,'/Q_obs.csv'],full(Q_runs)',',');
dlmwrite([outputfolder,'/S_obs.csv'],S_runs,',');
end
|
github | shainova/EMLN-master | modularity_weighted_multilayer_null1.m | .m | EMLN-master/NEE2017/Modularity/modularity_weighted_multilayer_null1.m | 3,654 | utf_8 | a48fbfce9c1c4c393c423628e0ccad8c | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
% This function analyses the modular structure of the temporal multilaer
% networks reshuffled according to the first null model (reshuffling
% intralayer interactions). The set of reshuffled network layers was
% produced using the R code accompanying this publication.
% The function takes as input the number of realizations to perform, the
% folder where the reshuffled network layers are stored and the output
% folder to where results are written. It writes as output a vector (Q)
% with the maximum modularity values calculated by the function and a
% matrix (S) with module affiliations of the state nodes. The number of
% columns in S corresponds to the number of realizations (reshuffled
% networks) and the number of rows is of length num_layers*num_nodes. The
% post processing of the output is done in R and expalined in the R code.
% The number of modules is calculated from S during the post processing.
function []=modularity_weighted_multilayer_null1(runs,inputfolder,outputfolder)
% initialize
gamma=1;
Q_runs=[];
S_runs=[];
for r=1:runs
r
files=dir([inputfolder,'/network_',num2str(r),'_*.csv']);
A=cell(1,length(files));
for i = 1:length(files)
bip_data=importdata([inputfolder,'/',files(i).name]);
% Transform the pxq matrix into (p+q)x(p+q)
[p,q]=size(bip_data);
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=bip_data;
onemode((p+1):(p+q), 1:p)=bip_data';
A{i}=onemode;
if ~issymmetric(A{i})
error(['layer ',num2str(i),' is NOT symmetric'])
end
end
N=length(A{1});
T=length(A);
B=spalloc(N*T,N*T,N*N*T+2*N*T);
twomu=0;
for s=1:T
k=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
k=k(1:p); % This is just the first set
d=sum(A{s}); % this is the sum of degrees of the nodes in the two sets
d=d((p+1):(p+q)); % This is just the 2nd set
m=sum(k); % Note the m instead of twom as in unipartite
twomu=twomu+m; % Note that we add m and not 2m to the mu. In the unipartite version this is twomu=twomu+twom
indx=[1:N]+(s-1)*N;
% This calculates the matrix of probabilities accroding to eq. 15 in
% Barber 2007
P_ij=zeros(p,q);
for i=1:p
for j=1:q
P_ij(i,j)=k(i)*d(j);
end
end
% Here again we have to create a symetric adjacency matrix out of the
% bipartite.
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=P_ij;
onemode((p+1):(p+q), 1:p)=P_ij';
P_ij=onemode;
B(indx,indx)=A{s}-gamma*P_ij/m; % Note the P_ij instead of k*k' as in the unipartite version. also the m in stead of 2m
end
% This is if all interlayer edges have different values. OMEGA IS A
% MATRIX. Note that it is the same matrix used for the observed network
% because the null model only reshuffls the intralayer interactions.
omega=importdata('interlayer_relative_abundance_matrix.csv');
twomu=twomu+2*sum(sum(omega));
B = B+omega;
[S,Q] = genlouvain(B,10000,0,1,1);
Q_runs = [Q_runs Q/twomu];
S_runs = [S_runs S];
end
full(Q_runs)
dlmwrite([outputfolder,'/Q_null1.csv'],full(Q_runs)',',');
dlmwrite([outputfolder,'/S_null1.csv'],S_runs,',');
end
|
github | shainova/EMLN-master | modularity_weighted_multilayer_null3.m | .m | EMLN-master/NEE2017/Modularity/modularity_weighted_multilayer_null3.m | 3,373 | utf_8 | aa4169e5f07c13619ac8715f8a34ae15 | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
% This function is for the third null model from the publication
% (permuting the order of layers).
% The function takes as input the number of realizations to perform and the
% output folder to where results are written. It writes as output a vector
% (Q) with the maximum modularity values calculated by the function and a
% matrix (S) with module affiliations of the state nodes. The number of
% columns in S corresponds to the number of realizations (reshuffled
% networks) and the number of rows is of length num_layers*num_nodes. The
% post processing of the output is done in R and expalined in the R code.
% The number of modules is calculated from S during the post processing.
function []=modularity_weighted_multilayer_null3(runs,outputfolder)
%% initialize
gamma=1;
Q_runs=[];
S_runs=[];
files=dir('host_parasite_abundance_weighted_layer_*.csv');
omega=importdata('interlayer_relative_abundance_matrix.csv');
A=cell(1,length(files));
for i = 1:length(files)
bip_data=importdata(files(i).name);
% Transform the pxq matrix into (p+q)x(p+q)
[p,q]=size(bip_data);
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=bip_data;
onemode((p+1):(p+q), 1:p)=bip_data';
A{i}=onemode;
if ~issymmetric(A{i})
disp(['layer ',num2str(i),' is NOT symmetric'])
end
end
N=length(A{1});
T=length(A);
%% Main loop
for r=1:runs
r
%% Here we permute the order of the layers
layerPermutations=randperm(T);
A_perm=cell(T,1);
for x=1:T
A_perm{x}=A{layerPermutations(x)};
end
%% Calculate modularity matrix
B=spalloc(N*T,N*T,N*N*T+2*N*T);
twomu=0;
for s=1:T
k=sum(A_perm{s}); % this is the sum of degrees of the nodes in the two sets
k=k(1:p); % This is just the first set
d=sum(A_perm{s}); % this is the sum of degrees of the nodes in the two sets
d=d((p+1):(p+q)); % This is just the 2nd set
m=sum(k); % Note the m instead of twom as in unipartite
twomu=twomu+m; % Note that we add m and not 2m to the mu. In the unipartite version this is twomu=twomu+twom
indx=[1:N]+(s-1)*N;
% This calculates the matrix of probabilities accroding to eq. 15 in
% Barber 2007
P_ij=zeros(p,q);
for i=1:p
for j=1:q
P_ij(i,j)=k(i)*d(j);
end
end
% Here again we have to create a symmetric adjacency matrix out of the
% bipartite.
onemode=zeros(p+q,p+q);
onemode(1:p, (p+1):(p+q))=P_ij;
onemode((p+1):(p+q), 1:p)=P_ij';
P_ij=onemode;
B(indx,indx)=A_perm{s}-gamma*P_ij/m; % Note the P_ij instead of k*k' as in the unipartite version. also the m in stead of 2m
end
twomu=twomu+2*sum(sum(omega));
B = B+omega;
%% Run modularity
[S,Q] = genlouvain(B,10000,0,1,1);
Q_runs = [Q_runs Q/twomu];
S_runs = [S_runs S];
end
%% Write results
dlmwrite([outputfolder,'/Q_null3.csv'],full(Q_runs)',',');
dlmwrite([outputfolder,'/S_null3.csv'],S_runs,',');
end
|
github | shainova/EMLN-master | genlouvain.m | .m | EMLN-master/NEE2017/Modularity/genlouvain.m | 11,697 | utf_8 | 92c2a8f309fb987f9c38da6c4be282ac | function [S,Q] = genlouvain(B,limit,verbose,randord,randmove)
%GENLOUVAIN Louvain-like community detection, specified quality function.
% Version 2.0 (July 2014)
%
% [S,Q] = GENLOUVAIN(B) with matrix B implements a Louvain-like greedy
% community detection method using the modularity/quality matrix B that
% encodes the quality function Q, defined by summing over all elements
% B(i,j) such that nodes i and j are placed in the same community.
% Following Blondel et al. 2008, the algorithm proceeds in two phases
% repeated iteratively: quality is optimized by moving one node at a time
% until no such moves improve quality; the communities found to that
% point are then aggregated to build a new network where each node
% represents a community. The output vector S encodes the obtained
% community assignments, with S(i) identifying the community to which
% node i has been assigned. The output Q gives the quality of the
% resulting partition of the network.
%
% [S,Q] = GENLOUVAIN(B) with function handle B such that B(i) returns
% the ith column of the modularity/quality matrix uses this function
% handle (to reduce the memory footprint for large networks) until the
% number of groups is less than 10000 and then builds the B matrix
% corresponding to the new aggregated network in subsequent passes. Use
% [S,Q] = GENLOUVAIN(B,limit) to change this default=10000 limit.
%
% [S,Q] = GENLOUVAIN(B,limit,0) suppresses displayed text output.
%
% [S,Q] = GENLOUVAIN(B,limit,verbose,0) forces index-ordered (cf.
% randperm-ordered) consideration of nodes, for deterministic results.
%
% [S,Q]=GENLOUVAIN(B,limit,verbose,randord,1) enables additional
% randomization to obtain a broader sample of the quality function landscape
% and mitigates some undesirable behavior for "multislice" modularity with
% ordinal coupling. Without 'randmove' enabled, the algorithm exhibits an
% abrupt change in behavior when the strength of the interslice coupling
% approaches the maximum value of the intraslice modularity matrices. With
% 'randmove' enabled, the algorithm moves the node under consideration to a
% community chosen uniformly at random from all moves that increase the
% quality function, instead of choosing the move that maximally increases the
% quality function.
%
% Example (using adjacency matrix A)
% k = full(sum(A));
% twom = sum(k);
% B = @(v) A(:,v) - k'*k(v)/twom;
% [S,Q] = genlouvain(B);
% Q = Q/twom;
% finds community assignments for the undirected network encoded by the
% symmetric adjacency matrix A. For small networks, one may obtain
% reasonably efficient results even more simply by handling the full
% modularity/quality matrix
% B = A - k'*k/twom;
% instead of the function handle. Intended use also includes the
% "multislice" network quality function of Mucha et al. 2010, where B
% encodes the interactions as an equivalent matrix (see examples posted
% online at http://netwiki.amath.unc.edu/GenLouvain).
%
% Notes:
% The matrix represented by B must be both symmetric and square. This
% condition is not checked thoroughly if B is a function handle, but is
% essential to the proper use of this routine.
%
% Under default options, this routine can return different results from
% run to run because it considers nodes in pseudorandom (randperm)
% order. Because of the potentially large number of nearly-optimal
% partitions (Good et al. 2010), one is encouraged to investigate
% results of repeated applications of this code (and, if possible, of
% other computational heuristics). To force deterministic behavior,
% ordering nodes by their index, pass zero as the fourth input:
% GENLOUVAIN(B,limit,verbose,0).
%
% This algorithm is only "Louvain-like" in the sense that the two
% phases are used iteratively in the same manner as in the Louvain
% algorithm (Blondel et al. 2008). Because it operates on a general
% quality/modularity matrix B, it does not include any analytical
% formulas for quickly identifying the change in modularity from a
% proposed move nor any improved efficiency obtained by their use. If
% your problem uses one of the well-used null models included in other
% codes, those codes should be much faster for your task.
%
% Past versions had a problem where accumulated subtraction error might
% lead to an infinite loop with each pass oscillating between two or
% more partitions yet incorrectly identifying increases in quality. We
% believe this problem has been corrected by the relative change checks
% in lines 178 and 269. If you encounter a similar problem, notify
% Peter Mucha (<a href="mailto:[email protected]">[email protected]</a>).
%
% The output Q provides the sum over the appropriate elements of B
% without any rescaling. As such, we have rescaled Q in the example
% above by 2m = sum(k) so that Q <= 1.
%
% The '~' for ignoring function returns (used for "max" below) are not
% supported prior to R2009b. Replace (e.g. 'dummy') for pre-2009b.
%
% By using this code, the user implicitly acknowledges that the authors
% accept no liability associated with that use. (What are you doing
% with it anyway that might cause there to be a potential liability?!?)
%
% References:
% Blondel, Vincent D., Jean-Loup Guillaume, Renaud Lambiotte, and
% Etienne Lefebvre, "Fast unfolding of communities in large networks,"
% Journal of Statistical Mechanics: Theory and Experiment, P10008
% (2008).
%
% Fortunato, Santo, "Community detection in graphs," Physics Reports
% 486, 75-174 (2010).
%
% Mucha, Peter J., Thomas Richardson, Kevin Macon, Mason A. Porter, and
% Jukka-Pekka Onnela. "Community Structure in Time-Dependent,
% Multiscale, and Multiplex Networks," Science 328, 876-878 (2010).
%
% Porter, M. A., J. P. Onnela, and P. J. Mucha, "Communities in
% networks," Notices of the American Mathematical Society 56, 1082-1097
% & 1164-1166 (2009).
%
% Acknowledgments:
% A special thank you to Stephen Reid, whose greedy.m code was the
% original version that has over time developed into the present code,
% and Marya Bazzi for noticing the problematic behavior of genlouvain for
% ordinal interslice coupling and contributing code that developed into the
% 'randmove' option.
% Thank you also to Dani Bassett, Jesse Blocher, Mason Porter and Simi
% Wang for inspiring improvements to the code.
%
% Citation: If you use this code, please cite as
% Inderjit S. Jutla, Lucas G. S. Jeub, and Peter J. Mucha,
% "A generalized Louvain method for community detection implemented
% in MATLAB," http://netwiki.amath.unc.edu/GenLouvain (2011-2014).
%set default for maximum size of modularity matrix
if nargin<2||isempty(limit)
limit = 10000;
end
%set level of reported/displayed text output
if nargin<3||isempty(verbose)
verbose = 1;
end
if verbose
mydisp = @(s) disp(s);
else
mydisp = @(s) disp('');
end
%set randperm- v. index-ordered
if nargin<4||isempty(randord)
randord = 1;
end
if randord
myord = @(n) randperm(n);
else
myord = @(n) 1:n;
end
%set move function (maximal (original Louvain) or random improvement)
if nargin<5||isempty(randmove)
randmove=false;
end
if randmove
movefunction='moverand';
else
movefunction='move';
end
%initialise variables and do symmetry check
if isa(B,'function_handle')
n=length(B(1));
S=(1:n)';
M=B;
it(:,1)=M(1);
ii=find(it(2:end)>0,3)+1;
ii=[1,ii'];
for i=2:length(ii),
it(:,i)=M(ii(i));
end
it=it(ii,:);
if norm(it-it')>2*eps
error('Function handle does not correspond to a symmetric matrix')
end
else
n = length(B);
S = (1:n)';
if nnz(B-B'),
B=(B+B')/2;
disp('WARNING: Forced symmetric B matrix')
end
M=B;
end
dtot=0; %keeps track of total change in modularity
%Run using function handle, if provided
while (isa(M,'function_handle')) %loop around each "pass" (in language of Blondel et al) with B function handle
y = unique(S); %unique also puts elements in ascending order
Sb=S;
clocktime=clock;
mydisp(['Merging ',num2str(length(y)),' communities ',num2str(clocktime(4:6))]);
dstep=1; %keeps track of change in modularity in pass
yb=[];
while (~isequal(yb,y))&&(dstep/dtot>2*eps) %This is the loop around Blondel et al's "first phase"
yb = y;
dstep=0;
group_handler('assign',y);
for i=myord(length(M(1)))
di=group_handler(movefunction,i,M(i));
dstep=dstep+di;
end
dtot=dtot+dstep;
y=group_handler('return');
mydisp([num2str(length(unique(y))),' change: ',num2str(dstep),...
' total: ',num2str(dtot),' relative: ',num2str(dstep/dtot)]);
end
%group_handler implements tidyconfig
for i=1:length(y)
S(S==i)=y(i);
end
%calculate modularity and return if converged
if isequal(Sb,S)
Q=0;
P=sparse(y,1:length(y),1);
for i=1:length(M(1))
Q=Q+(P*M(i))'*P(:,i);
end
return
end
%check wether #groups < limit
t = length(unique(S));
if (t>limit)
metanetwork_reduce('assign',S); %inputs group information to metanetwork_reduce
M=@(i) metanetwork_i(B,t,i); %use function handle if #groups>limit
else
metanetwork_reduce('assign',S);
J = zeros(t); %convert to matrix if #groups small enough
for c=1:t
J(:,c)=metanetwork_i(B,t,c);
end
B = J;
M=B;
end
end
S2 = (1:length(B))';
Sb = [];
while ~isequal(Sb,S2) %loop around each "pass" (in language of Blondel et al) with B matrix
y = unique(S2); %unique also puts elements in ascending order
Sb = S2;
clocktime=clock;
mydisp(['Merging ',num2str(length(y)),' communities ',num2str(clocktime(4:6))]);
yb = [];
dstep=1;
while (~isequal(yb,y)) && (dstep/dtot>2*eps) %This is the loop around Blondel et al's "first phase"
% mydisp([num2str(length(unique(y))),' ',num2str(Q)])
yb = y;
dstep=0;
group_handler('assign',y);
for i = myord(length(M))
di=group_handler(movefunction,i,M(:,i));
dstep=dstep+di;
end
dtot=dtot+dstep;
y=group_handler('return');
end
for i = 1:length(y)
S(S==i) = y(i);
S2(S2==i) = y(i);
end
if isequal(Sb,S2)
P=sparse(y,1:length(y),1);
Q=sum(sum((P*M).*P));
return
end
M = metanetwork(B,S2);
end
%-----%
function M = metanetwork(J,S)
%Computes new aggregated network (communities --> nodes)
PP = sparse(1:length(S),S,1);
M = PP'*J*PP;
M=full(M);
%-----%
function Mi = metanetwork_i(J,t,i)
%ith column of metanetwork (used to create function handle)
%J is a function handle
Mi=zeros(t,1);
ind=metanetwork_reduce('nodes',i);
for j=ind
Jj=J(j);
P=metanetwork_reduce('reduce',Jj);
Mi=Mi+P;
end
|
github | shainova/EMLN-master | single_layer_bipartite_B_matrix.m | .m | EMLN-master/NEE2017/Modularity/single_layer_bipartite_B_matrix.m | 554 | utf_8 | ce18365cfc84fce465315d920e40b606 | % NOTE!!! This file accompanies the following publication and can
% only be understood by reading the details in the manuscript and its
% SI. Please cite the original publication if using this code.
%
% Pilosof S, Porter MA, Pascual M, Kefi S.
% The multilayer nature of ecological networks.
% Nature Ecology & Evolution (2017).
function [B,mm]=single_layer_bipartite_B_matrix(A,gamma)
[m,n]=size(A);
N=m+n;
k=sum(A,2);
d=sum(A,1);
mm=sum(k);
B1=A-gamma*k*d/mm;
B=zeros(N,N);
B(1:m,m+1:N)=B1;
B(m+1:N,1:m)=B1';
end
|
github | shainova/EMLN-master | muxOctaveLib.m | .m | EMLN-master/NEE2017/Reducibility/muxOctaveLib.m | 58,399 | utf_8 | 410cc4713aa4cfb0d67441e66f48983c | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% MuxNetLib: Octave library for Multiplex Network Analysis in muxViz
%
% Version: 0.1
% Last update: Nov 2015
% Authors: Manlio De Domenico
%
% History:
%
% May 2014: First release, including part of muxNet
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [A,N] = loadNetworkFromFile(fileName,Flags,Nodes=0,FirstNode=0)
A = load(fileName);
%if the first node is numbered by zero shift of 1 unit to relabel
if FirstNode==0
A(:,1) = A(:,1) + 1;
A(:,2) = A(:,2) + 1;
endif
if Nodes==0
N = max(max(A(:,1)),max(A(:,2)));
else
N = Nodes;
endif
if max(ismember(Flags, 'W'))==0
%input is assumed to be an unweighted edge list
%add a column of ones as weight for connected nodes
%if there are more columns, we have to remove them
if columns(A)>2
A = A(:,1:2);
endif
A = [A 1.0*ones(size(A,1),1)];
else
if columns(A)>3
A = A(:,1:3);
endif
endif
A = spconvert(A);
A(size(A,1)+1:N,size(A,2)+1:N) = 0;
if ismember("D",Flags) && ismember("U",Flags)
%input is undirected but provided in directed shape, we need to sum the transpose
fprintf(2,"#Input is undirected but in directed shape\n");
A = A + A' - diag(diag(A));
#the -diag() is to avoid counting twice the self-loops
endif
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [NodesTensor,Layers,Nodes] = BuildMultiplexFromFileList(LayersList,Flags,Nodes=0,FirstNode=0)
% for input from different folders and put the full path in the LayerList
% Flags must be a cell array defining the network type: D(irected), W(eighted), U(ndirected with)D(irected input)
NodesTensor = {};
Ni = {};
Layers = length(LayersList);
for i = 1:Layers
if strcmp(LayersList{i},"NULL")
if Nodes == 0
fprintf(2,"\tBuildMultiplexFromFileList: ERROR! You requested a null layer, without specifying the number of nodes. Aborting process.\n");
exit
end
Ni{i} = Nodes;
NodesTensor{i} = sparse(Nodes,Nodes);
Ei = 0;
file = "Null layer";
printf("#Layer %d: %d Nodes %d Edges (file: %s)\n",i,Ni{i},Ei,file);
else
[NodesTensor{i},Ni{i}] = loadNetworkFromFile(LayersList{i},Flags,Nodes,FirstNode);
path = cellstr(strsplit (LayersList{i}, "/"));
file = path{length(path)};
Ei = sum(sum(NodesTensor{i}>0));
printf("#Layer %d: %d Nodes %d Edges (file: %s)\n",i,Ni{i},Ei,file);
end
%check that the number of nodes in each layer is the same
if i>1
if Ni{i} != Ni{i-1}
error(" BuildMultiplexFromFileList: ERROR! The number of nodes mismatches: %d (layer %d) vs %d (layer %d)\n",Ni{i},i,Ni{i-1},i-1);
%pause;
end
end
end
printf("#Flags: %s\n",Flags);
% if everything is fine, we assign the number of nodes
Nodes = Ni{1};
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [M,L,N] = BuildSupraAdjacencyMatrixFromFile(fileName,Flags,Nodes=0,FirstNode=0)
%auto-detection of number of layers and nodes (if not forced with Nodes parameter)
%input is expected to be a weighted edge list with 5 columns:
%node layer node layer [weight]
%if flag W is not specified, weight = 1 is assumed
A = load(fileName);
%if the first node is numbered by zero shift of 1 unit to relabel
if FirstNode==0
A(:,1) = A(:,1) + 1;
A(:,3) = A(:,3) + 1;
endif
%number of layers, assuming they are numbered starting from 1
L = max(max(A(:,2)),max(A(:,4)));
if Nodes==0
N = max(max(A(:,1)),max(A(:,3)));
else
N = Nodes;
endif
if max(ismember(Flags, 'W'))==0
if size(A)(2) == 5
%input is weighted, but the W flag is missing: reset weights to 1
A(:,5) = 1;
else
%input is assumed to be an unweighted edge list
%add a column of ones as weight for connected nodes
A = [A 1.0*ones(size(A,1),1)];
endif
endif
M = [A(:,1) + (A(:,2)-1)*N A(:,3) + (A(:,4)-1)*N A(:,5)];
M = spconvert(M);
%M = full(M)
%we work with sparse matrices
M(size(M,1)+1:N*L,size(M,2)+1:N*L) = 0;
if ismember("D",Flags) && ismember("U",Flags)
%input is undirected but provided in directed shape, we need to sum the transpose
fprintf(2,"#Input is undirected but in directed shape\n");
M = M + M' - diag(diag(M));
#the -diag() is to avoid counting twice the self-loops
endif
printf("#%d Layers %d Nodes %d Edges (file: %s)\n",L,N,sum(sum(M>0)),fileName);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function LayersTensor = BuildLayersTensor(Layers,Nodes,OmegaParameter,MultisliceType)
%Build the network of layers used to build the multiplex
if Layers>1
if strcmp(MultisliceType,"ordered")
LayersTensor = (diag(ones(1,Layers-1),1) + diag(ones(1,Layers-1),-1))*OmegaParameter;
end
if strcmp(MultisliceType, "categorical")
LayersTensor = ones(Layers,Layers)*OmegaParameter;
LayersTensor = LayersTensor - diag(diag(LayersTensor));
end
else
LayersTensor = 0;
fprintf(2,"--> I will proceed with algorithm for one layer\n");
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function SupraAdjacencyMatrix = BuildSupraAdjacencyMatrix(NodesTensor,LayersTensor,Layers,Nodes)
Identity = speye(Nodes);
%simple and easy way, probably the correct one
SupraAdjacencyMatrix = sparse(blkdiag(NodesTensor{}) + kron(LayersTensor,Identity));
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [QMatrix,LMatrix,Eigenvalues] = SolveEigenvalueProblem(Matrix)
[QMatrix,LMatrix] = eig(Matrix);
Eigenvalues=sort(diag(LMatrix));
endfunction
function [QMatrix,LMatrix] = GetLargestEigenv(Matrix)
%This flag force the library to use methods to find approximated leading eigenvalue/vector
%However, empirical evidence shows that such methods (coming with octave) are not so
%stable, therefore if the final output looks "weird", a full exact method for the calculation
%should be used. Unfortunately, the exact method will heavily slow down the computation
%Use with care at your own risk
UseFastMethodLargestEigenvalue = 0;
%we must distinguish between symmetric and nonsymmetric matrices to have correct results
if !UseFastMethodLargestEigenvalue
[QMatrix,LMatrix] = eig(Matrix);
[LambdaVector,IdxVector]=sort(diag(LMatrix));
Idx = length(LambdaVector);
LeadingEigenvalue = LambdaVector(Idx);
LeadingEigenvector = QMatrix(:,IdxVector(Idx));
QMatrix = LeadingEigenvector;
LMatrix = LeadingEigenvalue;
else
if all(all(Matrix == Matrix'))
%symmetric
[QMatrix,LMatrix] = eigs(Matrix,1,'la');
else
%asymmetric
[QMatrix,LMatrix] = eigs(Matrix,1,'lr');
endif
%check if the eigenvector has all negative components.. in that case we change the sign
%first, set to zero everything that is so small that can create problems even if it compatible with zero
QMatrix(find(QMatrix>-1e-12 & QMatrix<1e-12)) = 0;
%now verify that all components are negative and change sign
if all(floor(QMatrix<0) + floor(QMatrix==0))
QMatrix = -QMatrix;
endif
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [NodesTensor] = SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes)
% create the nodes tensor from a supradajcency matrix, ie, extracts diagonal blocks
NodesTensor = {};
for i = 1:Layers
NodesTensor{i} = sparse(SupraAdjacencyMatrix(1+ (i-1)*Nodes:i*Nodes,1+ (i-1)*Nodes:i*Nodes));
end
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [BlockTensor] = SupraAdjacencyToBlockTensor(SupraAdjacencyMatrix,Layers,Nodes)
% create the nodes tensor from a supradajcency matrix, ie, extracts all blocks
BlockTensor = {};
for i = 1:Layers
for j = 1:Layers
%BlockTensor{(i-1)*Layers + j} = SupraAdjacencyMatrix(1+ (i-1)*Nodes:i*Nodes,1+ (j-1)*Nodes:j*Nodes);
BlockTensor{i,j} = sparse(SupraAdjacencyMatrix(1+ (i-1)*Nodes:i*Nodes,1+ (j-1)*Nodes:j*Nodes));
endfor
endfor
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Aggregate = GetAggregateMatrix(NodesTensor,Layers,Nodes)
Aggregate = NodesTensor{1};
for alpha = 2:Layers
Aggregate += NodesTensor{alpha};
endfor
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Reducibility of Multilayer Networks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function LaplacianMatrix = GetLaplacianMatrix(AdjacencyMatrix)
%Calculate the laplacian matrix from an adjacency matrix
N = length(AdjacencyMatrix);
u = ones(N,1);
%laplacian
LaplacianMatrix = diag(AdjacencyMatrix*u) - AdjacencyMatrix;
%check
if sum(LaplacianMatrix*u) > 1.e-8
error("ERROR! The Laplacian matrix has rows that don't sum to 0. Aborting process.\n");
sum(LaplacianMatrix*u)
%pause;
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function DensityMatrix = BuildDensityMatrix(AdjacencyMatrix)
%Calculate the density matrix from an adjacency matrix
% References:
% S. L. Braunstein, S. Ghosh, S. Severini, Annals of Combinatorics 10, No 3, (2006)
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
DensityMatrix = GetLaplacianMatrix(AdjacencyMatrix);
%normalize to degree sum
DensityMatrix = DensityMatrix/(trace(DensityMatrix));
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Eigenvalues = GetEigenvaluesOfDensityMatrix(DensityMatrix)
%Calculate the eigenvalues of a density matrix
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
Eigenvalues = eig(DensityMatrix);
%check that eigenvalues sum to 1
if abs(sum(Eigenvalues)-1)>1e-8
error("ERROR! Eigenvalues dont sum to 1! Aborting process.");
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Eigenvalues = GetEigenvaluesOfDensityMatrixFromAdjacencyMatrix(AdjacencyMatrix)
DensityMatrix = BuildDensityMatrix(AdjacencyMatrix);
Eigenvalues = GetEigenvaluesOfDensityMatrix(DensityMatrix);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [RenyiEntropy] = GetRenyiEntropyFromAdjacencyMatrix(AdjacencyMatrix, q)
%Calculate the quantum Renyi entropy of a network
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
% M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
Eigenvalues = GetEigenvaluesOfDensityMatrixFromAdjacencyMatrix(AdjacencyMatrix);
if q==1.
%Von Neuman quantum entropy
RenyiEntropy = -sum(Eigenvalues(Eigenvalues>0).*log(Eigenvalues(Eigenvalues>0)));
else
%Renyi quantum entropy
RenyiEntropy = (1 - sum(Eigenvalues(Eigenvalues>0).^q))/(q-1);
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [JSD] = GetJensenShannonDivergence(AdjacencyMatrix1,AdjacencyMatrix2,VNEntropy1,VNEntropy2)
%Calculate the Jensen-Shannon Divergence of two networks
% References:
% M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
%M = 0.5 * (RHO + SIGMA)
%JSD: 0.5 * DKL( RHO || M ) + 0.5 * DKL( SIGMA || M )
%DKL( A || B ) = tr[ A log A - A log B ] = -entropy(A) - tr[ A log B ]
%
%JSD: 0.5 * ( -entropy(RHO) - entropy(SIGMA) - tr[ RHO log M ] - tr[ SIGMA log M ] )
% -0.5 * [ entropy(RHO) + entropy(SIGMA) ] - tr[ M log M ] )
% -0.5 * [ entropy(RHO) + entropy(SIGMA) ] + entropy(M)
DensityMatrix1 = BuildDensityMatrix(AdjacencyMatrix1);
DensityMatrix2 = BuildDensityMatrix(AdjacencyMatrix2);
DensityMatrixM = (DensityMatrix1 +DensityMatrix2)/2.;
EigenvaluesM = eig(DensityMatrixM);
CrossEntropyM = -sum(EigenvaluesM(EigenvaluesM>0).*log(EigenvaluesM(EigenvaluesM>0)));
JSD = CrossEntropyM - 0.5*(VNEntropy1 + VNEntropy2);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Topological Descriptors of Multilayer Networks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [AvGlobOverl] = GetAverageGlobalOverlapping(SupraAdjacencyMatrix,Layers,Nodes)
% References:
% M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
if Layers==1
fprintf(2,"GetAverageGlobalOverlapping:ERROR! At least two layers required. Aborting process.\n");
exit;
endif
NodesTensor = SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes);
O = min(NodesTensor{1},NodesTensor{2});
NormTotal = sum(sum(NodesTensor{1}));
%assuming that LayerTensor is an undirected clique
for l = 2:Layers
O = min(O,NodesTensor{l});
NormTotal = NormTotal + sum(sum(NodesTensor{l}));
end
AvGlobOverl = Layers*sum(sum(O))/NormTotal;
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [AvGlobOverlMatrix] = GetAverageGlobalNodeOverlappingMatrix(SupraAdjacencyMatrix,Layers,Nodes)
% References:
% M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
if Layers==1
fprintf(2,"GetAverageGlobalNodeOverlappingMatrix:ERROR! At least two layers required. Aborting process.\n");
exit;
endif
NodesTensor = SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes);
existingNodes = {};
for l = 1:Layers
#find rows where sum by column is > zero to identify existing nodes. Apply modulus Nodes
col = mod(find(sum(NodesTensor{l},2)!=0 ),Nodes);
#Impose that where modulus give 0, there should be the largest ID (= Nodes)
col(col==0) = Nodes;
#same with cols
row = mod(find(sum(NodesTensor{l},1)!=0 ),Nodes)';
row(row==0) = Nodes;
#merge the two (this approach is necessary to deal also with directed networks)
existingNodes{l} = union(col, row);
end
for l1 = 1:Layers
AvGlobOverlMatrix(l1,l1) = 1;
for l2 = (l1+1):Layers
AvGlobOverlMatrix(l1,l2) = length(intersect( existingNodes{l1}, existingNodes{l2} ))/Nodes;
AvGlobOverlMatrix(l2,l1) = AvGlobOverlMatrix(l1,l2);
end
end
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [AvGlobOverlMatrix] = GetAverageGlobalOverlappingMatrix(SupraAdjacencyMatrix,Layers,Nodes)
% References:
% M. De Domenico, V. Nicosia, A. Arenas, V. Latora, Nature Communications 6, 6864 (2015)
if Layers==1
fprintf(2,"GetAverageGlobalOverlappingMatrix:ERROR! At least two layers required. Aborting process.\n");
exit;
endif
NodesTensor = SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes);
for l1 = 1:Layers
AvGlobOverlMatrix(l1,l1) = 1;
Norm1 = sum(sum(NodesTensor{l1}));
for l2 = (l1+1):Layers
O = min(NodesTensor{l1},NodesTensor{l2});
AvGlobOverlMatrix(l1,l2) = 2*sum(sum(O))/(Norm1 + sum(sum(NodesTensor{l2})));
AvGlobOverlMatrix(l2,l1) = AvGlobOverlMatrix(l1,l2);
end
end
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [InterPearson,InterSpearman] = GetInterAssortativityTensor(SupraAdjacencyMatrix,Layers,Nodes,Flags,Type)
if Layers==1
fprintf(2,"GetInterAssortativityTensor: ERROR! At least two layers required. Aborting process.\n");
exit;
endif
NodesTensor = SupraAdjacencyToNodesTensor(SupraAdjacencyMatrix,Layers,Nodes);
InterPearson = sparse(Layers,Layers);
InterSpearman = sparse(Layers,Layers);
if strcmp(Type,"IO") || strcmp(Type,"OI")
InDegree = {};
OutDegree = {};
for l = 1:Layers
InDegree{l} = GetMultiInDegree(NodesTensor{l},1,Nodes,Flags);
OutDegree{l} = GetMultiOutDegree(NodesTensor{l},1,Nodes,Flags);
end
for l1 = 1:Layers
for l2 = 1:Layers
InterPearson(l1,l2) = corr(InDegree{l1},OutDegree{l2});
InterSpearman(l1,l2) = spearman(InDegree{l1},OutDegree{l2});
end
end
if strcmp(Type,"OI")
InterPearson = InterPearson';
InterSpearman = InterSpearman';
endif
else
Degree = {};
if strcmp(Type,"OO")
for l = 1:Layers
Degree{l} = GetMultiOutDegree(NodesTensor{l},1,Nodes,Flags);
end
endif
if strcmp(Type,"II")
for l = 1:Layers
Degree{l} = GetMultiInDegree(NodesTensor{l},1,Nodes,Flags);
end
endif
if strcmp(Type,"TT")
for l = 1:Layers
Degree{l} = GetMultiDegree(NodesTensor{l},1,Nodes,Flags);
end
endif
for l1 = 1:Layers
InterPearson(l1,l1) = 1;
InterSpearman(l1,l1) = 1;
for l2 = (l1+1):Layers
InterPearson(l1,l2) = corr(Degree{l1},Degree{l2});
InterSpearman(l1,l2) = spearman(Degree{l1},Degree{l2});
InterPearson(l2,l1) = InterPearson(l1,l2);
InterSpearman(l2,l1) = InterSpearman(l1,l2);
end
end
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function BinaryMatrix = binarizeMatrix(Matrix)
BinaryMatrix = double(Matrix|Matrix);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiDegreeVector = GetMultiDegree(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInDegreeVector = GetMultiInDegree(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes,Flags);
MultiOutDegreeVector = GetMultiOutDegree(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes,Flags);
if ismember("U",Flags)
MultiDegreeVector = (MultiInDegreeVector + MultiOutDegreeVector)/2;
else
MultiDegreeVector = MultiInDegreeVector + MultiOutDegreeVector;
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiOutDegreeVector = GetMultiOutDegree(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
if ismember("U",Flags)
%we proceed by considering the interlayers separately
BlockTensor = SupraAdjacencyToBlockTensor(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes);
MultiOutDegreeVector = sparse(Nodes,1);
%with the matrix U we reweight interlinks corresponding to same replicas
U = ones(Nodes,Nodes);
U(logical(speye(size(U)))) = 1/2;
for i = 1:Layers
for j = 1:Layers
if i==j
MultiOutDegreeVector += (BlockTensor{i,j}-diag(diag(BlockTensor{i,j})))*ones(Nodes,1) + diag(BlockTensor{i,j})*0.5;
else
MultiOutDegreeVector += (BlockTensor{i,j} .* U)*ones(Nodes,1);
endif
endfor
endfor
else
SupraDegree = binarizeMatrix(SupraAdjacencyMatrix)*ones(Nodes*Layers,1);
MultiOutDegreeVector = sum(reshape(SupraDegree,Nodes,Layers),2);
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiInDegreeVector = GetMultiInDegree(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
if ismember("U",Flags)
%using the following would consider multiple times the interlinks
%SupraDegree = (binarizeMatrix(SupraAdjacencyMatrix)*ones(Nodes*Layers,1) + (ones(1,Nodes*Layers)*binarizeMatrix(SupraAdjacencyMatrix))')/2;
%we proceed by considering the interlayers separately
BlockTensor = SupraAdjacencyToBlockTensor(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes);
MultiInDegreeVector = sparse(Nodes,1);
%with the matrix U we reweight interlinks corresponding to same replicas
U = ones(Nodes,Nodes);
U(logical(speye(size(U)))) = 1/2;
for i = 1:Layers
for j = 1:Layers
if i==j
MultiInDegreeVector += (ones(1,Nodes)*(BlockTensor{i,j}-diag(diag(BlockTensor{i,j}))))' + diag(BlockTensor{i,j})*0.5;
else
MultiInDegreeVector += (ones(1,Nodes)*(BlockTensor{i,j} .* U))';
endif
endfor
endfor
else
SupraDegree = (ones(1,Nodes*Layers)*binarizeMatrix(SupraAdjacencyMatrix))';
MultiInDegreeVector = sum(reshape(SupraDegree,Nodes,Layers),2);
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiDegreeVector = GetMultiDegreeSum(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInDegreeVector = GetMultiInDegreeSum(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes,Flags);
MultiOutDegreeVector = GetMultiOutDegreeSum(binarizeMatrix(SupraAdjacencyMatrix),Layers,Nodes,Flags);
if ismember("U",Flags)
MultiDegreeVector = (MultiInDegreeVector + MultiOutDegreeVector)/2;
else
MultiDegreeVector = MultiInDegreeVector + MultiOutDegreeVector;
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiOutDegreeVector = GetMultiOutDegreeSum(SupraAdjacencyMatrix,Layers,Nodes,Flags)
%this degree include multiple times the interlinks
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraDegree = binarizeMatrix(SupraAdjacencyMatrix)*ones(Nodes*Layers,1);
MultiOutDegreeVector = sum(reshape(SupraDegree,Nodes,Layers),2);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiInDegreeVector = GetMultiInDegreeSum(SupraAdjacencyMatrix,Layers,Nodes,Flags)
%this degree include multiple times the interlinks
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraDegree = (ones(1,Nodes*Layers)*binarizeMatrix(SupraAdjacencyMatrix))';
MultiInDegreeVector = sum(reshape(SupraDegree,Nodes,Layers),2);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiStrengthVector = GetMultiStrength(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInStrengthVector = GetMultiInStrength(SupraAdjacencyMatrix,Layers,Nodes,Flags);
MultiOutStrengthVector = GetMultiOutStrength(SupraAdjacencyMatrix,Layers,Nodes,Flags);
if ismember("U",Flags)
MultiStrengthVector = (MultiInStrengthVector + MultiOutStrengthVector)/2;
else
MultiStrengthVector = MultiInStrengthVector + MultiOutStrengthVector;
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiOutStrengthVector = GetMultiOutStrength(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
if ismember("U",Flags)
%we proceed by considering the interlayers separately
BlockTensor = SupraAdjacencyToBlockTensor(SupraAdjacencyMatrix,Layers,Nodes);
MultiOutStrengthVector = sparse(Nodes,1);
%with the matrix U we reweight interlinks corresponding to same replicas
U = ones(Nodes,Nodes);
U(logical(speye(size(U)))) = 1/2;
for i = 1:Layers
for j = 1:Layers
if i==j
MultiOutStrengthVector += (BlockTensor{i,j}-diag(diag(BlockTensor{i,j})))*ones(Nodes,1) + diag(BlockTensor{i,j})*0.5;
else
MultiOutStrengthVector += (BlockTensor{i,j} .* U)*ones(Nodes,1);
endif
endfor
endfor
else
SupraStrength = SupraAdjacencyMatrix*ones(Nodes*Layers,1);
MultiOutStrengthVector = sum(reshape(SupraStrength,Nodes,Layers),2);
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiInStrengthVector = GetMultiInStrength(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
if ismember("U",Flags)
%using the following would consider multiple times the interlinks
%SupraStrength = (SupraAdjacencyMatrix*ones(Nodes*Layers,1) + (ones(1,Nodes*Layers)*SupraAdjacencyMatrix)')/2;
%we proceed by considering the interlayers separately
BlockTensor = SupraAdjacencyToBlockTensor(SupraAdjacencyMatrix,Layers,Nodes);
MultiInStrengthVector = sparse(Nodes,1);
%with the matrix U we reweight interlinks corresponding to same replicas
U = ones(Nodes,Nodes);
U(logical(speye(size(U)))) = 1/2;
for i = 1:Layers
for j = 1:Layers
if i==j
MultiInStrengthVector += (ones(1,Nodes)*(BlockTensor{i,j}-diag(diag(BlockTensor{i,j}))))' + diag(BlockTensor{i,j})*0.5;
else
MultiInStrengthVector += (ones(1,Nodes)*(BlockTensor{i,j} .* U))';
endif
endfor
endfor
else
SupraStrength = (ones(1,Nodes*Layers)*SupraAdjacencyMatrix)';
MultiInStrengthVector = sum(reshape(SupraStrength,Nodes,Layers),2);
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiStrengthVector = GetMultiStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,Flags)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
MultiInStrengthVector = GetMultiInStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,Flags);
MultiOutStrengthVector = GetMultiOutStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,Flags);
if ismember("U",Flags)
MultiStrengthVector = (MultiInStrengthVector + MultiOutStrengthVector)/2;
else
MultiStrengthVector = MultiInStrengthVector + MultiOutStrengthVector;
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiOutStrengthVector = GetMultiOutStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,Flags)
%this Strength include multiple times the interlinks
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraStrength = SupraAdjacencyMatrix*ones(Nodes*Layers,1);
MultiOutStrengthVector = sum(reshape(SupraStrength,Nodes,Layers),2);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function MultiInStrengthVector = GetMultiInStrengthSum(SupraAdjacencyMatrix,Layers,Nodes,Flags)
%this Strength include multiple times the interlinks
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
SupraStrength = (ones(1,Nodes*Layers)*SupraAdjacencyMatrix)';
MultiInStrengthVector = sum(reshape(SupraStrength,Nodes,Layers),2);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CentralityVector = GetOverallKatzCentrality(SupraAdjacencyMatrix,Layers,Nodes)
%we pass the transpose of the transition matrix to get the left eigenvectors
% References:
% M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
[QMatrix,LMatrix] = GetLargestEigenv(SupraAdjacencyMatrix');
LeadingEigenvalue = LMatrix;
%Katz kernel tensor
deltaTensor = kron(speye(Nodes,Nodes),speye(Layers,Layers));
%this ensures convergence of the Katz kernel tensor
a = 0.99999/abs(LeadingEigenvalue);
KatzKernelTensor = inv(deltaTensor - a*SupraAdjacencyMatrix);
KatzCentralitySupraVector = KatzKernelTensor * ones(Nodes*Layers,1);
CentralityVector = sum(reshape(KatzCentralitySupraVector,Nodes,Layers),2);
CentralityVector = CentralityVector/max(CentralityVector);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CentralityVector = GetOverallEigenvectorCentrality(SupraAdjacencyMatrix,Layers,Nodes)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
% M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
%we pass the transpose of the transition matrix to get the left eigenvectors
[LeadingEigenvector,LeadingEigenvalue] = GetLargestEigenv(SupraAdjacencyMatrix');
%LeadingEigenvector = LeadingEigenvector / sum(LeadingEigenvector);
CentralityVector = sum(reshape(LeadingEigenvector,Nodes,Layers),2);
CentralityVector = CentralityVector/max(CentralityVector);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CentralityVector = GetOverallHubCentrality(SupraAdjacencyMatrix,Layers,Nodes)
%see review http://arxiv.org/pdf/0805.3322v2.pdf
% References:
% M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
%build the A A'
SupraMatrix = SupraAdjacencyMatrix*(SupraAdjacencyMatrix');
%we pass the matrix to get the right eigenvectors
%to deal with the possible degeneracy of the leading eigenvalue, we add an eps to the matrix
%this ensures that we can apply the Perron-Frobenius theorem to say that there is a unique
%leading eigenvector. Here we add eps, a very very small number (<1e-8, generally)
[LeadingEigenvector,LeadingEigenvalue] = GetLargestEigenv(SupraMatrix+eps);
%LeadingEigenvector = LeadingEigenvector / sum(LeadingEigenvector);
CentralityVector = sum(reshape(LeadingEigenvector,Nodes,Layers),2);
CentralityVector = CentralityVector/max(CentralityVector);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CentralityVector = GetOverallAuthCentrality(SupraAdjacencyMatrix,Layers,Nodes)
%see review http://arxiv.org/pdf/0805.3322v2.pdf
% References:
% M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
%build the A' A
SupraMatrix = (SupraAdjacencyMatrix') * SupraAdjacencyMatrix;
%we pass the matrix to get the right eigenvectors
%to deal with the possible degeneracy of the leading eigenvalue, we add an eps to the matrix
%this ensures that we can apply the Perron-Frobenius theorem to say that there is a unique
%leading eigenvector. Here we add eps, a very very small number (<1e-8, generally)
[LeadingEigenvector,LeadingEigenvalue] = GetLargestEigenv(SupraMatrix+eps);
CentralityVector = sum(reshape(LeadingEigenvector,Nodes,Layers),2);
CentralityVector = CentralityVector/max(CentralityVector);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CentralityVector = GetOverallMultiplexityCentrality(SupraAdjacencyMatrix,Layers,Nodes)
#build the block tensor
BlockTensor = SupraAdjacencyToBlockTensor(SupraAdjacencyMatrix,Layers,Nodes);
existingNodes = {};
nodeMultiplexity = zeros(1,Nodes);
for l = 1:Layers
#find rows where sum by column is > zero to identify existing nodes. Apply modulus Nodes
col = mod(find(sum(BlockTensor{l,l},2)!=0 ),Nodes);
#Impose that where modulus give 0, there should be the largest ID (= Nodes)
col(col==0) = Nodes;
#same with cols
row = mod(find(sum(BlockTensor{l,l},1)!=0 ),Nodes)';
row(row==0) = Nodes;
#merge the two (this approach is necessary to deal also with directed networks)
existingNodes{l} = union(col, row);
for n = 1:Nodes
nodeMultiplexity(n) += length(find(existingNodes{l}==n));
end
end
CentralityVector = nodeMultiplexity'/Layers;
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [S,Q] = GetMultisliceCommunityGeneralizedLouvain(NodesTensor, Layers, Nodes, GammaParameter, OmegaParameter, Type)
% This function is an interface between the genlouvain (see the corresponding function
% for reference and license) and muxNet (see the above functions for reference and
% license)
% Type can be: "ordered" or "categorical"
% See http://netwiki.amath.unc.edu/GenLouvain/GenLouvain
% Ordered Multislice Matrix
% Define the cell array A of square symmetric NxN matrices of equal size each representing
% one of the layers ordered, undirected network "slices".
% Categorical Multislice Matrix
% The distinction between ordered slices and categorical slices manifests in the presence
% of all-to-all identity arcs between slices.
if strcmp(Type,"categorical")
B = spalloc(Nodes*Layers,Nodes*Layers,(Nodes+Layers)*Nodes*Layers);
end
if strcmp(Type, "ordered")
B = spalloc(Nodes*Layers,Nodes*Layers,Nodes*Nodes*Layers+2*Nodes*Layers);
end
twomu = 0;
for s = 1:Layers
k = sum(NodesTensor{s});
twom = sum(k);
twomu = twomu + twom;
indx = [1:Nodes] + (s-1)*Nodes;
B(indx,indx) = NodesTensor{s} - GammaParameter* k' * k /twom;
end
if strcmp(Type,"categorical")
twomu = twomu + Layers*OmegaParameter*Nodes*(Layers-1);
all2all = Nodes*[(-Layers+1):-1,1:(Layers-1)];
B = B + OmegaParameter*spdiags(ones(Nodes*Layers,2*Layers-2),all2all,Nodes*Layers,Nodes*Layers);
end
if strcmp(Type, "ordered")
twomu = twomu + 2*OmegaParameter*Nodes*(Layers-1);
B = B + OmegaParameter*spdiags(ones(Nodes*Layers,2),[-Nodes,Nodes],Nodes*Layers,Nodes*Layers);
end
[S,Q] = genlouvain(B);
Q = Q/twomu;
Q = full(Q);
S = reshape(S,Nodes,Layers);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Random Walk in Multilayer Networks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function SupraTransitionMatrix = BuildSupraTransitionMatrixFromSupraAdjacencyMatrix(SupraAdjacencyMatrix,Layers,Nodes)
% References:
% M. De Domenico et al, Phys. Rev. X 3, 041022 (2013)
% M. De Domenico, A. Sole-Ribalta, S. Gomez, A. Arenas, PNAS 11, 8351 (2014)
Order = Layers*Nodes;
#SupraUnitVector = ones(Order,1);
SupraAdjacencyMatrix = sparse(SupraAdjacencyMatrix);
SupraStrengthMatrix = sum(SupraAdjacencyMatrix,2);
DisconnectedNodes = size(SupraStrengthMatrix(SupraStrengthMatrix==0),1);
SupraStrengthMatrix = sparse(diag(SupraStrengthMatrix));
if DisconnectedNodes>0
fprintf(2,"#Trapping nodes (no outgoing-links): %d\n",DisconnectedNodes);
endif
SupraStrengthMatrix(SupraStrengthMatrix(:)~=0) = 1./SupraStrengthMatrix(SupraStrengthMatrix(:)~=0);
SupraTransitionMatrix = SupraStrengthMatrix*SupraAdjacencyMatrix;
alpha = 0.85;
%to normalize correctly in the case of nodes with no outgoing links:
SupraTransitionMatrix(find(sum(SupraTransitionMatrix,2)==0),:) = 1/Order;
SupraTransitionMatrix(find(sum(SupraTransitionMatrix,2)!=0),:) = alpha * SupraTransitionMatrix(find(sum(SupraTransitionMatrix,2)!=0),:) + (1-alpha)/Order;
%no more disconnected nodes
DisconnectedNodes = 0;
%check
if abs(sum(sum(SupraTransitionMatrix,2))-Order+DisconnectedNodes) > 1e-6
error(" BuildSupraTransitionMatrixFromSupraAdjacencyMatrix: ERROR! Problems in building the supra-transition matrix -> %f. Aborting process.",abs(sum(sum(SupraTransitionMatrix,2))-Order+DisconnectedNodes));
%pause;
endif
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CentralityVector = GetOverallPageRankCentrality(SupraTransitionMatrix,Layers,Nodes)
% References:
% M. De Domenico, A. Sole-Ribalta, E. Omodei, S. Gomez, A. Arenas, Nature Communications 6, 6868 (2015)
%we pass the transpose of the transition matrix to get the left eigenvectors
[LeadingEigenvector,LeadingEigenvalue] = GetLargestEigenv(SupraTransitionMatrix');
if abs(LeadingEigenvalue-1)>1e-6
error("\tGetRWOverallOccupationProbability: ERROR! Expected leading eigenvalue equal to 1, obtained %f\n",LeadingEigenvalue);
%exit
endif
LeadingEigenvector = LeadingEigenvector / sum(LeadingEigenvector);
CentralityVector = sum(reshape(LeadingEigenvector,Nodes,Layers),2);
CentralityVector = CentralityVector/max(CentralityVector);
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Community Detection in Multislice Networks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%GENLOUVAIN Louvain-like community detection, specified quality function.
% Version 1.2 (July 2012)
%
% [S,Q] = GENLOUVAIN(B) with matrix B implements a Louvain-like greedy
% community detection method using the modularity/quality matrix B that
% encodes the quality function Q, defined by summing over all elements
% B(i,j) such that nodes i and j are placed in the same community.
% Following Blondel et al. 2008, the algorithm proceeds in two phases
% repeated iteratively: quality is optimized by moving one node at a time
% until no such moves improve quality; the communities found to that
% point are then aggregated to build a new network where each node
% represents a community. The output vector S encodes the obtained
% community assignments, with S(i) identifying the community to which
% node i has been assigned. The output Q gives the quality of the
% resulting partition of the network.
%
% [S,Q] = GENLOUVAIN(B) with function handle B such that B(i) returns
% the ith column of the modularity/quality matrix uses this function
% handle (to reduce the memory footprint for large networks) until the
% number of groups is less than 10000 and then builds the B matrix
% corresponding to the new aggregated network in subsequent passes. Use
% [S,Q] = GENLOUVAIN(B,limit) to change this default=10000 limit.
%
% [S,Q] = GENLOUVAIN(B,limit,0) suppresses displayed text output.
%
% [S,Q] = GENLOUVAIN(B,limit,verbose,0) forces index-ordered (cf.
% randperm-ordered) consideration of nodes, for deterministic results.
%
% Example (using adjacency matrix A)
% k = full(sum(A));
% twom = sum(k);
% B = @(v) A(:,v) - k'*k(v)/twom;
% [S,Q] = genlouvain(B);
% Q = Q/twom;
% finds community assignments for the undirected network encoded by the
% symmetric adjacency matrix A. For small networks, one may obtain
% reasonably efficient results even more simply by handling the full
% modularity/quality matrix
% B = A - k'*k/twom;
% instead of the function handle. Intended use also includes the
% "multislice" network quality function of Mucha et al. 2010, where B
% encodes the interactions as an equivalent matrix (see examples posted
% online at http://netwiki.amath.unc.edu/GenLouvain).
%
% Notes:
% The matrix represented by B must be both symmetric and square. This
% condition is not checked thoroughly if B is a function handle, but is
% essential to the proper use of this routine.
%
% Under default options, this routine can return different results from
% run to run because it considers nodes in pseudorandom (randperm)
% order. Because of the potentially large number of nearly-optimal
% partitions (Good et al. 2010), one is encouraged to investigate
% results of repeated applications of this code (and, if possible, of
% other computational heuristics). To force deterministic behavior,
% ordering nodes by their index, pass zero as the fourth input:
% GENLOUVAIN(B,limit,verbose,0).
%
% This algorithm is only "Louvain-like" in the sense that the two
% phases are used iteratively in the same manner as in the Louvain
% algorithm (Blondel et al. 2008). Because it operates on a general
% quality/modularity matrix B, it does not include any analytical
% formulas for quickly identifying the change in modularity from a
% proposed move nor any improved efficiency obtained by their use. If
% your problem uses one of the well-used null models included in other
% codes, those codes should be much faster for your task.
%
% Past versions had a problem where accumulated subtraction error might
% lead to an infinite loop with each pass oscillating between two or
% more partitions yet incorrectly identifying increases in quality. We
% believe this problem has been corrected by the relative change checks
% in lines 178 and 273. If you encounter a similar problem, notify
% Peter Mucha (<a href="mailto:[email protected]">[email protected]</a>).
%
% The output Q provides the sum over the appropriate elements of B
% without any rescaling. As such, we have rescaled Q in the example
% above by 2m = sum(k) so that Q <= 1.
%
% The '~' for ignoring function returns (used for "max" below) are not
% supported prior to R2009b. Replace (e.g. 'dummy') for pre-2009b.
%
% By using this code, the user implicitly acknowledges that the authors
% accept no liability associated with that use. (What are you doing
% with it anyway that might cause there to be a potential liability?!?)
%
% References:
% Blondel, Vincent D., Jean-Loup Guillaume, Renaud Lambiotte, and
% Etienne Lefebvre, "Fast unfolding of communities in large networks,"
% Journal of Statistical Mechanics: Theory and Experiment, P10008
% (2008).
%
% Fortunato, Santo, "Community detection in graphs," Physics Reports
% 486, 75-174 (2010).
%
% Mucha, Peter J., Thomas Richardson, Kevin Macon, Mason A. Porter, and
% Jukka-Pekka Onnela. "Community Structure in Time-Dependent,
% Multiscale, and Multiplex Networks," Science 328, 876-878 (2010).
%
% Porter, M. A., J. P. Onnela, and P. J. Mucha, "Communities in
% networks," Notices of the American Mathematical Society 56, 1082-1097
% & 1164-1166 (2009).
%
% Acknowledgments:
% A special thank you to Stephen Reid, whose greedy.m code was the
% original version that has over time developed into the present code.
% Thank you also to Dani Bassett, Jesse Blocher, Mason Porter and Simi
% Wang for inspiring improvements to the code.
%
% Citation: If you use this code, please cite as
% Inderjit S. Jutla, Lucas G. S. Jeub, and Peter J. Mucha,
% "A generalized Louvain method for community detection implemented
% in MATLAB," http://netwiki.amath.unc.edu/GenLouvain (2011-2012).
function [S,Q] = genlouvain(B,limit,verbose,randord)
%set default for maximum size of modularity matrix
if nargin<2
limit = 10000;
end
%set level of reported/displayed text output
if nargin<3
verbose = 1;
end
if verbose
mydisp = @(s) disp(s);
else
mydisp = @(s) disp('');
end
%set randperm- v. index-ordered
if nargin<4
randord = 1;
end
if randord
myord = @(n) randperm(n);
else
myord = @(n) 1:n;
end
%initialise variables and do symmetry check
if isa(B,'function_handle')
n=length(B(1));
S=(1:n)';
M=B;
it(:,1)=M(1);
ii=find(it(2:end)>0,3)+1;
ii=[1,ii'];
for i=2:length(ii),
it(:,i)=M(ii(i));
end
it=it(ii,:);
if nnz(it-it'),
disp('WARNING: Function handle does not correspond to a symmetric matrix')
end
else
n = length(B);
S = (1:n)';
M=B;
if nnz(M-M'),
B=(B+B')/2; disp('WARNING: Forced symmetric B matrix')
end
end
dtot=0; %keeps track of total change in modularity
%Run using function handle, if provided
while (isa(M,'function_handle')) %loop around each "pass" (in language of Blondel et al) with B function handle
y = unique(S); %unique also puts elements in ascending order
Sb=S;
yb = [];
clocktime=clock;
mydisp(['Merging ',num2str(length(y)),' communities ',num2str(clocktime(4:6))]);
dstep=1; %keeps track of change in modularity in pass
while (~isequal(yb,y))&&(dstep/dtot>2*eps) %This is the loop around Blondel et al's "first phase"
% Q = 0;
% %improves performance considerably if one doesn't compute modularity
% %for the first pass (for display purposes only)
% P = sparse(y,1:length(y),1); %Modularity Calculation
% for i = 1:length(M(1))
% Q = Q + (P*M(i))'*P(:,i);
% end
% mydisp([num2str(length(unique(y))),' ',num2str(Q)])
yb = y;
G=sparse(1:length(y),y,1); %no-mex version
dstep=0;
for i = myord(length(M(1))) %loop over nodes in pseudorandom order
Mi = M(i);
u = unique([y(i);y(Mi>0)]);
dH=Mi'*G(:,u); %no-mex version
%dH=modchange_y(Mi,y,u);
yi=find(u==y(i));
dH(yi) = dH(yi) - Mi(i);
[~, k] = max(dH);
%only move to different group if it is more optimized than
%staying in same group (up to error with double precision)
if(dH(k)>(dH(yi)))
dtot=dtot+dH(k)-dH(yi);
dstep=dstep+dH(k)-dH(yi);
G(i,y(i))=0; %no-mex version
G(i,u(k))=1; %no-mex version
y(i) = u(k);
end
end
mydisp([num2str(length(unique(y))),' change: ',num2str(dstep),...
' total: ',num2str(dtot),' relative: ',num2str(dstep/dtot)]);
end
%[S,y] = tidyconfig_c(S,y); %note tidyconfig reorders along node numbers
y = tidyconfig(y); %no-mex version
for i = 1:length(y) %no-mex version
S(S==i) = y(i); %no-mex version
end %no-mex version
%calculate modularity and return if converged
if isequal(Sb,S)
Q=0;
P=sparse(y,1:length(y),1);
for i=1:length(M(1))
Q=Q+(P*M(i))'*P(:,i);
end
return
end
%check wether #groups < limit
t = length(unique(S));
if (t>limit)
M=@(i) metanetwork_i(B,S,t,i); %use function handle if #groups>limit
else
J = zeros(t); %convert to matrix if #groups small enough
for c=1:t
J(:,c)=metanetwork_i(B,S,t,c);
end
B = J;
M=B;
end
end
S2 = (1:length(B))';
Sb = [];
while ~isequal(Sb,S2) %loop around each "pass" (in language of Blondel et al) with B matrix
y = unique(S2); %unique also puts elements in ascending order
Sb = S2;
clocktime=clock;
mydisp(['Merging ',num2str(length(y)),' communities ',num2str(clocktime(4:6))]);
yb = [];
G=sparse(1:length(y),y,1);
dstep=1;
% P = G';
% Q = sum(sum((P*M).*(P)));
% Qb = -inf;
while (~isequal(yb,y)) && (dstep/dtot>2*eps) %This is the loop around Blondel et al's "first phase"
% mydisp([num2str(length(unique(y))),' ',num2str(Q)])
yb = y;
% Qb=Q;
dstep=0;
for i = myord(length(M))
u = unique([y(i);y(M(:,i)>0)]);
% dH = modchange_y(M(:,i),y,u); %relative changes in modularities
dH = (M(:,i)'*G(:,u));
yi=find(u==y(i));
dH(yi) = dH(yi) - M(i,i);
[~, k] = max(dH);
%%only move to different group if it is more optimized than
%%staying in same group (up to error with double precision)
if(dH(k)>(dH(yi)))
dtot=dtot+dH(k)-dH(yi);
dstep=dstep+dH(k)-dH(yi);
G(i,y(i))=0;
G(i,u(k))=1;
y(i) = u(k);
end
end
% P=sparse(y,1:length(y),1);
% Q = sum(sum((P*M).*(P)));
end
y = tidyconfig(y); %note tidyconfig reorders along node numbers
for i = 1:length(y)
S(S==i) = y(i);
S2(S2==i) = y(i);
end
if isequal(Sb,S2)
P=G';
Q=sum(sum((P*M).*P));
return
end
M = metanetwork(B,S2);
end
endfunction
%-----%
function M = metanetwork(J,S)
%Computes new aggregated network (communities --> nodes)
if(issparse(J))
m=max(S);
[i,j,v]=find(J);
M = sparse(S(i),S(j),v,m,m);
else
PP = sparse(1:length(S),S,1);
M = PP'*J*PP;
end
endfunction
%-----%
function Mi = metanetwork_i(J,S,t,i)
%ith column of metanetwork (used to create function handle)
%J is a function handle
Mi=sparse([],[],[],t,1);
for j=find(S==i)'
Jj=J(j);
[ii,k,v]=find(Jj);
Mi=Mi+sparse(S(ii),k,v,t,1);
end
endfunction
%-----%
function S = tidyconfig(S)
%This function remains almost identical to that originally written by
%Stephen Reid for his greedy.m code.
% tidy up S i.e. S = [2 4 2 6] -> S = [1 2 1 3]
T = zeros(length(S),1);
for i = 1:length(S)
if T(i) == 0
T(S==S(i)) = max(T) + 1;
end
end
S = T;
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Connected Components in Multilayer Networks
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Components,ComponentsSize] = GetConnectedComponentsExtended(SupraAdjacencyMatrix,Layers,Nodes)
%
% Returns the components of an undirected graph specified by the binary and
% undirected adjacency matrix adj. Components and their constitutent nodes are
% assigned the same index and stored in the vector, comps. The vector, comp_sizes,
% contains the number of nodes beloning to each component.
%
% Note: disconnected nodes will appear as components with a component
% size of 1
%
% J Goni, University of Navarra and Indiana University, 2009/2011
%
% This extended version treats each node in each layer as a independent entity
% Manlio De Domenico, Universitat Rovira i Virgili, 2014
#if ~any(SupraAdjacencyMatrix-triu(SupraAdjacencyMatrix))
SupraAdjacencyMatrix = SupraAdjacencyMatrix | SupraAdjacencyMatrix';
#end
%if main diagonal of adj do not contain all ones, i.e. autoloops
if sum(diag(SupraAdjacencyMatrix))~=size(SupraAdjacencyMatrix,1)
%the main diagonal is set to ones
SupraAdjacencyMatrix = SupraAdjacencyMatrix | speye(size(SupraAdjacencyMatrix));
end
%Dulmage-Mendelsohn decomposition
[useless1,p,useless2,r] = dmperm(SupraAdjacencyMatrix);
%p indicates a permutation (along rows and columns)
%r is a vector indicating the component boundaries
% List including the number of nodes of each component. ith entry is r(i+1)-r(i)
ComponentsSize = diff(r);
% Number of components found.
num_comps = numel(ComponentsSize);
% initialization
Components = sparse(1,Nodes*Layers);
% first position of each component is set to one
Components(r(1:num_comps)) = ones(1,num_comps);
% cumulative sum produces a label for each component (in a consecutive way)
Components = cumsum(Components);
%re-order component labels according to adj.
Components(p) = Components;
if sum(ComponentsSize) != Nodes*Layers
printf("ERROR! The sum of components size is not equal to the number of nodes x layers. Aborting process.\n")
exit
end
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Components,ComponentsSize] = GetConnectedComponentsSimple(SupraAdjacencyMatrix,Layers,Nodes)
%as the extended, but each node and its replicas are treated as a unique entity
[Components,ComponentsSize] = GetConnectedComponentsExtended(SupraAdjacencyMatrix,Layers,Nodes);
%first we have to check if the same entity is assigned to the same component
%eg, if node A in layer 1 is assigned to component 1 and node A in layer 2 is assigned to component 2
%then it makes no sense to collapse the information: if they are a unique entity, the nodes
%should be assigned to the same component, and this happens if they are interconnected or
%if some of the replicas are isolated components while the others are interconnected
if Layers > 1
newComponents = sparse(1,Nodes);
for n = 1:Nodes
c = Components(n); %the component assigned to n in layer 1
newComponents(n) = c;
for l = 2:Layers
ctmp = Components( (l-1)*Nodes + n );
if ctmp != c
%check if it is isolated
if ComponentsSize(ctmp)!=1 && ComponentsSize(c)!=1
printf("Impossible to find meaningful connected components\n")
printf("Node %d in layer 1 is in component %d (size %d) while\n",n,c,ComponentsSize(c))
printf("Node %d (abs id: %d) in layer %d is in component %d (size %d)\n",n,(l-1)*Nodes + n,l,ctmp,ComponentsSize(ctmp))
printf("Aborting process.\n")
exit
endif
endif
end
end
end
Components = sparse(1,Nodes);
comps = unique(newComponents);
%readjust the components label
for i = 1:length(comps)
c = comps(i);
find(newComponents==c);
Components( find(newComponents==c) ) = i;
end
%readjust the components size
ComponentsSize = sparse(1,full(max(Components)));
for c = 1:max(Components)
ComponentsSize(c) = sum( Components==c );
end
if sum(ComponentsSize) != Nodes
printf("ERROR! The sum of components size is not equal to the number of nodes. Aborting process.\n")
exit
end
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [GCC,GCCSize] = GetGiantConnectedComponentExtended(SupraAdjacencyMatrix,Layers,Nodes)
%compute the giant connected component, each node in each layer is a independent entity
[Components,ComponentsSize] = GetConnectedComponentsExtended(SupraAdjacencyMatrix,Layers,Nodes);
%if there are multiple components with the same size, we choose the first one
[value,cID] = max(ComponentsSize);
GCC = find(Components==cID);
GCCSize = value;
endfunction
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [GCC,GCCSize] = GetGiantConnectedComponentSimple(SupraAdjacencyMatrix,Layers,Nodes)
%as the extended, but each node and its replicas are treated as a unique entity
[Components,ComponentsSize] = GetConnectedComponentsSimple(SupraAdjacencyMatrix,Layers,Nodes);
%if there are multiple components with the same size, we choose the first one
[value,cID] = max(ComponentsSize);
GCC = find(Components==cID);
GCCSize = value;
endfunction |
github | LiHeUA/FastESC-master | demo_EBMM.m | .m | FastESC-master/EBMM_Release/demo_EBMM.m | 4,568 | utf_8 | 5e8cf84542aa9a2863c390e4c0f1bdd7 | function demo_EBMM
% Demot of Extended Basic Matrix Multiplication algorithm.
% Select cT columns (or rows) from A (or B) to form C (or R) so that
% AB\approx CR.
% Also verify Theorem 1 in [1].
%
% Details of this algorithm can be found in Alg. 2 in [1].
%
% [1] Li He, Nilanjan Ray and Hong Zhang, Fast Large-Scale Spectral
% Clustering via Explicit Feature Mapping, submitted to IEEE Trans.
% Cybernetics.
%
% Parameter:
% A p*NT matrix A
% B NT*q matrix B
% N scalar choose c from N
% T scalar # of submatrices in A and B
% c scalar choose c from N
%
% Notation:
% A^(t): the t-th column in matrix A
% B_(t): the t-th row in matrix B
%
% Notice:
% A should be structured as A = [A[1], A[2], ..., A[T]], where A[i] is a
% p*N matrix. And
% [B[1]]
% B = [B[2]]
% ...
% [B[T]]
% where B[i] is an N*q matrix.
%
% Main idea:
%
% 1. Split A into T submatrices, titled A[1], A[2],..., A[T],
% A = [A[1], A[2], ..., A[T]]
% and
% [B[1]]
% B = [B[2]]
% ...
% [B[T]]
%
% 2. Randomly with replacement pick the t-th index i_t \in {1,...,N} with
% probability Prob[i_t=k] = p_k, k=1,...,N.
%
% 3. For t=1,...,c, if i_t==k, then select the k-th columns in A[1],
% A[2],...,A[T], scale by 1/sqrt(c*p_k) and form a new matrix C[t],
% C[t]=[A[1]^(k), A[2]^(k),...,A[T]^(k)]/sqrt(c*p_k). And
% [B[1]_(k)]
% R[t] = [B[2]_(k)] /sqrt(c*p_k)
% ...
% [B[T]_(k)]
%
% 4. Build C=[C[1],C[2],...,C[T]], and
% [R[1]]
% R = [R[2]]
% ...
% [R[T]]
%
% 5. Then, E[CR]=AB.
%
% 6. For i=1,...,N, define
%
% H[i] = A[1]^(i)*B[1]_(i) + A[2]^(i)*B_(i) +...+ A[T]^(i)*B_(i)
%
% If
%
% p_i = ||H[i]||_F/sum(||H[i']||_F)
%
% Then, E[||AB-CR||_F^2] is minimal.
%
% Li He, [email protected]
%% 0. Initialization
clc
N = 6;
T = 2;
c = 3;
% randomly generate A and B
A = rand(100,N*T);
B = rand(N*T,200);
p = size(A,1);
q = size(B,2);
% randomly generate the sampling probabilities; for arbitraty prob_col.,
% E(CR)=AB should hold true
prob_col = rand(1,N);
prob_col = prob_col/sum(prob_col);
%% 1. Verification of E(CR)=AB with Arbitrary Probabilities
% we have in total N^c possible C (and R); exhaustively calculate all
disp('Exp 1: E(CR)=AB with arbitrary sampling probabilities')
% generate all N^c possible indices
indices = nchoosek_with_replacement(N,c);
% probability of one C (or R) to appear
prob_matrix = prod( prob_col(indices), 2 );
% build C and R, and brute-forcely check E(CR)
% ECR = sum( prob_matrix*C*R )
ECR = zeros(p,q);
% E[||AB-CR||_F^2]
ECRF = 0;
% ground truth AB
AB = A*B;
C = zeros(p,c*T);
R = zeros(c*T,q);
for i=1:N^c
% chosen columns (rows) among N^c possible choices
index = indices(i,:);
% build C and R
for t=1:c
ind = index(t); % index of one chosen column
C(:,t:c:end) = A(:,ind:N:end)/sqrt(c*prob_col(ind));
R(t:c:end,:) = B(ind:N:end,:)/sqrt(c*prob_col(ind));
end
% E(CR)
ECR = ECR + prob_matrix(i)*C*R;
% E(|AB-CR|_F^2)
ECRF = ECRF + prob_matrix(i)*norm(C*R-AB,'fro')^2;
end
disp(['||E(CR) - AB||_F = ' num2str(norm(ECR-AB,'fro'))])
%% 2. Optimal Sapmling
% if using the optimal sampling, then E[||AB-CR||_F^2] should be minimum
disp(' ');
disp('Exp 2: the optimal sampling will minimize E(|AB-CR|_F^2)')
% get the optimal sampling probabilities
prob_opt = EBMM_OptProb(A, B, N, T);
% probability of one C (or R) to appear
prob_matrix_opt = prod( prob_opt(indices), 2 );
% ECR = sum( prob_matrix*C*R )
ECR_opt = zeros(p,q);
% E[||AB-CR||_F^2]
ECRF_opt = 0;
C = zeros(p,c*T);
R = zeros(c*T,q);
for i=1:N^c
% chosen columns (rows) among N^c possible choices
index = indices(i,:);
% build C and R
for t=1:c
ind = index(t); % index of one chosen column
C(:,t:c:end) = A(:,ind:N:end)/sqrt(c*prob_opt(ind));
R(t:c:end,:) = B(ind:N:end,:)/sqrt(c*prob_opt(ind));
end
ECR_opt = ECR_opt + prob_matrix_opt(i)*C*R;
ECRF_opt = ECRF_opt + prob_matrix_opt(i)*norm(C*R-AB,'fro')^2;
end
disp(['||E(CR_opt) - AB||_F = ' num2str(norm(ECR_opt-AB,'fro'))])
% compare the F-norm error of CR_optimal with the CR in Experiment 1
disp(['E[||CR_opt - AB||_F^2 = ' num2str(ECRF_opt) ', E[||CR_Exp1 - AB||_F^2 = ' num2str(ECRF)])
function indices = nchoosek_with_replacement(n,k)
indices = cell(1,k);
[indices{:}] = ndgrid(1:n);
indices = indices(end:-1:1);
indices = cat(k+1, indices{:});
indices = reshape(indices, [n^k, k]); |
github | mirtaheri/Grid-visualization-in-Matlab-master | plotCustMark.m | .m | Grid-visualization-in-Matlab-master/funcs/plotCustMark.m | 1,239 | utf_8 | 2a019f8cd68d58ea1aae70790ecba3d0 |
function patchHndl = plotCustMark(xData,yData,markerDataX,markerDataY,markerSize, lineThick, face_color)
% this function uses codes from: https://it.mathworks.com/matlabcentral/fileexchange/39487-custom-marker-plot
xData = reshape(xData,length(xData),1) ;
yData = reshape(yData,length(yData),1) ;
markerDataX = markerSize * reshape(markerDataX,1,length(markerDataX)) ;
markerDataY = markerSize * reshape(markerDataY,1,length(markerDataY)) ;
%% prepare and plot the patches
markerEdgeColor = [0 0 0] ;
markerFaceColor = face_color ;
% ------
vertX = repmat(markerDataX,length(xData),1) ; vertX = vertX(:) ;
vertY = repmat(markerDataY,length(yData),1) ; vertY = vertY(:) ;
% ------
vertX = repmat(xData,length(markerDataX),1) + vertX ;
vertY = repmat(yData,length(markerDataY),1) + vertY ;
% ------
faces = 0:length(xData):length(xData)*(length(markerDataY)-1) ;
faces = repmat(faces,length(xData),1) ;
faces = repmat((1:length(xData))',1,length(markerDataY)) + faces ;
% ------
patchHndl = patch('Faces',faces,'Vertices',[vertX vertY]);
set(patchHndl,'FaceColor',markerFaceColor,'LineWidth', lineThick, 'EdgeColor',markerEdgeColor) ;
hold on
% -------------------------------------------------------------
|
github | leonid-pishchulin/poseval-master | savejson.m | .m | poseval-master/matlab/external/jsonlab/savejson.m | 18,981 | utf_8 | 63859e6bc24eb998f433f53d5880015b | function json=savejson(rootname,obj,varargin)
%
% json=savejson(rootname,obj,filename)
% or
% json=savejson(rootname,obj,opt)
% json=savejson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a JSON (JavaScript
% Object Notation) string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance).
% filename: a string for the file name to save the output JSON data.
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.FloatFormat ['%.10g'|string]: format to show each numeric element
% of a 1D/2D array;
% opt.ArrayIndent [1|0]: if 1, output explicit data array with
% precedent indentation; if 0, no indentation
% opt.ArrayToStruct[0|1]: when set to 0, savejson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [0|1]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, savejson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.Inf ['"$1_Inf_"'|string]: a customized regular expression pattern
% to represent +/-Inf. The matched pattern is '([-+]*)Inf'
% and $1 represents the sign. For those who want to use
% 1e999 to represent Inf, they can set opt.Inf to '$11e999'
% opt.NaN ['"_NaN_"'|string]: a customized regular expression pattern
% to represent NaN
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSONP='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
% opt.SaveBinary [0|1]: 1 - save the JSON file in binary mode; 0 - text mode.
% opt.Compact [0|1]: 1- out compact JSON format (remove all newlines and tabs)
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a string in the JSON format (see http://json.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% savejson('jmesh',jsonmesh)
% savejson('',jsonmesh,'ArrayIndent',0,'FloatFormat','\t%.5g')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(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');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
whitespaces=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
if(jsonopt('Compact',0,opt)==1)
whitespaces=struct('tab','','newline','','sep',',');
end
if(~isfield(opt,'whitespaces_'))
opt.whitespaces_=whitespaces;
end
nl=whitespaces.newline;
json=obj2json(rootname,obj,rootlevel,opt);
if(rootisarray)
json=sprintf('%s%s',json,nl);
else
json=sprintf('{%s%s%s}\n',nl,json,nl);
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=sprintf('%s(%s);%s',jsonp,json,nl);
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
if(jsonopt('SaveBinary',0,opt)==1)
fid = fopen(filename, 'wb');
fwrite(fid,json);
else
fid = fopen(filename, 'wt');
fwrite(fid,json,'char');
end
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2json(name,item,level,varargin)
if(iscell(item))
txt=cell2json(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2json(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2json(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2json(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;
bracketlevel=~jsonopt('singletcell',1,varargin{:});
if(len>bracketlevel)
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl}; name='';
else
txt={padding0, '[', nl};
end
elseif(len==0)
if(~isempty(name))
txt={padding0, '"' checkname(name,varargin{:}) '": []'}; name='';
else
txt={padding0, '[]'};
end
end
for i=1:dim(1)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for j=1:dim(2)
txt{end+1}=obj2json(name,item{i,j},level+(dim(1)>1)+(len>bracketlevel),varargin{:});
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
%if(j==dim(2)) txt=sprintf('%s%s',txt,sprintf(',%s',nl)); end
end
if(len>bracketlevel)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=struct2json(name,item,level,varargin)
txt={};
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding0=repmat(ws.tab,1,level);
padding2=repmat(ws.tab,1,level+1);
padding1=repmat(ws.tab,1,level+(dim(1)>1)+forcearray);
nl=ws.newline;
if(isempty(item))
if(~isempty(name))
txt={padding0, '"', checkname(name,varargin{:}),'": []'};
else
txt={padding0, '[]'};
end
return;
end
if(~isempty(name))
if(forcearray)
txt={padding0, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(forcearray)
txt={padding0, '[', nl};
end
end
for j=1:dim(2)
if(dim(1)>1)
txt(end+1:end+3)={padding2,'[',nl};
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt(end+1:end+5)={padding1, '"', checkname(name,varargin{:}),'": {', nl};
else
txt(end+1:end+3)={padding1, '{', nl};
end
if(~isempty(names))
for e=1:length(names)
txt{end+1}=obj2json(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:});
if(e<length(names))
txt{end+1}=',';
end
txt{end+1}=nl;
end
end
txt(end+1:end+2)={padding1,'}'};
if(i<dim(1))
txt(end+1:end+2)={',' nl};
end
end
if(dim(1)>1)
txt(end+1:end+3)={nl,padding2,']'};
end
if(j<dim(2))
txt(end+1:end+2)={',' nl};
end
end
if(forcearray)
txt(end+1:end+3)={nl,padding0,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
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={padding1, '"', checkname(name,varargin{:}),'": [', nl};
end
else
if(len>1)
txt={padding1, '[', nl};
end
end
for e=1:len
val=escapejsonstring(item(e,:));
if(len==1)
obj=['"' checkname(name,varargin{:}) '": ' '"',val,'"'];
if(isempty(name))
obj=['"',val,'"'];
end
txt(end+1:end+2)={padding1, obj};
else
txt(end+1:end+4)={padding0,'"',val,'"'};
end
if(e==len)
sep='';
end
txt{end+1}=sep;
end
if(len>1)
txt(end+1:end+3)={nl,padding1,']'};
end
txt = sprintf('%s',txt{:});
%%-------------------------------------------------------------------------
function txt=mat2json(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
ws=struct('tab',sprintf('\t'),'newline',sprintf('\n'),'sep',sprintf(',\n'));
ws=jsonopt('whitespaces_',ws,varargin{:});
padding1=repmat(ws.tab,1,level);
padding0=repmat(ws.tab,1,level+1);
nl=ws.newline;
sep=ws.sep;
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
if(isempty(name))
txt=sprintf('%s{%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
else
txt=sprintf('%s"%s": {%s%s"_ArrayType_": "%s",%s%s"_ArraySize_": %s,%s',...
padding1,checkname(name,varargin{:}),nl,padding0,class(item),nl,padding0,regexprep(mat2str(size(item)),'\s+',','),nl);
end
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0 && level>0)
numtxt=regexprep(regexprep(matdata2json(item,level+1,varargin{:}),'^\[',''),']','');
else
numtxt=matdata2json(item,level+1,varargin{:});
end
if(isempty(name))
txt=sprintf('%s%s',padding1,numtxt);
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
else
txt=sprintf('%s"%s": %s',padding1,checkname(name,varargin{:}),numtxt);
end
end
return;
end
dataformat='%s%s%s%s%s';
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
end
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsSparse_": ','1', sep);
if(size(item,1)==1)
% Row vector, store only column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([iy(:),data'],level+2,varargin{:}), nl);
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,data],level+2,varargin{:}), nl);
else
% General case, store row and column indices.
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([ix,iy,data],level+2,varargin{:}), nl);
end
else
if(isreal(item))
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json(item(:)',level+2,varargin{:}), nl);
else
txt=sprintf(dataformat,txt,padding0,'"_ArrayIsComplex_": ','1', sep);
txt=sprintf(dataformat,txt,padding0,'"_ArrayData_": ',...
matdata2json([real(item(:)) imag(item(:))],level+2,varargin{:}), nl);
end
end
txt=sprintf('%s%s%s',txt,padding1,'}');
%%-------------------------------------------------------------------------
function txt=matlabobject2json(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2json(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=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='[]';
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
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\$1');
else
escapechars={'\\','\"','\/','\a','\b','\f','\n','\r','\t','\v'};
for i=1:length(escapechars);
newstr=regexprep(newstr,escapechars{i},regexprep(escapechars{i},'\\','\\\\'));
end
newstr=regexprep(newstr,'\\\\(u[0-9a-fA-F]{4}[^0-9a-fA-F]*)','\\$1');
end
|
github | leonid-pishchulin/poseval-master | loadjson.m | .m | poseval-master/matlab/external/jsonlab/loadjson.m | 16,145 | ibm852 | 7582071c5bd7f5e5f74806ce191a9078 | function data = loadjson(fname,varargin)
%
% data=loadjson(fname,opt)
% or
% data=loadjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2011/09/09, including previous works from
%
% Nedialko Krouchev: http://www.mathworks.com/matlabcentral/fileexchange/25713
% created on 2009/11/02
% François Glineur: http://www.mathworks.com/matlabcentral/fileexchange/23393
% created on 2009/03/22
% Joel Feenstra:
% http://www.mathworks.com/matlabcentral/fileexchange/20565
% created on 2008/07/03
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a JSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.FastArrayParser [1|0 or integer]: if set to 1, use a
% speed-optimized array parser when loading an
% array object. The fast array parser may
% collapse block arrays into a single large
% array similar to rules defined in cell2mat; 0 to
% use a legacy parser; if set to a larger-than-1
% value, this option will specify the minimum
% dimension to enable the fast array parser. For
% example, if the input is a 3D array, setting
% FastArrayParser to 1 will return a 3D array;
% setting to 2 will return a cell array of 2D
% arrays; setting to 3 will return to a 2D cell
% array of 1D vectors; setting to 4 will return a
% 3D cell array.
% opt.ShowProgress [0|1]: if set to 1, loadjson displays a progress bar.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% dat=loadjson('{"obj":{"string":"value","array":[1,2,3]}}')
% dat=loadjson(['examples' filesep 'example1.json'])
% dat=loadjson(['examples' filesep 'example1.json'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken
if(regexp(fname,'^\s*(?:\[.+\])|(?:\{.+\})\s*$','once'))
string=fname;
elseif(exist(fname,'file'))
try
string = fileread(fname);
catch
try
string = urlread(['file://',fname]);
catch
string = urlread(['file://',fullfile(pwd,fname)]);
end
end
else
error('input file does not exist');
end
pos = 1; len = length(string); inStr = string;
isoct=exist('OCTAVE_VERSION','builtin');
arraytoken=find(inStr=='[' | inStr==']' | inStr=='"');
jstr=regexprep(inStr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
% String delimiters and escape chars identified to improve speed:
esc = find(inStr=='"' | inStr=='\' ); % comparable to: regexp(inStr, '["\\]');
index_esc = 1; len_esc = length(esc);
opt=varargin2struct(varargin{:});
if(jsonopt('ShowProgress',0,opt)==1)
opt.progressbar_=waitbar(0,'loading ...');
end
jsoncount=1;
while pos <= len
switch(next_char)
case '{'
data{jsoncount} = parse_object(opt);
case '['
data{jsoncount} = parse_array(opt);
otherwise
error_pos('Outer level structure must be an object or an array');
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(isfield(opt,'progressbar_'))
close(opt.progressbar_);
end
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
if next_char ~= '}'
while 1
str = parseStr(varargin{:});
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
parse_char(':');
val = parse_value(varargin{:});
object.(valid_field(str))=val;
if next_char == '}'
break;
end
parse_char(',');
end
end
parse_char('}');
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function object = parse_array(varargin) % JSON array is written in row-major order
global pos inStr isoct
parse_char('[');
object = cell(0, 1);
dim2=[];
arraydepth=jsonopt('JSONLAB_ArrayDepth_',1,varargin{:});
pbar=-1;
if(isfield(varargin{1},'progressbar_'))
pbar=varargin{1}.progressbar_;
end
if next_char ~= ']'
if(jsonopt('FastArrayParser',1,varargin{:})>=1 && arraydepth>=jsonopt('FastArrayParser',1,varargin{:}))
[endpos, e1l, e1r]=matching_bracket(inStr,pos);
arraystr=['[' inStr(pos:endpos)];
arraystr=regexprep(arraystr,'"_NaN_"','NaN');
arraystr=regexprep(arraystr,'"([-+]*)_Inf_"','$1Inf');
arraystr(arraystr==sprintf('\n'))=[];
arraystr(arraystr==sprintf('\r'))=[];
%arraystr=regexprep(arraystr,'\s*,',','); % this is slow,sometimes needed
if(~isempty(e1l) && ~isempty(e1r)) % the array is in 2D or higher D
astr=inStr((e1l+1):(e1r-1));
astr=regexprep(astr,'"_NaN_"','NaN');
astr=regexprep(astr,'"([-+]*)_Inf_"','$1Inf');
astr(astr==sprintf('\n'))=[];
astr(astr==sprintf('\r'))=[];
astr(astr==' ')='';
if(isempty(find(astr=='[', 1))) % array is 2D
dim2=length(sscanf(astr,'%f,',[1 inf]));
end
else % array is 1D
astr=arraystr(2:end-1);
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',[1,inf]);
if(nextidx>=length(astr)-1)
object=obj;
pos=endpos;
parse_char(']');
return;
end
end
if(~isempty(dim2))
astr=arraystr;
astr(astr=='[')='';
astr(astr==']')='';
astr(astr==' ')='';
[obj, count, errmsg, nextidx]=sscanf(astr,'%f,',inf);
if(nextidx>=length(astr)-1)
object=reshape(obj,dim2,numel(obj)/dim2)';
pos=endpos;
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
return;
end
end
arraystr=regexprep(arraystr,'\]\s*,','];');
else
arraystr='[';
end
try
if(isoct && regexp(arraystr,'"','once'))
error('Octave eval can produce empty cells for JSON-like input');
end
object=eval(arraystr);
pos=endpos;
catch
while 1
newopt=varargin2struct(varargin{:},'JSONLAB_ArrayDepth_',arraydepth+1);
val = parse_value(newopt);
object{end+1} = val;
if next_char == ']'
break;
end
parse_char(',');
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
parse_char(']');
if(pbar>0)
waitbar(pos/length(inStr),pbar,'loading ...');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
pos=skip_whitespace(pos,inStr,len);
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
pos=skip_whitespace(pos,inStr,len);
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function newpos=skip_whitespace(pos,inStr,len)
newpos=pos;
while newpos <= len && isspace(inStr(newpos))
newpos = newpos + 1;
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr len esc index_esc len_esc
% len, ns = length(inStr), keyboard
if inStr(pos) ~= '"'
error_pos('String starting with " expected at position %d');
else
pos = pos + 1;
end
str = '';
while pos <= len
while index_esc <= len_esc && esc(index_esc) < pos
index_esc = index_esc + 1;
end
if index_esc > len_esc
str = [str inStr(pos:len)];
pos = len + 1;
break;
else
str = [str inStr(pos:esc(index_esc)-1)];
pos = esc(index_esc);
end
nstr = length(str);
switch inStr(pos)
case '"'
pos = pos + 1;
if(~isempty(str))
if(strcmp(str,'_Inf_'))
str=Inf;
elseif(strcmp(str,'-_Inf_'))
str=-Inf;
elseif(strcmp(str,'_NaN_'))
str=NaN;
end
end
return;
case '\'
if pos+1 > len
error_pos('End of file reached right after escape character');
end
pos = pos + 1;
switch inStr(pos)
case {'"' '\' '/'}
str(nstr+1) = inStr(pos);
pos = pos + 1;
case {'b' 'f' 'n' 'r' 't'}
str(nstr+1) = sprintf(['\' inStr(pos)]);
pos = pos + 1;
case 'u'
if pos+4 > len
error_pos('End of file reached in escaped unicode character');
end
str(nstr+(1:6)) = inStr(pos-1:pos+4);
pos = pos + 5;
end
otherwise % should never happen
str(nstr+1) = inStr(pos);
keyboard;
pos = pos + 1;
end
end
error_pos('End of file while expecting end of inStr');
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct
currstr=inStr(pos:min(pos+30,end));
if(isoct~=0)
numstr=regexp(currstr,'^\s*-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?','end');
[num] = sscanf(currstr, '%f', 1);
delta=numstr+1;
else
[num, one, err, delta] = sscanf(currstr, '%f', 1);
if ~isempty(err)
error_pos('Error reading number at position %d');
end
end
pos = pos + delta-1;
%%-------------------------------------------------------------------------
function val = parse_value(varargin)
global pos inStr len
if(isfield(varargin{1},'progressbar_'))
waitbar(pos/len,varargin{1}.progressbar_,'loading ...');
end
switch(inStr(pos))
case '"'
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'-','0','1','2','3','4','5','6','7','8','9'}
val = parse_number(varargin{:});
return;
case 't'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'true')
val = true;
pos = pos + 4;
return;
end
case 'f'
if pos+4 <= len && strcmpi(inStr(pos:pos+4), 'false')
val = false;
pos = pos + 5;
return;
end
case 'n'
if pos+3 <= len && strcmpi(inStr(pos:pos+3), 'null')
val = [];
pos = pos + 4;
return;
end
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | leonid-pishchulin/poseval-master | loadubjson.m | .m | poseval-master/matlab/external/jsonlab/loadubjson.m | 13,300 | utf_8 | b15e959f758c5c2efa2711aa79c443fc | function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/01
%
% $Id$
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% opt.SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% opt.IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
% opt.NameIsString [0|1]: for UBJSON Specification Draft 8 or
% earlier versions (JSONLab 1.0 final or earlier),
% the "name" tag is treated as a string. To load
% these UBJSON data, you need to manually set this
% flag to 1.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
global pos inStr len esc index_esc len_esc isoct arraytoken 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
%%-------------------------------------------------------------------------
function object = parse_object(varargin)
parse_char('{');
object = [];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1); % TODO
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
count=double(parse_number());
end
if next_char ~= '}'
num=0;
while 1
if(jsonopt('NameIsString',0,varargin{:}))
str = parseStr(varargin{:});
else
str = parse_name(varargin{:});
end
if isempty(str)
error_pos('Name of value at position %d cannot be empty');
end
%parse_char(':');
val = parse_value(varargin{:});
num=num+1;
object.(valid_field(str))=val;
if next_char == '}' || (count>=0 && num>=count)
break;
end
%parse_char(',');
end
end
if(count==-1)
parse_char('}');
end
if(isstruct(object))
object=struct2jdata(object);
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d');
end
%%-------------------------------------------------------------------------
function [data, adv]=parse_block(type,count,varargin)
global pos inStr isoct fileendian systemendian
[cid,len]=elem_info(type);
datastr=inStr(pos:pos+len*count-1);
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
parse_char('[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
if(next_char == '$')
type=inStr(pos+1);
pos=pos+2;
end
if(next_char == '#')
pos=pos+1;
if(next_char=='[')
dim=parse_array(varargin{:});
count=prod(double(dim));
else
count=double(parse_number());
end
end
if(~isempty(type))
if(count>=0)
[object, adv]=parse_block(type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=matching_bracket(inStr,pos);
[cid,len]=elem_info(type);
count=(endpos-pos)/len;
[object, adv]=parse_block(type,count,varargin{:});
pos=pos+adv;
parse_char(']');
return;
end
end
if next_char ~= ']'
while 1
val = parse_value(varargin{:});
object{end+1} = val;
if next_char == ']'
break;
end
%parse_char(',');
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
if(count==-1)
parse_char(']');
end
%%-------------------------------------------------------------------------
function parse_char(c)
global pos inStr len
skip_whitespace;
if pos > len || inStr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c));
else
pos = pos + 1;
skip_whitespace;
end
%%-------------------------------------------------------------------------
function c = next_char
global pos inStr len
skip_whitespace;
if pos > len
c = [];
else
c = inStr(pos);
end
%%-------------------------------------------------------------------------
function skip_whitespace
global pos inStr len
while pos <= len && isspace(inStr(pos))
pos = pos + 1;
end
%%-------------------------------------------------------------------------
function str = parse_name(varargin)
global pos inStr
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of name');
end
%%-------------------------------------------------------------------------
function str = parseStr(varargin)
global pos inStr
% len, ns = length(inStr), keyboard
type=inStr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d');
else
pos = pos + 1;
end
if(type == 'C')
str=inStr(pos);
pos=pos+1;
return;
end
bytelen=double(parse_number());
if(length(inStr)>=pos+bytelen-1)
str=inStr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inStr');
end
%%-------------------------------------------------------------------------
function num = parse_number(varargin)
global pos inStr isoct fileendian systemendian
id=strfind('iUIlLdD',inStr(pos));
if(isempty(id))
error_pos('expecting a number at position %d');
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inStr(pos+1:pos+bytelen(id));
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
switch(inStr(pos))
case {'S','C','H'}
val = parseStr(varargin{:});
return;
case '['
val = parse_array(varargin{:});
return;
case '{'
val = parse_object(varargin{:});
return;
case {'i','U','I','l','L','d','D'}
val = parse_number(varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d');
%%-------------------------------------------------------------------------
function error_pos(msg)
global pos inStr len
poShow = max(min([pos-15 pos-1 pos pos+20],len),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inStr(poShow(1):poShow(2)) '<error>' inStr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
%%-------------------------------------------------------------------------
function str = valid_field(str)
global isoct
% From MATLAB doc: field names must begin with a letter, which may be
% followed by any combination of letters, digits, and underscores.
% Invalid characters will be converted to underscores, and the prefix
% "x0x[Hex code]_" will be added if the first character is not a letter.
pos=regexp(str,'^[^A-Za-z]','once');
if(~isempty(pos))
if(~isoct)
str=regexprep(str,'^([^A-Za-z])','x0x${sprintf(''%X'',unicode2native($1))}_','once');
else
str=sprintf('x0x%X_%s',char(str(1)),str(2:end));
end
end
if(isempty(regexp(str,'[^0-9A-Za-z_]', 'once' )))
return;
end
if(~isoct)
str=regexprep(str,'([^0-9A-Za-z_])','_0x${sprintf(''%X'',unicode2native($1))}_');
else
pos=regexp(str,'[^0-9A-Za-z_]');
if(isempty(pos))
return;
end
str0=str;
pos0=[0 pos(:)' length(str)];
str='';
for i=1:length(pos)
str=[str str0(pos0(i)+1:pos(i)-1) sprintf('_0x%X_',str0(pos(i)))];
end
if(pos(end)~=length(str))
str=[str str0(pos0(end-1)+1:pos0(end))];
end
end
%str(~isletter(str) & ~('0' <= str & str <= '9')) = '_';
%%-------------------------------------------------------------------------
function endpos = matching_quote(str,pos)
len=length(str);
while(pos<len)
if(str(pos)=='"')
if(~(pos>1 && str(pos-1)=='\'))
endpos=pos;
return;
end
end
pos=pos+1;
end
error('unmatched quotation mark');
%%-------------------------------------------------------------------------
function [endpos, e1l, e1r, maxlevel] = matching_bracket(str,pos)
global arraytoken
level=1;
maxlevel=level;
endpos=0;
bpos=arraytoken(arraytoken>=pos);
tokens=str(bpos);
len=length(tokens);
pos=1;
e1l=[];
e1r=[];
while(pos<=len)
c=tokens(pos);
if(c==']')
level=level-1;
if(isempty(e1r))
e1r=bpos(pos);
end
if(level==0)
endpos=bpos(pos);
return
end
end
if(c=='[')
if(isempty(e1l))
e1l=bpos(pos);
end
level=level+1;
maxlevel=max(maxlevel,level);
end
if(c=='"')
pos=matching_quote(tokens,pos+1);
end
pos=pos+1;
end
if(endpos==0)
error('unmatched "]"');
end
|
github | leonid-pishchulin/poseval-master | saveubjson.m | .m | poseval-master/matlab/external/jsonlab/saveubjson.m | 17,723 | utf_8 | 3414421172c05225dfbd4a9c8c76e6b3 | function json=saveubjson(rootname,obj,varargin)
%
% json=saveubjson(rootname,obj,filename)
% or
% json=saveubjson(rootname,obj,opt)
% json=saveubjson(rootname,obj,'param1',value1,'param2',value2,...)
%
% convert a MATLAB object (cell, struct or array) into a Universal
% Binary JSON (UBJSON) binary string
%
% author: Qianqian Fang (fangq<at> nmr.mgh.harvard.edu)
% created on 2013/08/17
%
% $Id$
%
% input:
% rootname: the name of the root-object, when set to '', the root name
% is ignored, however, when opt.ForceRootName is set to 1 (see below),
% the MATLAB variable name will be used as the root name.
% obj: a MATLAB object (array, cell, cell array, struct, struct array,
% class instance)
% filename: a string for the file name to save the output UBJSON data
% opt: a struct for additional options, ignore to use default values.
% opt can have the following fields (first in [.|.] is the default)
%
% opt.FileName [''|string]: a file name to save the output JSON data
% opt.ArrayToStruct[0|1]: when set to 0, saveubjson outputs 1D/2D
% array in JSON array format; if sets to 1, an
% array will be shown as a struct with fields
% "_ArrayType_", "_ArraySize_" and "_ArrayData_"; for
% sparse arrays, the non-zero elements will be
% saved to _ArrayData_ field in triplet-format i.e.
% (ix,iy,val) and "_ArrayIsSparse_" will be added
% with a value of 1; for a complex array, the
% _ArrayData_ array will include two columns
% (4 for sparse) to record the real and imaginary
% parts, and also "_ArrayIsComplex_":1 is added.
% opt.ParseLogical [1|0]: if this is set to 1, logical array elem
% will use true/false rather than 1/0.
% opt.SingletArray [0|1]: if this is set to 1, arrays with a single
% numerical element will be shown without a square
% bracket, unless it is the root object; if 0, square
% brackets are forced for any numerical arrays.
% opt.SingletCell [1|0]: if 1, always enclose a cell with "[]"
% even it has only one element; if 0, brackets
% are ignored when a cell has only 1 element.
% opt.ForceRootName [0|1]: when set to 1 and rootname is empty, saveubjson
% will use the name of the passed obj variable as the
% root object name; if obj is an expression and
% does not have a name, 'root' will be used; if this
% is set to 0 and rootname is empty, the root level
% will be merged down to the lower level.
% opt.JSONP [''|string]: to generate a JSONP output (JSON with padding),
% for example, if opt.JSON='foo', the JSON data is
% wrapped inside a function call as 'foo(...);'
% opt.UnpackHex [1|0]: conver the 0x[hex code] output by loadjson
% back to the string form
%
% opt can be replaced by a list of ('param',value) pairs. The param
% string is equivallent to a field in opt and is case sensitive.
% output:
% json: a binary string in the UBJSON format (see http://ubjson.org)
%
% examples:
% jsonmesh=struct('MeshNode',[0 0 0;1 0 0;0 1 0;1 1 0;0 0 1;1 0 1;0 1 1;1 1 1],...
% 'MeshTetra',[1 2 4 8;1 3 4 8;1 2 6 8;1 5 6 8;1 5 7 8;1 3 7 8],...
% 'MeshTri',[1 2 4;1 2 6;1 3 4;1 3 7;1 5 6;1 5 7;...
% 2 8 4;2 8 6;3 8 4;3 8 7;5 8 6;5 8 7],...
% 'MeshCreator','FangQ','MeshTitle','T6 Cube',...
% 'SpecialData',[nan, inf, -inf]);
% saveubjson('jsonmesh',jsonmesh)
% saveubjson('jsonmesh',jsonmesh,'meshdata.ubj')
%
% license:
% BSD License, see LICENSE_BSD.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(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');
if(isfield(opt,'norowbracket'))
warning('Option ''NoRowBracket'' is depreciated, please use ''SingletArray'' and set its value to not(NoRowBracket)');
if(~isfield(opt,'singletarray'))
opt.singletarray=not(opt.norowbracket);
end
end
rootisarray=0;
rootlevel=1;
forceroot=jsonopt('ForceRootName',0,opt);
if((isnumeric(obj) || islogical(obj) || ischar(obj) || isstruct(obj) || ...
iscell(obj) || isobject(obj)) && isempty(rootname) && forceroot==0)
rootisarray=1;
rootlevel=0;
else
if(isempty(rootname))
rootname=varname;
end
end
if((isstruct(obj) || iscell(obj))&& isempty(rootname) && forceroot)
rootname='root';
end
json=obj2ubjson(rootname,obj,rootlevel,opt);
if(~rootisarray)
json=['{' json '}'];
end
jsonp=jsonopt('JSONP','',opt);
if(~isempty(jsonp))
json=[jsonp '(' json ')'];
end
% save to a file if FileName is set, suggested by Patrick Rapin
filename=jsonopt('FileName','',opt);
if(~isempty(filename))
fid = fopen(filename, 'wb');
fwrite(fid,json);
fclose(fid);
end
%%-------------------------------------------------------------------------
function txt=obj2ubjson(name,item,level,varargin)
if(iscell(item))
txt=cell2ubjson(name,item,level,varargin{:});
elseif(isstruct(item))
txt=struct2ubjson(name,item,level,varargin{:});
elseif(ischar(item))
txt=str2ubjson(name,item,level,varargin{:});
elseif(isobject(item))
txt=matlabobject2ubjson(name,item,level,varargin{:});
else
txt=mat2ubjson(name,item,level,varargin{:});
end
%%-------------------------------------------------------------------------
function txt=cell2ubjson(name,item,level,varargin)
txt='';
if(~iscell(item))
error('input is not a cell');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
bracketlevel=~jsonopt('singletcell',1,varargin{:});
len=numel(item); % let's handle 1D cell first
if(len>bracketlevel)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) '[']; name='';
else
txt='[';
end
elseif(len==0)
if(~isempty(name))
txt=[N_(checkname(name,varargin{:})) 'Z']; name='';
else
txt='Z';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
txt=[txt obj2ubjson(name,item{i,j},level+(len>bracketlevel),varargin{:})];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(len>bracketlevel)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=struct2ubjson(name,item,level,varargin)
txt='';
if(~isstruct(item))
error('input is not a struct');
end
dim=size(item);
if(ndims(squeeze(item))>2) % for 3D or higher dimensions, flatten to 2D for now
item=reshape(item,dim(1),numel(item)/dim(1));
dim=size(item);
end
len=numel(item);
forcearray= (len>1 || (jsonopt('SingletArray',0,varargin{:})==1 && level>0));
if(~isempty(name))
if(forcearray)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(forcearray)
txt='[';
end
end
for j=1:dim(2)
if(dim(1)>1)
txt=[txt '['];
end
for i=1:dim(1)
names = fieldnames(item(i,j));
if(~isempty(name) && len==1 && ~forcearray)
txt=[txt N_(checkname(name,varargin{:})) '{'];
else
txt=[txt '{'];
end
if(~isempty(names))
for e=1:length(names)
txt=[txt obj2ubjson(names{e},item(i,j).(names{e}),...
level+(dim(1)>1)+1+forcearray,varargin{:})];
end
end
txt=[txt '}'];
end
if(dim(1)>1)
txt=[txt ']'];
end
end
if(forcearray)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=str2ubjson(name,item,level,varargin)
txt='';
if(~ischar(item))
error('input is not a string');
end
item=reshape(item, max(size(item),[1 0]));
len=size(item,1);
if(~isempty(name))
if(len>1)
txt=[N_(checkname(name,varargin{:})) '['];
end
else
if(len>1)
txt='[';
end
end
for e=1:len
val=item(e,:);
if(len==1)
obj=[N_(checkname(name,varargin{:})) '' '',S_(val),''];
if(isempty(name))
obj=['',S_(val),''];
end
txt=[txt,'',obj];
else
txt=[txt,'',['',S_(val),'']];
end
end
if(len>1)
txt=[txt ']'];
end
%%-------------------------------------------------------------------------
function txt=mat2ubjson(name,item,level,varargin)
if(~isnumeric(item) && ~islogical(item))
error('input is not an array');
end
if(length(size(item))>2 || issparse(item) || ~isreal(item) || ...
(isempty(item) && any(size(item))) ||jsonopt('ArrayToStruct',0,varargin{:}))
cid=I_(uint32(max(size(item))));
if(isempty(name))
txt=['{' N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1)) ];
else
if(isempty(item))
txt=[N_(checkname(name,varargin{:})),'Z'];
return;
else
txt=[N_(checkname(name,varargin{:})),'{',N_('_ArrayType_'),S_(class(item)),N_('_ArraySize_'),I_a(size(item),cid(1))];
end
end
else
if(isempty(name))
txt=matdata2ubjson(item,level+1,varargin{:});
else
if(numel(item)==1 && jsonopt('SingletArray',0,varargin{:})==0)
numtxt=regexprep(regexprep(matdata2ubjson(item,level+1,varargin{:}),'^\[',''),']','');
txt=[N_(checkname(name,varargin{:})) numtxt];
else
txt=[N_(checkname(name,varargin{:})),matdata2ubjson(item,level+1,varargin{:})];
end
end
return;
end
if(issparse(item))
[ix,iy]=find(item);
data=full(item(find(item)));
if(~isreal(item))
data=[real(data(:)),imag(data(:))];
if(size(item,1)==1)
% Kludge to have data's 'transposedness' match item's.
% (Necessary for complex row vector handling below.)
data=data';
end
txt=[txt,N_('_ArrayIsComplex_'),'T'];
end
txt=[txt,N_('_ArrayIsSparse_'),'T'];
if(size(item,1)==1)
% Row vector, store only column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([iy(:),data'],level+2,varargin{:})];
elseif(size(item,2)==1)
% Column vector, store only row indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,data],level+2,varargin{:})];
else
% General case, store row and column indices.
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([ix,iy,data],level+2,varargin{:})];
end
else
if(isreal(item))
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson(item(:)',level+2,varargin{:})];
else
txt=[txt,N_('_ArrayIsComplex_'),'T'];
txt=[txt,N_('_ArrayData_'),...
matdata2ubjson([real(item(:)) imag(item(:))],level+2,varargin{:})];
end
end
txt=[txt,'}'];
%%-------------------------------------------------------------------------
function txt=matlabobject2ubjson(name,item,level,varargin)
if numel(item) == 0 %empty object
st = struct();
else
% "st = struct(item);" would produce an inmutable warning, because it
% make the protected and private properties visible. Instead we get the
% visible properties
propertynames = properties(item);
for p = 1:numel(propertynames)
for o = numel(item):-1:1 % aray of objects
st(o).(propertynames{p}) = item(o).(propertynames{p});
end
end
end
txt=struct2ubjson(name,st,level,varargin{:});
%%-------------------------------------------------------------------------
function txt=matdata2ubjson(mat,level,varargin)
if(isempty(mat))
txt='Z';
return;
end
type='';
hasnegtive=(mat<0);
if(isa(mat,'integer') || isinteger(mat) || (isfloat(mat) && all(mod(mat(:),1) == 0)))
if(isempty(hasnegtive))
if(max(mat(:))<=2^8)
type='U';
end
end
if(isempty(type))
% todo - need to consider negative ones separately
id= histc(abs(max(mat(:))),[0 2^7 2^15 2^31 2^63]);
if(isempty(id~=0))
error('high-precision data is not yet supported');
end
key='iIlL';
type=key(id~=0);
end
txt=[I_a(mat(:),type,size(mat))];
elseif(islogical(mat))
logicalval='FT';
if(numel(mat)==1)
txt=logicalval(mat+1);
else
txt=['[$U#' I_a(size(mat),'l') typecast(swapbytes(uint8(mat(:)')),'uint8')];
end
else
if(numel(mat)==1)
txt=['[' D_(mat) ']'];
else
txt=D_a(mat(:),'D',size(mat));
end
end
%txt=regexprep(mat2str(mat),'\s+',',');
%txt=regexprep(txt,';',sprintf('],['));
% if(nargin>=2 && size(mat,1)>1)
% txt=regexprep(txt,'\[',[repmat(sprintf('\t'),1,level) '[']);
% end
if(any(isinf(mat(:))))
txt=regexprep(txt,'([-+]*)Inf',jsonopt('Inf','"$1_Inf_"',varargin{:}));
end
if(any(isnan(mat(:))))
txt=regexprep(txt,'NaN',jsonopt('NaN','"_NaN_"',varargin{:}));
end
%%-------------------------------------------------------------------------
function newname=checkname(name,varargin)
isunpack=jsonopt('UnpackHex',1,varargin{:});
newname=name;
if(isempty(regexp(name,'0x([0-9a-fA-F]+)_','once')))
return
end
if(isunpack)
isoct=jsonopt('IsOctave',0,varargin{:});
if(~isoct)
newname=regexprep(name,'(^x|_){1}0x([0-9a-fA-F]+)_','${native2unicode(hex2dec($2))}');
else
pos=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','start');
pend=regexp(name,'(^x|_){1}0x([0-9a-fA-F]+)_','end');
if(isempty(pos))
return;
end
str0=name;
pos0=[0 pend(:)' length(name)];
newname='';
for i=1:length(pos)
newname=[newname str0(pos0(i)+1:pos(i)-1) char(hex2dec(str0(pos(i)+3:pend(i)-1)))];
end
if(pos(end)~=length(name))
newname=[newname str0(pos0(end-1)+1:pos0(end))];
end
end
end
%%-------------------------------------------------------------------------
function val=N_(str)
val=[I_(int32(length(str))) str];
%%-------------------------------------------------------------------------
function val=S_(str)
if(length(str)==1)
val=['C' str];
else
val=['S' I_(int32(length(str))) str];
end
%%-------------------------------------------------------------------------
function val=I_(num)
if(~isinteger(num))
error('input is not an integer');
end
if(num>=0 && num<255)
val=['U' data2byte(swapbytes(cast(num,'uint8')),'uint8')];
return;
end
key='iIlL';
cid={'int8','int16','int32','int64'};
for i=1:4
if((num>0 && num<2^(i*8-1)) || (num<0 && num>=-2^(i*8-1)))
val=[key(i) data2byte(swapbytes(cast(num,cid{i})),'uint8')];
return;
end
end
error('unsupported integer');
%%-------------------------------------------------------------------------
function val=D_(num)
if(~isfloat(num))
error('input is not a float');
end
if(isa(num,'single'))
val=['d' data2byte(num,'uint8')];
else
val=['D' data2byte(num,'uint8')];
end
%%-------------------------------------------------------------------------
function data=I_a(num,type,dim,format)
id=find(ismember('iUIlL',type));
if(id==0)
error('unsupported integer array');
end
% based on UBJSON specs, all integer types are stored in big endian format
if(id==1)
data=data2byte(swapbytes(int8(num)),'uint8');
blen=1;
elseif(id==2)
data=data2byte(swapbytes(uint8(num)),'uint8');
blen=1;
elseif(id==3)
data=data2byte(swapbytes(int16(num)),'uint8');
blen=2;
elseif(id==4)
data=data2byte(swapbytes(int32(num)),'uint8');
blen=4;
elseif(id==5)
data=data2byte(swapbytes(int64(num)),'uint8');
blen=8;
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/blen)) data(:)'];
end
data=['[' data(:)'];
else
data=reshape(data,blen,numel(data)/blen);
data(2:blen+1,:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function data=D_a(num,type,dim,format)
id=find(ismember('dD',type));
if(id==0)
error('unsupported float array');
end
if(id==1)
data=data2byte(single(num),'uint8');
elseif(id==2)
data=data2byte(double(num),'uint8');
end
if(nargin>=3 && length(dim)>=2 && prod(dim)~=dim(2))
format='opt';
end
if((nargin<4 || strcmp(format,'opt')) && numel(num)>1)
if(nargin>=3 && (length(dim)==1 || (length(dim)>=2 && prod(dim)~=dim(2))))
cid=I_(uint32(max(dim)));
data=['$' type '#' I_a(dim,cid(1)) data(:)'];
else
data=['$' type '#' I_(int32(numel(data)/(id*4))) data(:)'];
end
data=['[' data];
else
data=reshape(data,(id*4),length(data)/(id*4));
data(2:(id*4+1),:)=data;
data(1,:)=type;
data=data(:)';
data=['[' data(:)' ']'];
end
%%-------------------------------------------------------------------------
function bytes=data2byte(varargin)
bytes=typecast(varargin{:});
bytes=bytes(:)';
|
github | lhmRyan/dual-purpose-hashing-DPH-master | classification_demo.m | .m | dual-purpose-hashing-DPH-master/matlab/demo/classification_demo.m | 5,466 | utf_8 | 45745fb7cfe37ef723c307dfa06f1b97 | function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github | yuqingtong1990/webrtc_vs2015-master | apmtest.m | .m | webrtc_vs2015-master/webrtc/modules/audio_processing/test/apmtest.m | 9,470 | utf_8 | ad72111888b4bb4b7c4605d0bf79d572 | function apmtest(task, testname, filepath, casenumber, legacy)
%APMTEST is a tool to process APM file sets and easily display the output.
% APMTEST(TASK, TESTNAME, CASENUMBER) performs one of several TASKs:
% 'test' Processes the files to produce test output.
% 'list' Prints a list of cases in the test set, preceded by their
% CASENUMBERs.
% 'show' Uses spclab to show the test case specified by the
% CASENUMBER parameter.
%
% using a set of test files determined by TESTNAME:
% 'all' All tests.
% 'apm' The standard APM test set (default).
% 'apmm' The mobile APM test set.
% 'aec' The AEC test set.
% 'aecm' The AECM test set.
% 'agc' The AGC test set.
% 'ns' The NS test set.
% 'vad' The VAD test set.
%
% FILEPATH specifies the path to the test data files.
%
% CASENUMBER can be used to select a single test case. Omit CASENUMBER,
% or set to zero, to use all test cases.
%
if nargin < 5 || isempty(legacy)
% Set to true to run old VQE recordings.
legacy = false;
end
if nargin < 4 || isempty(casenumber)
casenumber = 0;
end
if nargin < 3 || isempty(filepath)
filepath = 'data/';
end
if nargin < 2 || isempty(testname)
testname = 'all';
end
if nargin < 1 || isempty(task)
task = 'test';
end
if ~strcmp(task, 'test') && ~strcmp(task, 'list') && ~strcmp(task, 'show')
error(['TASK ' task ' is not recognized']);
end
if casenumber == 0 && strcmp(task, 'show')
error(['CASENUMBER must be specified for TASK ' task]);
end
inpath = [filepath 'input/'];
outpath = [filepath 'output/'];
refpath = [filepath 'reference/'];
if strcmp(testname, 'all')
tests = {'apm','apmm','aec','aecm','agc','ns','vad'};
else
tests = {testname};
end
if legacy
progname = './test';
else
progname = './process_test';
end
global farFile;
global nearFile;
global eventFile;
global delayFile;
global driftFile;
if legacy
farFile = 'vqeFar.pcm';
nearFile = 'vqeNear.pcm';
eventFile = 'vqeEvent.dat';
delayFile = 'vqeBuf.dat';
driftFile = 'vqeDrift.dat';
else
farFile = 'apm_far.pcm';
nearFile = 'apm_near.pcm';
eventFile = 'apm_event.dat';
delayFile = 'apm_delay.dat';
driftFile = 'apm_drift.dat';
end
simulateMode = false;
nErr = 0;
nCases = 0;
for i=1:length(tests)
simulateMode = false;
if strcmp(tests{i}, 'apm')
testdir = ['apm/'];
outfile = ['out'];
if legacy
opt = ['-ec 1 -agc 2 -nc 2 -vad 3'];
else
opt = ['--no_progress -hpf' ...
' -aec --drift_compensation -agc --fixed_digital' ...
' -ns --ns_moderate -vad'];
end
elseif strcmp(tests{i}, 'apm-swb')
simulateMode = true;
testdir = ['apm-swb/'];
outfile = ['out'];
if legacy
opt = ['-fs 32000 -ec 1 -agc 2 -nc 2'];
else
opt = ['--no_progress -fs 32000 -hpf' ...
' -aec --drift_compensation -agc --adaptive_digital' ...
' -ns --ns_moderate -vad'];
end
elseif strcmp(tests{i}, 'apmm')
testdir = ['apmm/'];
outfile = ['out'];
opt = ['-aec --drift_compensation -agc --fixed_digital -hpf -ns ' ...
'--ns_moderate'];
else
error(['TESTNAME ' tests{i} ' is not recognized']);
end
inpathtest = [inpath testdir];
outpathtest = [outpath testdir];
refpathtest = [refpath testdir];
if ~exist(inpathtest,'dir')
error(['Input directory ' inpathtest ' does not exist']);
end
if ~exist(refpathtest,'dir')
warning(['Reference directory ' refpathtest ' does not exist']);
end
[status, errMsg] = mkdir(outpathtest);
if (status == 0)
error(errMsg);
end
[nErr, nCases] = recurseDir(inpathtest, outpathtest, refpathtest, outfile, ...
progname, opt, simulateMode, nErr, nCases, task, casenumber, legacy);
if strcmp(task, 'test') || strcmp(task, 'show')
system(['rm ' farFile]);
system(['rm ' nearFile]);
if simulateMode == false
system(['rm ' eventFile]);
system(['rm ' delayFile]);
system(['rm ' driftFile]);
end
end
end
if ~strcmp(task, 'list')
if nErr == 0
fprintf(1, '\nAll files are bit-exact to reference\n', nErr);
else
fprintf(1, '\n%d files are NOT bit-exact to reference\n', nErr);
end
end
function [nErrOut, nCases] = recurseDir(inpath, outpath, refpath, ...
outfile, progname, opt, simulateMode, nErr, nCases, task, casenumber, ...
legacy)
global farFile;
global nearFile;
global eventFile;
global delayFile;
global driftFile;
dirs = dir(inpath);
nDirs = 0;
nErrOut = nErr;
for i=3:length(dirs) % skip . and ..
nDirs = nDirs + dirs(i).isdir;
end
if nDirs == 0
nCases = nCases + 1;
if casenumber == nCases || casenumber == 0
if strcmp(task, 'list')
fprintf([num2str(nCases) '. ' outfile '\n'])
else
vadoutfile = ['vad_' outfile '.dat'];
outfile = [outfile '.pcm'];
% Check for VAD test
vadTest = 0;
if ~isempty(findstr(opt, '-vad'))
vadTest = 1;
if legacy
opt = [opt ' ' outpath vadoutfile];
else
opt = [opt ' --vad_out_file ' outpath vadoutfile];
end
end
if exist([inpath 'vqeFar.pcm'])
system(['ln -s -f ' inpath 'vqeFar.pcm ' farFile]);
elseif exist([inpath 'apm_far.pcm'])
system(['ln -s -f ' inpath 'apm_far.pcm ' farFile]);
end
if exist([inpath 'vqeNear.pcm'])
system(['ln -s -f ' inpath 'vqeNear.pcm ' nearFile]);
elseif exist([inpath 'apm_near.pcm'])
system(['ln -s -f ' inpath 'apm_near.pcm ' nearFile]);
end
if exist([inpath 'vqeEvent.dat'])
system(['ln -s -f ' inpath 'vqeEvent.dat ' eventFile]);
elseif exist([inpath 'apm_event.dat'])
system(['ln -s -f ' inpath 'apm_event.dat ' eventFile]);
end
if exist([inpath 'vqeBuf.dat'])
system(['ln -s -f ' inpath 'vqeBuf.dat ' delayFile]);
elseif exist([inpath 'apm_delay.dat'])
system(['ln -s -f ' inpath 'apm_delay.dat ' delayFile]);
end
if exist([inpath 'vqeSkew.dat'])
system(['ln -s -f ' inpath 'vqeSkew.dat ' driftFile]);
elseif exist([inpath 'vqeDrift.dat'])
system(['ln -s -f ' inpath 'vqeDrift.dat ' driftFile]);
elseif exist([inpath 'apm_drift.dat'])
system(['ln -s -f ' inpath 'apm_drift.dat ' driftFile]);
end
if simulateMode == false
command = [progname ' -o ' outpath outfile ' ' opt];
else
if legacy
inputCmd = [' -in ' nearFile];
else
inputCmd = [' -i ' nearFile];
end
if exist([farFile])
if legacy
inputCmd = [' -if ' farFile inputCmd];
else
inputCmd = [' -ir ' farFile inputCmd];
end
end
command = [progname inputCmd ' -o ' outpath outfile ' ' opt];
end
% This prevents MATLAB from using its own C libraries.
shellcmd = ['bash -c "unset LD_LIBRARY_PATH;'];
fprintf([command '\n']);
[status, result] = system([shellcmd command '"']);
fprintf(result);
fprintf(['Reference file: ' refpath outfile '\n']);
if vadTest == 1
equal_to_ref = are_files_equal([outpath vadoutfile], ...
[refpath vadoutfile], ...
'int8');
if ~equal_to_ref
nErr = nErr + 1;
end
end
[equal_to_ref, diffvector] = are_files_equal([outpath outfile], ...
[refpath outfile], ...
'int16');
if ~equal_to_ref
nErr = nErr + 1;
end
if strcmp(task, 'show')
% Assume the last init gives the sample rate of interest.
str_idx = strfind(result, 'Sample rate:');
fs = str2num(result(str_idx(end) + 13:str_idx(end) + 17));
fprintf('Using %d Hz\n', fs);
if exist([farFile])
spclab(fs, farFile, nearFile, [refpath outfile], ...
[outpath outfile], diffvector);
%spclab(fs, diffvector);
else
spclab(fs, nearFile, [refpath outfile], [outpath outfile], ...
diffvector);
%spclab(fs, diffvector);
end
end
end
end
else
for i=3:length(dirs)
if dirs(i).isdir
[nErr, nCases] = recurseDir([inpath dirs(i).name '/'], outpath, ...
refpath,[outfile '_' dirs(i).name], progname, opt, ...
simulateMode, nErr, nCases, task, casenumber, legacy);
end
end
end
nErrOut = nErr;
function [are_equal, diffvector] = ...
are_files_equal(newfile, reffile, precision, diffvector)
are_equal = false;
diffvector = 0;
if ~exist(newfile,'file')
warning(['Output file ' newfile ' does not exist']);
return
end
if ~exist(reffile,'file')
warning(['Reference file ' reffile ' does not exist']);
return
end
fid = fopen(newfile,'rb');
new = fread(fid,inf,precision);
fclose(fid);
fid = fopen(reffile,'rb');
ref = fread(fid,inf,precision);
fclose(fid);
if length(new) ~= length(ref)
warning('Reference is not the same length as output');
minlength = min(length(new), length(ref));
new = new(1:minlength);
ref = ref(1:minlength);
end
diffvector = new - ref;
if isequal(new, ref)
fprintf([newfile ' is bit-exact to reference\n']);
are_equal = true;
else
if isempty(new)
warning([newfile ' is empty']);
return
end
snr = snrseg(new,ref,80);
fprintf('\n');
are_equal = false;
end
|
github | yuqingtong1990/webrtc_vs2015-master | plot_neteq_delay.m | .m | webrtc_vs2015-master/webrtc/modules/audio_coding/neteq/test/delay_tool/plot_neteq_delay.m | 5,563 | utf_8 | 8b6a66813477863da513b1e6971dbc97 | function [delay_struct, delayvalues] = plot_neteq_delay(delayfile, varargin)
% InfoStruct = plot_neteq_delay(delayfile)
% InfoStruct = plot_neteq_delay(delayfile, 'skipdelay', skip_seconds)
%
% Henrik Lundin, 2006-11-17
% Henrik Lundin, 2011-05-17
%
try
s = parse_delay_file(delayfile);
catch
error(lasterr);
end
delayskip=0;
noplot=0;
arg_ptr=1;
delaypoints=[];
s.sn=unwrap_seqno(s.sn);
while arg_ptr+1 <= nargin
switch lower(varargin{arg_ptr})
case {'skipdelay', 'delayskip'}
% skip a number of seconds in the beginning when calculating delays
delayskip = varargin{arg_ptr+1};
arg_ptr = arg_ptr + 2;
case 'noplot'
noplot=1;
arg_ptr = arg_ptr + 1;
case {'get_delay', 'getdelay'}
% return a vector of delay values for the points in the given vector
delaypoints = varargin{arg_ptr+1};
arg_ptr = arg_ptr + 2;
otherwise
warning('Unknown switch %s\n', varargin{arg_ptr});
arg_ptr = arg_ptr + 1;
end
end
% find lost frames that were covered by one-descriptor decoding
one_desc_ix=find(isnan(s.arrival));
for k=1:length(one_desc_ix)
ix=find(s.ts==max(s.ts(s.ts(one_desc_ix(k))>s.ts)));
s.sn(one_desc_ix(k))=s.sn(ix)+1;
s.pt(one_desc_ix(k))=s.pt(ix);
s.arrival(one_desc_ix(k))=s.arrival(ix)+s.decode(one_desc_ix(k))-s.decode(ix);
end
% remove duplicate received frames that were never decoded (RED codec)
if length(unique(s.ts(isfinite(s.ts)))) < length(s.ts(isfinite(s.ts)))
ix=find(isfinite(s.decode));
s.sn=s.sn(ix);
s.ts=s.ts(ix);
s.arrival=s.arrival(ix);
s.playout_delay=s.playout_delay(ix);
s.pt=s.pt(ix);
s.optbuf=s.optbuf(ix);
plen=plen(ix);
s.decode=s.decode(ix);
end
% find non-unique sequence numbers
[~,un_ix]=unique(s.sn);
nonun_ix=setdiff(1:length(s.sn),un_ix);
if ~isempty(nonun_ix)
warning('RTP sequence numbers are in error');
end
% sort vectors
[s.sn,sort_ix]=sort(s.sn);
s.ts=s.ts(sort_ix);
s.arrival=s.arrival(sort_ix);
s.decode=s.decode(sort_ix);
s.playout_delay=s.playout_delay(sort_ix);
s.pt=s.pt(sort_ix);
send_t=s.ts-s.ts(1);
if length(s.fs)<1
warning('No info about sample rate found in file. Using default 8000.');
s.fs(1)=8000;
s.fschange_ts(1)=min(s.ts);
elseif s.fschange_ts(1)>min(s.ts)
s.fschange_ts(1)=min(s.ts);
end
end_ix=length(send_t);
for k=length(s.fs):-1:1
start_ix=find(s.ts==s.fschange_ts(k));
send_t(start_ix:end_ix)=send_t(start_ix:end_ix)/s.fs(k)*1000;
s.playout_delay(start_ix:end_ix)=s.playout_delay(start_ix:end_ix)/s.fs(k)*1000;
s.optbuf(start_ix:end_ix)=s.optbuf(start_ix:end_ix)/s.fs(k)*1000;
end_ix=start_ix-1;
end
tot_time=max(send_t)-min(send_t);
seq_ix=s.sn-min(s.sn)+1;
send_t=send_t+max(min(s.arrival-send_t),0);
plot_send_t=nan*ones(max(seq_ix),1);
plot_send_t(seq_ix)=send_t;
plot_nw_delay=nan*ones(max(seq_ix),1);
plot_nw_delay(seq_ix)=s.arrival-send_t;
cng_ix=find(s.pt~=13); % find those packets that are not CNG/SID
if noplot==0
h=plot(plot_send_t/1000,plot_nw_delay);
set(h,'color',0.75*[1 1 1]);
hold on
if any(s.optbuf~=0)
peak_ix=find(s.optbuf(cng_ix)<0); % peak mode is labeled with negative values
no_peak_ix=find(s.optbuf(cng_ix)>0); %setdiff(1:length(cng_ix),peak_ix);
h1=plot(send_t(cng_ix(peak_ix))/1000,...
s.arrival(cng_ix(peak_ix))+abs(s.optbuf(cng_ix(peak_ix)))-send_t(cng_ix(peak_ix)),...
'r.');
h2=plot(send_t(cng_ix(no_peak_ix))/1000,...
s.arrival(cng_ix(no_peak_ix))+abs(s.optbuf(cng_ix(no_peak_ix)))-send_t(cng_ix(no_peak_ix)),...
'g.');
set([h1, h2],'markersize',1)
end
%h=plot(send_t(seq_ix)/1000,s.decode+s.playout_delay-send_t(seq_ix));
h=plot(send_t(cng_ix)/1000,s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix));
set(h,'linew',1.5);
hold off
ax1=axis;
axis tight
ax2=axis;
axis([ax2(1:3) ax1(4)])
end
% calculate delays and other parameters
delayskip_ix = find(send_t-send_t(1)>=delayskip*1000, 1 );
use_ix = intersect(cng_ix,... % use those that are not CNG/SID frames...
intersect(find(isfinite(s.decode)),... % ... that did arrive ...
(delayskip_ix:length(s.decode))')); % ... and are sent after delayskip seconds
mean_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-send_t(use_ix));
neteq_delay = mean(s.decode(use_ix)+s.playout_delay(use_ix)-s.arrival(use_ix));
Npack=max(s.sn(delayskip_ix:end))-min(s.sn(delayskip_ix:end))+1;
nw_lossrate=(Npack-length(s.sn(delayskip_ix:end)))/Npack;
neteq_lossrate=(length(s.sn(delayskip_ix:end))-length(use_ix))/Npack;
delay_struct=struct('mean_delay',mean_delay,'neteq_delay',neteq_delay,...
'nw_lossrate',nw_lossrate,'neteq_lossrate',neteq_lossrate,...
'tot_expand',round(s.tot_expand),'tot_accelerate',round(s.tot_accelerate),...
'tot_preemptive',round(s.tot_preemptive),'tot_time',tot_time,...
'filename',delayfile,'units','ms','fs',unique(s.fs));
if not(isempty(delaypoints))
delayvalues=interp1(send_t(cng_ix),...
s.decode(cng_ix)+s.playout_delay(cng_ix)-send_t(cng_ix),...
delaypoints,'nearest',NaN);
else
delayvalues=[];
end
% SUBFUNCTIONS %
function y=unwrap_seqno(x)
jumps=find(abs((diff(x)-1))>65000);
while ~isempty(jumps)
n=jumps(1);
if x(n+1)-x(n) < 0
% negative jump
x(n+1:end)=x(n+1:end)+65536;
else
% positive jump
x(n+1:end)=x(n+1:end)-65536;
end
jumps=find(abs((diff(x(n+1:end))-1))>65000);
end
y=x;
return;
|
github | kalov/ShapePFCN-master | classification_demo.m | .m | ShapePFCN-master/caffe-ours/matlab/demo/classification_demo.m | 5,412 | utf_8 | 8f46deabe6cde287c4759f3bc8b7f819 | function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to you Matlab search PATH to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github | usgs/landslides-mLS-master | mLS.m | .m | landslides-mLS-master/mLS.m | 7,878 | utf_8 | 5fc99d5ed047ae1cd3d70caf7f13cc6c | % This script is provided as a supplementary material of a paper
% published in Earth Surface Processes and Landforms. The details of the
% method followed in the given script is described in the corresponding
% paper. If you publish use this script or a its modified version please
% cite the following paper:
% Tanyas, H., K.E. Allstadt, and C.J. van Westen, 2018,
% An updated method for estimating landslide-event magnitude, Earth Surface
% Processes and Landforms. DOI: 10.1002/esp.4359
% The Pupose Of The Script And The Input Parametes
% This script is provided for the accurate estimation of landslide-event
% magnitude. We used Matlab R2015b to test the given script. It basically
% requires three input parameters to estimate landslide-event magnitude:
% cutoff smallest area that follows power law)and beta (power-law exponent)
% values of frequency-size distribution (FAD) of landslides, and a horizontal
% array (Area) with landslide sizes. This script can also calculate the
% uncertainty in landslide-event magnitude if uncertainties in cutoff and
% beta values are given as input parameters.
% The power-law distribution can be captured in both cumulative and
% non-cumulative FADs, and the power-law exponent (beta) for a non-cumulative
% FAD can be transferred to its cumulative equivalent, alpha, using the relation
% alpha=beta-1 (Guzzetti et al., 2002). In this code, the calculations are carried
% out on the non-cumulative FAD.
% The cutoff is the landslide size where frequency-size distribution curve
% diverges form the power-law. In this code its unit is meter square.
% Beta value resfers to the slope of the frequency-size distribution. It also
% called as power-law exponent (scaling parameter, beta). For most landslide
% inventories, non-cumulative power-law exponents occur in the range of
% 1.4–3.4, with a central tendency of 2.3–2.5 (Stark and Guzzetti, 2009;
% Van Den Eeckhaut et al., 2007).
% The unit of landslide sizes are in meter square.
% To obtain the cutoff & beta values and thier uncertainties the method
% suggested by Clauset et al.(2009) can be used. The original scripts
% (plfit.m and plvar.m) of Clauset et al. (2009) can be downloaded from the
% following link to calculate these parameters:
% http://www.santafe.edu/~aaronc/powerlaws/
% The Output Of The Script
% When you run the mLS function, for the given sample data, the corresponding
% mLS (landslide-event magnitude) will be obtained. If the uncertainties in
% cutoff (cutoff_error) and beta (beta_error) values are provided, the
% uncertainty in mLS (error) is also estimated by the script. As an output
% of this code, a plot showing the frequency-area distribution of the given
% landslides and the corresponding power-law fit are also obtained.
% mLS does not have any unit.
function [mLS,error]=mLS(Area,cutoff,beta,beta_error,cutoff_error)
% In the following lines, the bins are defined with an array. We took 2 as
% the minimum bin size and we used increasing bin sizes. We increase the
% bin widths while the landslide size increases, so that bin widths become
% approximately equal in logarithmic coordinates. To create a long array for
% the bins we tentatively pick 120 for the size of x1 vector defined below.
x1(1,1)=2;
for i=2:120
x1(1,i)=x1(1,i-1)*1.2;
end
x2=log10(x1);
Freq=histc(Area,x1); %Frequency values are calculated for each bin
s=size(x1);
s=s(1,2);
internal=zeros(1,s);
for i=2:s
internal(1,i)=x1(1,i)-x1(1,i-1);
end
internal(1,1)=min(x1);
FD=Freq./internal;
x1_rev = abs(x1-cutoff); % the index of value that is closest to cutoff value is identified along the x1 array
[indexMidpoint indexMidpoint] = min(x1_rev);
x=x1(indexMidpoint:end); % the x (size bines) array for the frequeny-size distribution is defined
y=FD(indexMidpoint:end); % the y (frequency densities) array for the frequeny-size distribution is defined
if beta>0 % beta value have to be negative
beta=-1*beta;
end
beta_stored=beta;
constant=y(1,1)/cutoff^beta; % The c constant is calculated along the power-low where x=cutoff
fit_y=constant*x1.^beta; % Frequency-density values calculated for the defined power-law fit
fit_y_stored=fit_y;
midx=10^((log10(max(Area))+(log10(cutoff)))/2); % The x and y values at mid-point location is read along the power-law fit
midy=constant*midx^beta;
Refmidx=4.876599623713225e+04; % X value for the mid point of the Northridge (reference point) inventory
Refmidy=8.364725347860417e-04; % Y value for the mid point of the Northridge (reference point) inventory
ac=Refmidy/(11111*Refmidx^beta); % the c' constant (as) is calculated here for the mid-point of
% the Northridge inventory as a reference point where mLS=log(11111)
mLS=log10((midy/(ac*midx^(beta)))); % mLS is calculated in this line
mLS_stored=mLS;
% Uncertainty in mLS will be calculated if the required inputs are given
% To do that Monte-Carlo simulation is run 10,000 times
if exist('beta_error')==1 && exist('cutoff_error')==1
beta_interval_N=((beta+beta_error)-(beta-beta_error))/(499); %Number of elements to create an array including 500 uniformly distributed beta values is defined
beta_interval=(beta-beta_error):beta_interval_N:(beta+beta_error); %An array including 500 uniformly distributed beta values is defined
cutoff_min=(cutoff-cutoff_error);
if cutoff_min<=0
cutoff_min=2;
else
cutoff_min=cutoff_min;
end
cutoff_max=(cutoff+cutoff_error);
cutoff_interval_N=((cutoff_max)-(cutoff_min))/(499); %Number of elements to create an array including 500 uniformly distributed cutoff values is defined
cutoff_interval=(cutoff_min):cutoff_interval_N:(cutoff_max); %An array including 500 uniformly distributed cutoff values is defined
beta_mean=mean(beta_interval); %Mean of beta values is identified
beta_std=std(beta_interval); %Standard deviation of beta vaues is identified
cutoff_mean=mean(cutoff_interval); %Mean of cutoff values is identified
cutoff_std=std(cutoff_interval); %Standard deviation of cutoff values is identified
for i=1:10000 %mLS values are calculated for randomly sampled beta and cutoff values below
cutoff=normrnd(cutoff_mean,cutoff_std);
beta=normrnd(beta_mean,beta_std);
constant=y(1,1)/cutoff^beta;
fit_y=constant*x1.^beta;
midx=10^((log10(max(Area))+(log10(cutoff)))/2);
ac=Refmidy/(11111*Refmidx^beta);
mLS_array(i,1)=log10((midy/(ac*midx^(beta))));
end
mLS_array=mLS_array(all(~isinf(mLS_array),2),:); % "Inf" cells are removed from the array
error=std(mLS_array(:)); %Uncertainty of mLS calcultated as a first standard deviation of mLS values
else
disp('Uncertainty in mLS will not be calculated because the variable "cutoff_error" and "beta_error" is missing')
error='?'
end
% A graph showing the frequency-area distribution of the given landslides
% and the corresponding power-law fit are plotted.
loglog(x1,fit_y_stored,'-','LineWidth',2,'Color','r');hold on
loglog(x1,FD,'ok','MarkerSize',8,'MarkerFaceColor','b','MarkerEdgeColor','k')
axis([1 1.E+7 1.E-6 1000])
set(get(gca,'Xlabel'),'string','Landslide Area (m^2)','FontSize',12, 'FontUnits','points','FontWeight','normal')
set(get(gca,'Ylabel'),'string','Frequency Density (m^-^2)','FontSize',12, 'FontUnits','points','FontWeight','normal')
str={['\beta = ',num2str(beta_stored)];['mLS = ',num2str(mLS_stored),(char(177)),num2str(error)]};
text(x1(1,1),(min(FD(FD>0)*10)),str,'FontSize',12)
end
|
github | WenbingLv/NPC-radiomics-master | getGLCM_Symmetric.m | .m | NPC-radiomics-master/getGLCM_Symmetric.m | 5,813 | utf_8 | 5c7c1e015f2cfab250ac285142fb04c5 | function coocMat = getGLCM_Symmetric(varargin)
%inputStr = {TumorVolume,'Distance',[],'Direction',[],'numgray',levelsM+1};
%
%[email protected]
%Southern Medical University
%
%Default settings
coocMat= NaN;
distance = [1;2;4;8];
numLevels = 16;
offSet = [1 0 0; 1 1 0; 0 1 0; -1 1 0]; %2D Co-Occurrence directions 0,45,90,135 degrees
%the additional 9 directions of 3D volume
dimension3 = [0 0 1; 1 0 1; -1 0 1; 0,1,1; 0 -1 1; 1 1 1; -1 1 1; 1 1 -1; 1 1 -1];
offSet = cat(1,offSet,dimension3);%13 directions
%checking inputs
data = varargin{1};
temp = size(data);
if size(temp)<3
disp('Error: This program is designed for 3 dimensional data')
return;
end
numInput = size(varargin,2);
for inputs =2:numInput
temp = varargin{1,inputs};
if ~ischar(temp)
continue;
end
temp = upper(temp);
switch (temp)
case 'DIRECTION'
temp2 = int8(varargin{1,inputs+1});
if size(size(temp2),2) ~=2
disp('Error: Direction input is formatted poorly')
return;
end
if size(temp2,2) ~=3
disp(['Error: Incorrect number of columns in ' ...
'direction variable'])
return;
end
if max(max(temp2))>1 | min(min(temp2))<-1
disp('Error: Direction values can only be {-1,0,1}')
return;
end
offSet = temp2;
case 'DISTANCE'
temp2 = int8(varargin{1,inputs+1});
if size(size(temp2)) ~= 2
disp('Error: Incorrect formatting of distance variable')
return;
end
if sum(sum(size(temp2))) ~= max(size(temp2)+1)
disp(['Error: Distance variable is to be a one ' ...
'dimensional array'])
return;
end
distance = temp2;
case 'NUMGRAY'
temp2 = varargin{1,inputs+1};
if temp2<1
disp('The number of graylevels must be positive')
return;
end
numLevels = uint16(temp2);
end
end
noDirections = size(offSet,1); %number of directions, currently 13
coocMat = zeros(numLevels, numLevels, noDirections, size(distance,2));
for dist =1:size(distance,2) %distance
[coocMat(:,:,:,dist)] = graycooc3d(data(:,:,:),distance(dist),numLevels,offSet);
end
return
function [new_coMat]= graycooc3d(I,distance,numLevels,offSet)
%I = the 3D image matrix
%distance = a vector of the distances to analyze in
%numLevels = the number of graylevels to be used
%offSet = a matrix of the directions to analyze in
%coMat the Co-Occurrence matrices produced%%
%**************Variable initialization/Declaration**********************
%harMat =0;
noDirections = size(offSet,1); %number of directions, currently 13
coMat = zeros(numLevels,numLevels,noDirections);
%**************************Beginning analysis*************************
%Order of loops: Direction, slice, graylevel, graylevel locations
for direction =1:noDirections %currently 13 (for the 3d image)
tempMat = zeros(numLevels,numLevels,size(I,3));
for slicej =1:size(I,3)
for j=1:numLevels %graylevel
%find all the instances of that graylevel
[rowj,colj] = find(I(:,:,slicej)==j);
%populating the Cooc matrix.
for tempCount = 1:size(rowj,1)
rowT = rowj(tempCount) + distance*offSet(direction,1);
colT = colj(tempCount) + distance*offSet(direction,2);
sliceT = slicej + distance*offSet(direction,3);
rowTnegative = rowj(tempCount) - distance*offSet(direction,1);%the symmetry of GLCM.
colTnegative = colj(tempCount) - distance*offSet(direction,2);%the symmetry of GLCM.
sliceTnegative = slicej - distance*offSet(direction,3);%the symmetry of GLCM.
[I1, I2, I3] = size(I);
if rowT <= I1 && colT <= I2 && sliceT <= I3
if rowT > 0 && colT > 0 && sliceT > 0
%Error checking for NANs and Infinite numbers
IIntensity = I(rowT,colT,sliceT);
if ~isnan(IIntensity)
if ~isinf(IIntensity)
tempMat(j,IIntensity,slicej)= tempMat...
(j,IIntensity,slicej)+1;
end
end
end
end
if rowTnegative <= I1 && colTnegative <= I2 && sliceTnegative <= I3
if rowTnegative > 0 && colTnegative > 0 && sliceTnegative > 0
%Error checking for NANs and Infinite numbers
IIntensitynegative = I(rowTnegative,colTnegative,sliceTnegative);% added by
if ~isnan(IIntensitynegative)
if ~isinf(IIntensitynegative)
tempMat(j,IIntensitynegative,slicej)= tempMat...
(j,IIntensitynegative,slicej)+1;
end
end
end
end
end
end
end
for slicej =1:size(I,3)
coMat(:,:,direction)= coMat(:,:,direction)+tempMat(:,:,slicej);
end
end
new_coMat=coMat(:,:,:);
return
|
github | WenbingLv/NPC-radiomics-master | getGLCM_Asymmetric.m | .m | NPC-radiomics-master/getGLCM_Asymmetric.m | 5,891 | utf_8 | d600aef8916ea9dd698c1241d56050d9 | function coocMat = getGLCM_Asymmetric(varargin)
%inputStr = {TumorVolume,'Distance',[],'Direction',[],'numgray',levelsM+1};
%
%[email protected]
%Southern Medical University
%
%Default settings
coocMat= NaN;
distance = [1;2;4;8];
numLevels = 16;
offSet = [1 0 0; 1 1 0; 0 1 0; -1 1 0]; %2D Co-Occurrence directions 0,45,90,135 degrees
%the additional 9 directions of 3D volume
dimension3 = [0 0 1; 1 0 1; -1 0 1; 0,1,1; 0 -1 1; 1 1 1; -1 1 1; 1 1 -1; 1 1 -1];
offSet = cat(1,offSet,dimension3);%13 directions
%checking inputs
data = varargin{1};
temp = size(data);
if size(temp)<3
disp('Error: This program is designed for 3 dimensional data')
return;
end
numInput = size(varargin,2);
for inputs =2:numInput
temp = varargin{1,inputs};
if ~ischar(temp)
continue;
end
temp = upper(temp);
switch (temp)
case 'DIRECTION'
temp2 = int8(varargin{1,inputs+1});
if size(size(temp2),2) ~=2
disp('Error: Direction input is formatted poorly')
return;
end
if size(temp2,2) ~=3
disp(['Error: Incorrect number of columns in ' ...
'direction variable'])
return;
end
if max(max(temp2))>1 | min(min(temp2))<-1
disp('Error: Direction values can only be {-1,0,1}')
return;
end
offSet = temp2;
case 'DISTANCE'
temp2 = int8(varargin{1,inputs+1});
if size(size(temp2)) ~= 2
disp('Error: Incorrect formatting of distance variable')
return;
end
if sum(sum(size(temp2))) ~= max(size(temp2)+1)
disp(['Error: Distance variable is to be a one ' ...
'dimensional array'])
return;
end
distance = temp2;
case 'NUMGRAY'
temp2 = varargin{1,inputs+1};
if temp2<1
disp('The number of graylevels must be positive')
return;
end
numLevels = uint16(temp2);
end
end
noDirections = size(offSet,1); %number of directions, currently 13
coocMat = zeros(numLevels, numLevels, noDirections, size(distance,2));
for dist =1:size(distance,2) %distance
[coocMat(:,:,:,dist)] = graycooc3d(data(:,:,:),distance(dist),numLevels,offSet);
end
return
function [new_coMat]= graycooc3d(I,distance,numLevels,offSet)
%I = the 3D image matrix
%distance = a vector of the distances to analyze in
%numLevels = the number of graylevels to be used
%offSet = a matrix of the directions to analyze in
%coMat the Co-Occurrence matrices produced
%**************Variable initialization/Declaration**********************
noDirections = size(offSet,1); %number of directions, currently 13
coMat = zeros(numLevels,numLevels,noDirections);
%**************************Beginning analysis*************************
%Order of loops: Direction, slice, graylevel, graylevel locations
for direction =1:noDirections %currently 13 (for the 3d image)
tempMat = zeros(numLevels,numLevels,size(I,3));
for slicej =1:size(I,3)
for j=1:numLevels %graylevel
%find all the instances of that graylevel
[rowj,colj] = find(I(:,:,slicej)==j);
%populating the Cooc matrix.
for tempCount = 1:size(rowj,1)
rowT = rowj(tempCount) + distance*offSet(direction,1);
colT = colj(tempCount) + distance*offSet(direction,2);
sliceT = slicej + distance*offSet(direction,3);
rowTnegative = rowj(tempCount) - distance*offSet(direction,1);%the symmetry of GLCM.
colTnegative = colj(tempCount) - distance*offSet(direction,2);%the symmetry of GLCM.
sliceTnegative = slicej - distance*offSet(direction,3);%the symmetry of GLCM.
[I1, I2, I3] = size(I);
if rowT <= I1 && colT <= I2 && sliceT <= I3
if rowT > 0 && colT > 0 && sliceT > 0
%Error checking for NANs and Infinite numbers
IIntensity = I(rowT,colT,sliceT);
if ~isnan(IIntensity)
if ~isinf(IIntensity)
tempMat(j,IIntensity,slicej)= tempMat...
(j,IIntensity,slicej)+1;
end
end
end
end
% if rowTnegative <= I1 && colTnegative <= I2 && sliceTnegative <= I3
% if rowTnegative > 0 && colTnegative > 0 && sliceTnegative > 0
%
% %Error checking for NANs and Infinite numbers
%
% IIntensitynegative = I(rowTnegative,colTnegative,sliceTnegative);% added by
% if ~isnan(IIntensitynegative)
% if ~isinf(IIntensitynegative)
% %Matlab doesn't have a ++ operator.
% tempMat(j,IIntensitynegative,slicej)= tempMat...
% (j,IIntensitynegative,slicej)+1;
%
% end
% end
% end
% end
end
end
end
for slicej =1:size(I,3)
coMat(:,:,direction)= coMat(:,:,direction)+tempMat(:,:,slicej);
end
end
new_coMat=coMat(:,:,:);
return
|
github | WenbingLv/NPC-radiomics-master | computeBoundingBox.m | .m | NPC-radiomics-master/computeBoundingBox.m | 3,017 | utf_8 | 71c3aad5fb0ffd5ca96a185b0ee529e2 | function [boxBound] = computeBoundingBox(mask)
% -------------------------------------------------------------------------
% function [boxBound] = computeBoundingBox(mask)
% -------------------------------------------------------------------------
% DESCRIPTION:
% This function computes the smallest box containing the whole region of
% interest (ROI). It is adapted from the function compute_boundingbox.m
% of CERR <http://www.cerr.info/>.
% -------------------------------------------------------------------------
% INPUTS:
% - mask: 3D array, with 1's inside the ROI, and 0's outside the ROI.
% -------------------------------------------------------------------------
% OUTPUTS:
% - boxBound: Bounds of the smallest box containing the ROI.
% Format: [minRow, maxRow;
% minColumn, maxColumns;
% minSlice, maxSlice]
% -------------------------------------------------------------------------
% AUTHOR(S):
% - Martin Vallieres <[email protected]>
% - CERR development team <http://www.cerr.info/>
% -------------------------------------------------------------------------
% HISTORY:
% - Creation: May 2015
%--------------------------------------------------------------------------
% STATEMENT:
% This file is part of <https://github.com/mvallieres/radiomics/>,
% a package providing MATLAB programming tools for radiomics analysis.
% --> Copyright (C) 2015 Martin Vallieres
% --> Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team
%
% This package 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 package 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 package. If not, see <http://www.gnu.org/licenses/>.
% -------------------------------------------------------------------------
[iV,jV,kV] = find3d(mask);
boxBound(1,1) = min(iV);
boxBound(1,2) = max(iV);
boxBound(2,1) = min(jV);
boxBound(2,2) = max(jV);
boxBound(3,1) = min(kV);
boxBound(3,2) = max(kV);
end
% CERR UTILITY FUNCTIONS (can be found at: https://github.com/adityaapte/CERR)
function [iV,jV,kV] = find3d(mask3M)
indV = find(mask3M(:));
[iV,jV,kV] = fastind2sub(size(mask3M),indV);
iV = iV';
jV = jV';
kV = kV';
end
function varargout = fastind2sub(siz,ndx)
nout = max(nargout,1);
if length(siz)<=nout,
siz = [siz ones(1,nout-length(siz))];
else
siz = [siz(1:nout-1) prod(siz(nout:end))];
end
n = length(siz);
k = [1 cumprod(siz(1:end-1))];
ndx = ndx - 1;
for i = n:-1:1,
varargout{i} = floor(ndx/k(i)) + 1;
ndx = ndx - (varargout{i}-1) * k(i);
end
end |
github | PerfXLab/caffe_perfdnn-master | classification_demo.m | .m | caffe_perfdnn-master/matlab/demo/classification_demo.m | 5,466 | utf_8 | 45745fb7cfe37ef723c307dfa06f1b97 | function [scores, maxlabel] = classification_demo(im, use_gpu)
% [scores, maxlabel] = classification_demo(im, use_gpu)
%
% Image classification demo using BVLC CaffeNet.
%
% IMPORTANT: before you run this demo, you should download BVLC CaffeNet
% from Model Zoo (http://caffe.berkeleyvision.org/model_zoo.html)
%
% ****************************************************************************
% For detailed documentation and usage on Caffe's Matlab interface, please
% refer to the Caffe Interface Tutorial at
% http://caffe.berkeleyvision.org/tutorial/interfaces.html#matlab
% ****************************************************************************
%
% input
% im color image as uint8 HxWx3
% use_gpu 1 to use the GPU, 0 to use the CPU
%
% output
% scores 1000-dimensional ILSVRC score vector
% maxlabel the label of the highest score
%
% You may need to do the following before you start matlab:
% $ export LD_LIBRARY_PATH=/opt/intel/mkl/lib/intel64:/usr/local/cuda-5.5/lib64
% $ export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libstdc++.so.6
% Or the equivalent based on where things are installed on your system
% and what versions are installed.
%
% Usage:
% im = imread('../../examples/images/cat.jpg');
% scores = classification_demo(im, 1);
% [score, class] = max(scores);
% Five things to be aware of:
% caffe uses row-major order
% matlab uses column-major order
% caffe uses BGR color channel order
% matlab uses RGB color channel order
% images need to have the data mean subtracted
% Data coming in from matlab needs to be in the order
% [width, height, channels, images]
% where width is the fastest dimension.
% Here is the rough matlab code for putting image data into the correct
% format in W x H x C with BGR channels:
% % permute channels from RGB to BGR
% im_data = im(:, :, [3, 2, 1]);
% % flip width and height to make width the fastest dimension
% im_data = permute(im_data, [2, 1, 3]);
% % convert from uint8 to single
% im_data = single(im_data);
% % reshape to a fixed size (e.g., 227x227).
% im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear');
% % subtract mean_data (already in W x H x C with BGR channels)
% im_data = im_data - mean_data;
% If you have multiple images, cat them with cat(4, ...)
% Add caffe/matlab to your Matlab search PATH in order to use matcaffe
if exist('../+caffe', 'dir')
addpath('..');
else
error('Please run this demo from caffe/matlab/demo');
end
% Set caffe mode
if exist('use_gpu', 'var') && use_gpu
caffe.set_mode_gpu();
gpu_id = 0; % we will use the first gpu in this demo
caffe.set_device(gpu_id);
else
caffe.set_mode_cpu();
end
% Initialize the network using BVLC CaffeNet for image classification
% Weights (parameter) file needs to be downloaded from Model Zoo.
model_dir = '../../models/bvlc_reference_caffenet/';
net_model = [model_dir 'deploy.prototxt'];
net_weights = [model_dir 'bvlc_reference_caffenet.caffemodel'];
phase = 'test'; % run with phase test (so that dropout isn't applied)
if ~exist(net_weights, 'file')
error('Please download CaffeNet from Model Zoo before you run this demo');
end
% Initialize a network
net = caffe.Net(net_model, net_weights, phase);
if nargin < 1
% For demo purposes we will use the cat image
fprintf('using caffe/examples/images/cat.jpg as input image\n');
im = imread('../../examples/images/cat.jpg');
end
% prepare oversampled input
% input_data is Height x Width x Channel x Num
tic;
input_data = {prepare_image(im)};
toc;
% do forward pass to get scores
% scores are now Channels x Num, where Channels == 1000
tic;
% The net forward function. It takes in a cell array of N-D arrays
% (where N == 4 here) containing data of input blob(s) and outputs a cell
% array containing data from output blob(s)
scores = net.forward(input_data);
toc;
scores = scores{1};
scores = mean(scores, 2); % take average scores over 10 crops
[~, maxlabel] = max(scores);
% call caffe.reset_all() to reset caffe
caffe.reset_all();
% ------------------------------------------------------------------------
function crops_data = prepare_image(im)
% ------------------------------------------------------------------------
% caffe/matlab/+caffe/imagenet/ilsvrc_2012_mean.mat contains mean_data that
% is already in W x H x C with BGR channels
d = load('../+caffe/imagenet/ilsvrc_2012_mean.mat');
mean_data = d.mean_data;
IMAGE_DIM = 256;
CROPPED_DIM = 227;
% Convert an image returned by Matlab's imread to im_data in caffe's data
% format: W x H x C with BGR channels
im_data = im(:, :, [3, 2, 1]); % permute channels from RGB to BGR
im_data = permute(im_data, [2, 1, 3]); % flip width and height
im_data = single(im_data); % convert from uint8 to single
im_data = imresize(im_data, [IMAGE_DIM IMAGE_DIM], 'bilinear'); % resize im_data
im_data = im_data - mean_data; % subtract mean_data (already in W x H x C, BGR)
% oversample (4 corners, center, and their x-axis flips)
crops_data = zeros(CROPPED_DIM, CROPPED_DIM, 3, 10, 'single');
indices = [0 IMAGE_DIM-CROPPED_DIM] + 1;
n = 1;
for i = indices
for j = indices
crops_data(:, :, :, n) = im_data(i:i+CROPPED_DIM-1, j:j+CROPPED_DIM-1, :);
crops_data(:, :, :, n+5) = crops_data(end:-1:1, :, :, n);
n = n + 1;
end
end
center = floor(indices(2) / 2) + 1;
crops_data(:,:,:,5) = ...
im_data(center:center+CROPPED_DIM-1,center:center+CROPPED_DIM-1,:);
crops_data(:,:,:,10) = crops_data(end:-1:1, :, :, 5);
|
github | BrainardLab/TeachingCode-master | initialiseProcedure.m | .m | TeachingCode-master/ArduinoAnomaloscope/xxxContributed/arduinoHFP/initialiseProcedure.m | 1,144 | utf_8 | 86882fe4db83c69d7a985d7d13165b79 |
function [increaseKey, decreaseKey, deltaKey, finishKey, ...
increaseInputs, decreaseInputs, deltaIndex, rDeltas]=initialiseProcedure
increaseKey=KbName('up'); % key code for increasing red intensity
decreaseKey=KbName('down'); % key code for decreaseing red intensity
deltaKey=KbName('space'); % key code for changing red delta
finishKey=KbName('q'); % key code for finishing procedure and recording data
% THIS IS IMPORTANT: increase/decrease inputs are the messages telling Arduino
% how to change red intensity. increaseInput{i} and decreaseInput{i} have
% the same absolute value, but opposite sign (e.g., increaseInput{1}=20,
% decreaseInput{1}=-20. so that a single index can change the delta of
% both. in the current arduino code, 'q'/'r' change the intensity by 20
% bytes (0-255), 'w'/'t' by 5, 'e', 'y' by 1. To change how much each
% affects the code, you need to change the arduino FlickeringLight code.
% (by changing the if statements for each input signal)
increaseInputs={'q', 'w', 'e'};
decreaseInputs={'r', 't', 'y'};
deltaIndex=1;
rDeltas=[20, 5, 1];
end |
github | BrainardLab/TeachingCode-master | ArduinoMethodOfAdjustmentHFP.m | .m | TeachingCode-master/ArduinoAnomaloscope/xxxContributed/arduinoHFP/ArduinoMethodOfAdjustmentHFP.m | 3,327 | utf_8 | 2afbe378afee5e39e4b9675765af3179 |
% if the code doesn't work, check that the arduino port (written in
% ConstantsHFP) is the right one (for windows, check Device Manager->ports)
function ArduinoImplementedHFP
% clear everything before starting program
delete(instrfindall)
clear
addpath('C:\Users\mediaworld\Documents\MATLAB\internship\HFP_Code\HFP_Code');
% call arduino object
serialObj=serialport(ConstantsHFP.serialPort, 9600);
% create variables
[increaseKey, decreaseKey, deltaKey,...
finishKey, ...
increaseInputs, decreaseInputs, ...
deltaIndex, rDeltas]=initialiseProcedure;
% adjust flicker settings
while true
fopen(serialObj);
ListenChar(0)
DoYouWantToStart=input('would you like to run a new trial? (yes or no) ', 's');
if strcmp(DoYouWantToStart, 'yes')==0
disp('aborting mission')
break;
end
ListenChar(2)
% setup random initial flicker setting ('s' is the message, in the
% FlickeringLight.ino code that stands for randomised start)
fprintf(serialObj, 's');
% Record red and green initial values for final save
rInit=read(serialObj, 6, "char");
gInit=read(serialObj, 6, "char");
pause(2)
disp('starting new trial');
% run trial
while true
% get keyboard input
[secs, keyCode, deltaSecs]=KbPressWait();
if keyCode(increaseKey)
% if user asks to increase light, select increase amount
% corresponding to current delta. See initialiseProcedure.m for more info
arduinoInput=increaseInputs{deltaIndex};
fprintf(serialObj, arduinoInput);
elseif keyCode(decreaseKey)
% decrease intensity. for more info look at
% initialiseProcedure.m
arduinoInput=decreaseInputs{deltaIndex};
fprintf(serialObj, arduinoInput);
elseif keyCode(deltaKey)
deltaIndex=deltaIndex+1;
if deltaIndex>length(rDeltas)
deltaIndex=1;
end
elseif keyCode(finishKey)
disp('Printing final results... please wait')
% print initial and final red value
fprintf(serialObj, 'f');
%in case you want to eliminate one of these "read" commands,
%remember to cancel the correspondent part in the "f" if
%statement in the FlickeringLight arduino code
initialRed=read(serialObj, 6, "char");
finalRed=read(serialObj, 6, "char");
fprintf("Initial Red Value = %d,\n", str2num(initialRed));
fprintf("Final Red Value = %d \n", str2num(finalRed));
% save everything
ListenChar(0)
WantToSave=input("Would you like to save these data? (yes or no) ", 's');
if strcmp(WantToSave, 'yes')
disp("Saving results...");
SaveHFPResultsTable(finalRed, rInit, gInit);
else
disp("Results not saved");
end
ListenChar(2)
break;
else
continue;
end
end
delete(instrfindall);
%save data
end
ListenChar(0) |
github | BrainardLab/TeachingCode-master | RenderSpectrumOnMonitorTutorial.m | .m | TeachingCode-master/ICVS2020Tutorials/RenderSpectrumOnMonitorTutorial.m | 11,826 | utf_8 | 749776d43b6f5da2a72aa5cc8f8786df | % RenderSpectrumOnMonitorTutorial
%
% Exercise to learn about rendering metamers on a monitor.
%
% This tutorial is available in the github repository
% https://github.com/BrainardLab/TeachingCode
% You can either clone the respository or just download a copy from
% that page (see green "Code" button).
%
% To run this, you will need both the Psychophysics Toolbox (PsychToolbox)
% and the BrainardLabToolbox on your path. You can get the PsychToolbox
% from
% psychtoolbox.org
% You can get the BrainardLabToolbox from
% https://github.com/BrainardLab/BrainardLabToolbox
%
% If you use the ToolboxToolbox (https://github.com/toolboxhub/toolboxtoolbox)
% and install the TeachingCode repository in your projects folder, you can
% install the dependencies by using
% tbUseProject('TeachingCode')
% at the Matlab prompt.
%
% You also need the calibration file NEC_MultisyncPA241W.mat, which is in
% the same directory as this tutorial in the github respository.
%
% There is a video that goes through this script and unpacks the
% calculations. It may be streamed from this link
% https://www.dropbox.com/s/v0ylynxteh7jc2j/RenderASpectrum.Orig.mp4?dl=0
% and downloaded from this link
% https://www.dropbox.com/s/v0ylynxteh7jc2j/RenderASpectrum.Orig.mp4?dl=1
% The downloaded version will play at higher resolution.
%
% A video lecture on using matrix-vector representations in colorimetric
% calculations is available here
% Stream - https://www.dropbox.com/s/lvtr3r60olmho3d/ConeFundamentalsLinearTransform.Orig.mp4?dl=0
% Download - https://www.dropbox.com/s/lvtr3r60olmho3d/ConeFundamentalsLinearTransform.Orig.mp4?dl=1
% As with the video above, the downloaded version will play at higher resolution.
%
% See also: RenderSpectrumOnMonitorForDogTutorial, RenderImageOnMonitorForDogTutorial
% History:
% 08/01/2020 dhb Wrote for ICVS from other tutorials that weren't quite
% what we wanted.
%% Clear
clear; close all;
%% Load and examine a test calibration file
%
% These are measurements from an LCD monitor, with data stored in a
% structure that describes key monitor properties.
calData = load('NEC_MultisyncPA241W');
cal = calData.cals{end};
% Get wavelength sampling of functions in cal file.
S = cal.rawData.S;
wls = SToWls(S);
% For simplicity, let's assume that no light comes off the monitor when the
% input is set to zero. This isn't true for real monitors, but we don't
% need to fuss with that aspect at the start.
cal.processedData.P_ambient = zeros(size(cal.processedData.P_ambient));
%% Plot the spectra of the three monitor primaries.
%
% For this monitor each primary is determined by the emission spectra of
% one of the phosphors on its faceplate, but that's a detail. Whwat we care
% about are the spectra, not how they were instrumented physically.
%
% Each primary spectrum is in a separate column of the matrix cal.processedData.P_device.
% In MATLAB,can use the : operator to help extract various pieces of a
% matrix. So:
redPhosphor = cal.processedData.P_device(:,1);
greenPhosphor = cal.processedData.P_device(:,2);
bluePhosphor = cal.processedData.P_device(:,3);
figure(1);clf; hold on
set(gca,'FontName','Helvetica','FontSize',18);
plot(wls,redPhosphor,'r','LineWidth',3);
plot(wls,greenPhosphor,'g','LineWidth',3);
plot(wls,bluePhosphor,'b','LineWidth',3);
title( 'Monitor channel spectra','FontSize',24);
xlabel( 'Wavelength [ nm ]','FontSize',24); ylabel( 'Radiance [ W / m^2 / sr / wlbin ]','FontSize',24);
hold off
%% Get human cone spectral sensitivities
%
% Here we use the Stockman-Sharpe 2-degree fundamentals, which are also the
% CIE fundamentals. They are stored as a .mat file in the Psychophysics
% Toolbox. See "help PsychColorimetricMatFiles'.
%
% By convention in the Psychtoolbox, we store sensitivities as the rows of
% a matrix. Spline the wavelength sampling to match that in the calibration
% file.
load T_cones_ss2
T_cones = SplineCmf(S_cones_ss2,T_cones_ss2,S);
% Make a plot
figure(2); clf; hold on
set(gca,'FontName','Helvetica','FontSize',18);
plot(wls,T_cones(1,:),'r','LineWidth',3);
plot(wls,T_cones(2,:),'g','LineWidth',3);;
plot(wls,T_cones(3,:),'b','LineWidth',3);
title( 'LMS Cone Fundamentals','FontSize',24);
xlabel( 'Wavelength','FontSize',24); ylabel( 'Sensitivity','FontSize',24);
hold off
%% Get a spectrum to render
%
% We want to render a spectrum on the monitor so that the light coming off the monitor has
% the same effect on the human cones as the spectrum would have. So we
% need a spectrum. We'll CIE daylight D65, since we have it available.
%
% The spectrum we read in is too bright to render on our monitor, so we
% also scale it down into a more reasonable range so we don't have to worry
% about that below.
load spd_D65
spectrumToRender = SplineSpd(S_D65,spd_D65,S)/0.75e4;
% If you want a different spectrum, this is operation on the D65
% produces a spectrum with more long wavelenght power and that renders
% pinkish.
% spectrumToRender = 1.5*max(spectrumToRender(:))*ones(size(spectrumToRender))-spectrumToRender;
% Make a plot of the spectrum to render
figure(3); clf; hold on
plot(wls,spectrumToRender,'k','LineWidth',3);
title('Metamers','FontSize',24);
xlabel('Wavelength','FontSize',24); ylabel( 'Power','FontSize',24);
%% Compute the cone excitations from the spectrum we want to render
%
% This turns out to be a simple matrix multiply in Matlab. The
% sensitivities are in the rows of T_cones and the spectral radiance is in
% the column vector spectrumToRender. For each row of T_cones, the matrix
% multiple consists of weighting the spectrum by the sensitivity at each
% wavelength and adding them up.
%
% Implicit here is that the units of spectrum give power per wavelength
% sampling bin, another important detail you'd want to think about to get
% units right for a real application and that we won't worry about here.
LMSToRender = T_cones*spectrumToRender;
%% We want to find a mixture of the monitor primaries that produces the same excitations
%
% Let's use the column vector [r g b]' to denote the amount of each primary
% we'll ultimately want in the mixture. By convention we'll think of r, g,
% and b as proportions relative to the maximum amount of each phosphor
% available on the monitor.
%
% It might be useful to make a plot of the example spectrum and see that it
% indeed looks like a mixture of the primary spectra.
rgbExample = [0.2 0.5 0.9]';
monitorSpectrumExample = rgbExample(1)*redPhosphor + rgbExample(2)*greenPhosphor + rgbExample(3)*bluePhosphor;
% We can also compute the spectrum coming off the monitor for any choice of r,
% g, and b using a matrix multiply. In this case, think of the
% multiplication as weighting each of the columns of cal.processedData.P_device (which
% are the primary spectra) and then summing them. You can verify that this
% gives the same answer as the expanded form just above.
monitorSpectrumExampleCheck = cal.processedData.P_device*rgbExample;
% We can also compute the LMS cone excitations for this example. This is
% just a column vector of three numbers.
monitorLMSExample = T_cones*monitorSpectrumExample;
% Now note that we can combine the two steps above, precomputing the matrix
% that maps between the rgb vector and the LMS excitations that result.
%
% You can verify that monitorLMSExample and monitorLMSExampleCheck are the
% same as each other.
rgbToLMSMatrix = T_cones*cal.processedData.P_device;
monitorLMSExampleCheck = rgbToLMSMatrix*rgbExample;
% We want to go the other way, starting with LMSToRender and obtaining an
% rgb vector that produces it. This is basically inverting the relation
% above, which is easy in Matlab.
LMSTorgbMatrix = inv(rgbToLMSMatrix);
rgbThatRender = LMSTorgbMatrix*LMSToRender;
% Let's check that it worked. The check values here should be the same as
% LMSToRender.
renderedSpectrum = cal.processedData.P_device*rgbThatRender;
LMSToRenderCheck = T_cones*renderedSpectrum;
% Add rendered spectrum to plot of target spectrum. You can see that they
% are of the same overall scale but differ in relative spectra. These two
% spectra are metamers - they produce the same excitations in the cones and
% will look the same to a human observer.
figure(3);
plot(wls,renderedSpectrum,'k:','LineWidth',3);
%% Make an image that shows the color
%
% We know the proportions of each of the monitor primaries required to
% produce a metamer to the spectrum we wanted to render. Now we'd like to
% look at this rendered spectrum. We have to assume that the properties of
% the monitor we're using are the same as the one in the calibration file,
% which isn't exactly true but will be close enough for illustrative
% purposes.
% What we need to do is find RGB values to put in the image so that we get
% the desired rgb propotions in the mixture that comes off. This is a
% little tricky, because the relation between the RGB values we put into an
% image and the rgb values that come off is non-linear. This non-linearity
% is called the gamma curve of the monitor, and we have to correct for it,
% a process known as gamma correction.
% As part of the monitor calibration, we meausured the gamma curves of our
% monitor, and they are in the calibration structure. Let's have a look
figure(4); clf; hold on
set(gca,'FontName','Helvetica','FontSize',18);
gammaInput = cal.processedData.gammaInput;
redGamma = cal.processedData.gammaTable(:,1);
greenGamma = cal.processedData.gammaTable(:,2);
blueGamma = cal.processedData.gammaTable(:,3);
plot(gammaInput,redGamma,'r','LineWidth',3);
plot(gammaInput,greenGamma,'g','LineWidth',3);
plot(gammaInput,blueGamma,'b','LineWidth',3);
title( 'Monitor gamma curves','FontSize',24);
xlabel( 'Input RGB','FontSize',24); ylabel( 'Mixture rgb','FontSize',24);
% We need to invert this curve - for each of our desired rgb values we need
% to find the corresponding RGB. That's not too hard, we can just do
% exhasutive search. This is done here in a little subfunction called
% SimpleGammaCorrection at the bottom of this file.
nLevels = length(gammaInput);
R = SimpleGammaCorrection(gammaInput,redGamma,rgbThatRender(1));
G = SimpleGammaCorrection(gammaInput,greenGamma,rgbThatRender(2));
B = SimpleGammaCorrection(gammaInput,blueGamma,rgbThatRender(3));
RGBThatRender = [R G B]';
% Make an and show the color image. We get (on my Apple Display) a slightly
% bluish gray, which is about right for D65 given that we aren't using a
% calibration of this display.
nPixels = 256;
theImage = zeros(nPixels,nPixels,3);
for ii = 1:nPixels
for jj = 1:nPixels
theImage(ii,jj,:) = RGBThatRender;
end
end
figure(5);
imshow(theImage);
%% Go from RGB back to the spectrum coming off the monitor
%
% There will be a very small difference between rgbFromRGB and
% rgbThatRender because the gamma correction quantizes the RGB
% values to discrete levels.
rgbFromRGB(1) = SimpleGammaCorrection(redGamma,gammaInput,RGBThatRender(1));
rgbFromRGB(2) = SimpleGammaCorrection(greenGamma,gammaInput,RGBThatRender(2));
rgbFromRGB(3) = SimpleGammaCorrection(blueGamma,gammaInput,RGBThatRender(3));
rgbFromRGB = rgbFromRGB';
spectrumFromRGB = cal.processedData.P_device*rgbFromRGB;
figure(3);
plot(wls,spectrumFromRGB,'r:','LineWidth',2);
function output = SimpleGammaCorrection(gammaInput,gamma,input)
% output = SimpleGammaCorrection(gammaInput,gamma,input)
%
% Perform gamma correction by exhaustive search. Just to show idea,
% not worried about efficiency.
%
% 9/14/08 ijk Wrote it.
% 12/2/09 dhb Update for [0,1] input table.
% 08/01/20 dhb Get rid of extraneous input variable
min_diff = Inf;
for i=1:length(gammaInput)
currentdiff = abs(gamma(i)-input);
if(currentdiff < min_diff)
min_diff = currentdiff;
output = i;
end
end
output = gammaInput(output);
end |
github | BrainardLab/TeachingCode-master | ColourCamouflageImageTutorial.m | .m | TeachingCode-master/ICVS2020Tutorials/ColourCamouflageImageTutorial.m | 8,062 | utf_8 | f7e8af66320136d261df52d4cfeecef3 | % ColourCamouflageImageTutorial
%
% Example code to colour a 3-colour image with dichromat confusion colours
% for use in camouflage example.
%
% To run this, you will need both the Psychophysics Toolbox (PsychToolbox)
% and the BrainardLabToolbox on your path. You can get the PsychToolbox
% from
% psychtoolbox.org
% You can get the BrainardLabToolbox from
% https://github.com/BrainardLab/BrainardLabToolbox
%
% You also need the kmeans_fast_Color function from Matlab Central
% https://uk.mathworks.com/matlabcentral/fileexchange/44598-fast-kmeans-algorithm-code?s_tid=mwa_osa_a
%
% If you use the ToolboxToolbox (https://github.com/toolboxhub/toolboxtoolbox)
% and install the TeachingCode repository in your projects folder, you can
% install the above dependencies by using
% tbUseProject('TeachingCode')
% at the Matlab prompt.
%
% You also need the calibration file NEC_MultisyncPA241W.mat and the image
% animal-silhouette-squirrel.jpg which are in the same directory as this
% tutorial in the TeachingCode github respository.
%
% Before running this, you may want to become familiar with
% RenderSpectrumOnMonitorTutorial.
%
% See also: RenderSpectrumOnMonitorTutorial.
% History:
% Written 04/08/2020 (that's 08/04/2020 for Americans) by Hannah Smithson
% using example code from the RenderSpectrumOnMonitorTutorial
% 08/06/20 dhb Some commenting.
%% Clear old variables, and close figure windows
clear; close all;
%% Set some key parameters
rgbBackground = [0.2 0.2 0.0]'; % for a 'natural looking' image, choose a brown background
coneContrastsForTarget = [1.4 1.4 1.4]; % triplet specifying multiplier on the background LMS (e.g. [1.2, 1.0, 1.0] is 20% L-cone contrast)
coneContrastsForCamouflage = [1.3 0.7 1.0]; % triplet specifying multiplier on the background LMS (e.g. [1.2, 1.0, 1.0] is 20% L-cone contrast)
numberOfCamoBlobs = 700; % specify the number of "camouflage" blobs
numberOfIntensityBlobs = 300; % specify the number of blobs used to add intensity variation
sizeScaleFactorCamo = 0.03; % size of blobs (fraction of image width)
sizeScaleFactorIntensity = 0.05;
%% Load and a test calibration file
%
% These are measurements from an LCD monitor, with data stored in a
% structure that describes key monitor properties.
calData = load('NEC_MultisyncPA241W');
cal = calData.cals{end};
% Get wavelength sampling of functions in cal file.
S = cal.rawData.S;
wls = SToWls(S);
% For simplicity, let's assume that no light comes off the monitor when the
% input is set to zero. This isn't true for real monitors, but we don't
% need to fuss with that aspect at the start.
cal.processedData.P_ambient = zeros(size(cal.processedData.P_ambient));
%% Get human cone spectral sensitivities
%
% Here we use the Stockman-Sharpe 2-degree fundamentals, which are also the
% CIE fundamentals. They are stored as a .mat file in the Psychophysics
% Toolbox. See "help PsychColorimetricMatFiles'.
%
% By convention in the Psychtoolbox, we store sensitivities as the rows of
% a matrix. Spline the wavelength sampling to match that in the calibration
% file.
load T_cones_ss2
T_cones = SplineCmf(S_cones_ss2,T_cones_ss2,S);
%% We want to find a mixture of the monitor primaries that produces a given LMS excitation
%
% Use the calibration data to generate the rgbToLMSMatrix
% (more info available in RenderSpectrumOnMonitor tutorial)
%
% We use the column vector [r g b]' to denote the amount of each primary
% we'll ultimately want in the mixture. By convention we'll think of r, g,
% and b as proportions relative to the maximum amount of each phosphor
% available on the monitor.
rgbToLMSMatrix = T_cones*cal.processedData.P_device;
lmsBackground = rgbToLMSMatrix*rgbBackground;
% Now set an LMS triplet for the "figure", which differs from the ground
% only in L-cone excitation - a 20% increase in L-cone excitation
lmsTarget = coneContrastsForTarget' .* lmsBackground;
lmsCamouflage = coneContrastsForCamouflage' .* lmsBackground;
% We want to go the other way, starting with lmsFigure and obtaining an
% rgb vector that produces it. This is basically inverting the relation
% above, which is easy in Matlab.
LMSTorgbMatrix = inv(rgbToLMSMatrix);
rgbTarget = LMSTorgbMatrix*lmsTarget;
rgbCamouflage = LMSTorgbMatrix*lmsCamouflage;
%% Make an image that shows the three colors - background, target and camouflage
%
% What we need to do is find RGB values to put in the image so that we get
% the desired rgb propotions in the mixture that comes off. This is a
% little tricky, because the relation between the RGB values we put into an
% image and the rgb values that come off is non-linear. This non-linearity
% is called the gamma curve of the monitor, and we have to correct for it,
% a process known as gamma correction.
RGBBackground = GammaCorrectionForTriplet(rgbBackground, cal);
RGBTarget = GammaCorrectionForTriplet(rgbTarget, cal);
RGBCamouflage = GammaCorrectionForTriplet(rgbCamouflage, cal);
nPixels = 256;
theImageBackground = cat(3, ones(nPixels)*RGBBackground(1), ones(nPixels)*RGBBackground(2), ones(nPixels)*RGBBackground(3));
theImageTarget = cat(3, ones(nPixels)*RGBTarget(1), ones(nPixels)*RGBTarget(2), ones(nPixels)*RGBTarget(3));
theImageCamouflage = cat(3, ones(nPixels)*RGBCamouflage(1), ones(nPixels)*RGBCamouflage(2), ones(nPixels)*RGBCamouflage(3));
figure;
imshow(cat(1, theImageBackground, theImageTarget, theImageCamouflage));
%% Make a more naturalistic image of camouflaged targets
%
% Read in a binary black and white image
A = imread('animal-silhouette-squirrel.jpg'); % white = background; black = target
imW = size(A, 1);
imH = size(A, 2);
% Show the original image
figure
imagesc(A)
%% Convert the white to grey and add camo blobs
A = 0.5 * A;
for i = 1:numberOfCamoBlobs
A = insertShape(A,'FilledCircle',[imH*rand(1), imW*rand(1), sizeScaleFactorCamo*imW*rand(1)], 'Color', 'white','Opacity',1.0);
end
% Show the grey scale image with blobs
figure
imshow(A)
% If the original image has smoothing or compression, cluster 3 pixel values
[threeColImage,vec_mean] = kmeans_fast_Color(A, 3);
% Make a colour map from the colours we defined
map = cat(1, RGBTarget, RGBBackground, RGBCamouflage);
figure
imshow(threeColImage, map);
% Add intensity noise to true colour image
A = ind2rgb(threeColImage, map);
for i = 1:numberOfIntensityBlobs
A = insertShape(A,'FilledCircle',[imH*rand(1), imW*rand(1), sizeScaleFactorIntensity*imW*rand(1)], 'Color', 'black','Opacity',0.1);
end
figure
imshow(A)
function useRGB = GammaCorrectionForTriplet(desiredrgb, cal)
% As part of the monitor calibration, we meausured the gamma curves of our
% monitor, and they are in the calibration structure. Let's have a look
gammaInput = cal.processedData.gammaInput;
redGamma = cal.processedData.gammaTable(:,1);
greenGamma = cal.processedData.gammaTable(:,2);
blueGamma = cal.processedData.gammaTable(:,3);
% We need to invert this gamma curve - for each of our desired rgb values we need
% to find the corresponding RGB. That's not too hard, we can just do
% exhasutive search. This is done here in a little subfunction called
% SimpleGammaCorrection at the bottom of this file.
R = SimpleGammaCorrection(gammaInput,redGamma,desiredrgb(1));
G = SimpleGammaCorrection(gammaInput,greenGamma,desiredrgb(2));
B = SimpleGammaCorrection(gammaInput,blueGamma,desiredrgb(3));
useRGB = [R G B];
end
function output = SimpleGammaCorrection(gammaInput,gamma,input)
% output = SimpleGammaCorrection(gammaInput,gamma,input)
%
% Perform gamma correction by exhaustive search. Just to show idea,
% not worried about efficiency.
%
% 9/14/08 ijk Wrote it.
% 12/2/09 dhb Update for [0,1] input table.
% 08/01/20 dhb Get rid of extraneous input variable
min_diff = Inf;
for i=1:length(gammaInput)
currentdiff = abs(gamma(i)-input);
if(currentdiff < min_diff)
min_diff = currentdiff;
output = i;
end
end
output = gammaInput(output);
end
|
github | BrainardLab/TeachingCode-master | RenderSpectrumOnMonitorForDogTutorial.m | .m | TeachingCode-master/ICVS2020Tutorials/RenderSpectrumOnMonitorForDogTutorial.m | 11,021 | utf_8 | 0e4da36aa7791abdabd1128cfd429255 | % RenderSpectrumOnMonitorForDogTutorial
%
% Exercise to learn about rendering metamers on a monitor. This version is
% for a dichromat. As an example, we'll use the cone spectral
% sensitivities of the dog.
%
% Before working through this tutorial, you should work through the
% tutorial RenderSpectrumOnMonitorTutorial. After you understand this one,
% you can look at RenderImageOnMonitorForDogTutorial, which applies the
% idea to render images rather than a single spectrum.
%
% This tutorial is available in the github repository
% https://github.com/BrainardLab/TeachingCode
% You can either clone the respository or just download a copy from
% that page (see green "Code" button).
%
% To run this, you will need both the Psychophysics Toolbox (PsychToolbox)
% and the BrainardLabToolbox on your path. You can get the PsychToolbox
% from
% psychtoolbox.org
% You can get the BrainardLabToolbox from
% https://github.com/BrainardLab/BrainardLabToolbox
%
% If you use the ToolboxToolbox (https://github.com/toolboxhub/toolboxtoolbox)
% and install the TeachingCode repository in your projects folder, you can
% install the dependencies by using
% tbUseProject('TeachingCode')
% at the Matlab prompt.
%
% You also need the calibration file NEC_MultisyncPA241W.mat, which is in
% the same directory as this tutorial in the github respository.
%
% See also: RenderSpectrumOnMonitorTutorial, RenderImageOnMonitorForDogTutorial
% History:
% 08/02/2020 dhb Wrote for ICVS from other tutorials that weren't quite
% what we wanted.
%% Clear
clear; close all;
%% Load and examine a test calibration file
%
% These are measurements from an LCD monitor, with data stored in a
% structure that describes key monitor properties.
calData = load('NEC_MultisyncPA241W');
cal = calData.cals{end};
% Get wavelength sampling of functions in cal file.
S = cal.rawData.S;
wls = SToWls(S);
% For simplicity, let's assume that no light comes off the monitor when the
% input is set to zero. This isn't true for real monitors, but we don't
% need to fuss with that aspect at the start.
cal.processedData.P_ambient = zeros(size(cal.processedData.P_ambient));
%% Plot the spectra of the three monitor primaries.
%
% For this monitor each primary is determined by the emission spectra of
% one of the phosphors on its faceplate, but that's a detail. Whwat we care
% about are the spectra, not how they were instrumented physically.
%
% Each primary spectrum is in a separate column of the matrix cal.processedData.P_device.
% In MATLAB,can use the : operator to help extract various pieces of a
% matrix. So:
redPhosphor = cal.processedData.P_device(:,1);
greenPhosphor = cal.processedData.P_device(:,2);
bluePhosphor = cal.processedData.P_device(:,3);
figure(1);clf; hold on
set(gca,'FontName','Helvetica','FontSize',18);
plot(wls,redPhosphor,'r','LineWidth',3);
plot(wls,greenPhosphor,'g','LineWidth',3);
plot(wls,bluePhosphor,'b','LineWidth',3);
title( 'Monitor channel spectra','FontSize',24);
xlabel( 'Wavelength [ nm ]','FontSize',24); ylabel( 'Radiance [ W / m^2 / sr / wlbin ]','FontSize',24);
hold off
%% Get animal spectral sensitivities
%
% Here we use the dog, a dichromat.
%
% By convention in the Psychtoolbox, we store sensitivities as the rows of
% a matrix. Spline the wavelength sampling to match that in the calibration
% file.
%
% T_dogrec has the dog L cone, dog S cone, and dog rod in its three
% rows. We only want the cones for high light level viewing.
load T_dogrec
T_cones = SplineCmf(S_dogrec,T_dogrec([1,2],:),S);
load T_cones_ss2
T_cones = SplineCmf(S_cones_ss2,T_cones_ss2,S);
T_cones = T_cones([1,3],:);
% Make a plot
figure(2); clf; hold on
set(gca,'FontName','Helvetica','FontSize',18);
plot(wls,T_cones(1,:),'r','LineWidth',3);
plot(wls,T_cones(2,:),'b','LineWidth',3);
title( 'LS Cone Fundamentals','FontSize',24);
xlabel( 'Wavelength','FontSize',24); ylabel( 'Sensitivity','FontSize',24);
hold off
%% Get a spectrum to render
%
% We want to render a spectrum on the monitor so that the light coming off
% the monitor has the same effect on the human cones as the spectrum would
% have. So we need a spectrum. We'll use a spectrum computed from CIE D65
% that renders pinkish for a human. (See alternate spectrum in
% RenderSpectrumOnMonitorTutorial).
load spd_D65
spectrumToRender = SplineSpd(S_D65,spd_D65,S)/0.75e4;
spectrumToRender = 1.5*max(spectrumToRender(:))*ones(size(spectrumToRender))-spectrumToRender;
% Make a plot of the spectrum to render
figure(3); clf; hold on
plot(wls,spectrumToRender,'k','LineWidth',3);
title('Metamers','FontSize',24);
xlabel('Wavelength','FontSize',24); ylabel( 'Power','FontSize',24);
%% Compute the cone excitations from the spectrum we want to render
%
% This turns out to be a simple matrix multiply in Matlab. The
% sensitivities are in the rows of T_cones and the spectral radiance is in
% the column vector spectrumToRender. For each row of T_cones, the matrix
% multiple consists of weighting the spectrum by the sensitivity at each
% wavelength and adding them up.
%
% Implicit here is that the units of spectrum give power per wavelength
% sampling bin, another important detail you'd want to think about to get
% units right for a real application and that we won't worry about here.
LSToRender = T_cones*spectrumToRender;
%% We want to find a mixture of the monitor primaries that produces the same excitations
%
% Since there are only two primaries needed, we'll average the red and green
% and treat that as a yellow primary.
%
% Let's use the column vector [y b]' to denote the amount of each primary
% we'll ultimately want in the mixture. By convention we'll think of y
% and b as proportions relative to the maximum amount of each primary
% available on the monitor.
%
% It might be useful to make a plot of the example spectrum and see that it
% indeed looks like a mixture of the primary spectra.
ybExample = [0.2 0.5]';
monitorSpectrumExample = ybExample(1)*(redPhosphor+greenPhosphor)/2 + ybExample(2)*bluePhosphor;
% We can also compute the spectrum coming off the monitor for any choice of
% y and b using a matrix multiply. In this case, think of the
% multiplication as weighting each of the columns of monitorBasis (defined
% below) and then summing them. You can verify that this gives the same
% answer as the expanded form just above.
monitorBasis = [(redPhosphor+greenPhosphor)/2 bluePhosphor];
monitorSpectrumExampleCheck = monitorBasis*ybExample;
% We can also compute the LMS cone excitations for this example. This is
% just a column vector of three numbers.
monitorLMSExample = T_cones*monitorSpectrumExample;
% Now note that we can combine the two steps above, precomputing the matrix
% that maps between the rgb vector and the LS excitations that result.
%
% You can verify that monitorLMSExample and monitorLMSExampleCheck are the
% same as each other.
ybToLSMatrix = T_cones*monitorBasis;
monitorLMSExampleCheck = ybToLSMatrix*ybExample;
% We want to go the other way, starting with LSToRender and obtaining an
% rgb vector that produces it. This is basically inverting the relation
% above, which is easy in Matlab.
LSTorgbMatrix = inv(ybToLSMatrix);
ybThatRender = LSTorgbMatrix*LSToRender;
% Let's check that it worked. The check values here should be the same as
% LMSToRender.
renderedSpectrum = monitorBasis*ybThatRender;
LSToRenderCheck = T_cones*renderedSpectrum;
% Add rendered spectrum to plot of target spectrum. You can see that they
% are of the same overall scale but differ in relative spectra. These two
% spectra are metamers - they produce the same excitations in the cones and
% will look the same to a human observer.
figure(3);
plot(wls,renderedSpectrum,'k:','LineWidth',3);
%% Make an image that shows the color
%
% We know the proportions of each of the monitor primaries required to
% produce a metamer to the spectrum we wanted to render. Now we'd like to
% look at this rendered spectrum. We have to assume that the properties of
% the monitor we're using are the same as the one in the calibration file,
% which isn't exactly true but will be close enough for illustrative
% purposes.
% What we need to do is find RGB values to put in the image so that we get
% the desired rgb propotions in the mixture that comes off. This is a
% little tricky, because the relation between the RGB values we put into an
% image and the rgb values that come off is non-linear. This non-linearity
% is called the gamma curve of the monitor, and we have to correct for it,
% a process known as gamma correction.
% As part of the monitor calibration, we meausured the gamma curves of our
% monitor, and they are in the calibration structure. Let's have a look
figure(4); clf; hold on
set(gca,'FontName','Helvetica','FontSize',18);
gammaInput = cal.processedData.gammaInput;
redGamma = cal.processedData.gammaTable(:,1);
greenGamma = cal.processedData.gammaTable(:,2);
blueGamma = cal.processedData.gammaTable(:,3);
plot(gammaInput,redGamma,'r','LineWidth',3);
plot(gammaInput,greenGamma,'g','LineWidth',3);
plot(gammaInput,blueGamma,'b','LineWidth',3);
title( 'Monitor gamma curves','FontSize',24);
xlabel( 'Input RGB','FontSize',24); ylabel( 'Mixture rgb','FontSize',24);
% We need to convert our yb values to rgb values at this point. But that's
% easy r = g = y/2.
rgbThatRender = [ybThatRender(1)/2 ybThatRender(1)/2 ybThatRender(2)]';
% Check that this rgb does what we want
renderedSpectrum1 = cal.processedData.P_device*rgbThatRender;
LSToRenderCheck1 = T_cones*renderedSpectrum1;
% Then we invert the RGB gamma curve - for each of our desired rgb values we need
% to find the corresponding RGB. That's not too hard, we can just do
% exhasutive search. This is done here in a little subfunction called
% SimpleGammaCorrection at the bottom of this file.
nLevels = length(gammaInput);
R = SimpleGammaCorrection(gammaInput,redGamma,rgbThatRender(1));
G = SimpleGammaCorrection(gammaInput,greenGamma,rgbThatRender(2));
B = SimpleGammaCorrection(gammaInput,blueGamma,rgbThatRender(3));
RGBThatRender = [R G B]';
% Make an and show the color image. We get (on my Apple Display) a slightly
% bluish gray, which is about right for D65 given that we aren't using a
% calibration of this display.
nPixels = 256;
theImage = zeros(nPixels,nPixels,3);
for ii = 1:nPixels
for jj = 1:nPixels
theImage(ii,jj,:) = RGBThatRender;
end
end
figure(5);
imshow(theImage);
function output = SimpleGammaCorrection(gammaInput,gamma,input)
% output = SimpleGammaCorrection(gammaInput,gamma,input)
%
% Perform gamma correction by exhaustive search. Just to show idea,
% not worried about efficiency.
%
% 9/14/08 ijk Wrote it.
% 12/2/09 dhb Update for [0,1] input table.
% 08/01/20 dhb Get rid of extraneous input variable
min_diff = Inf;
for i=1:length(gammaInput)
currentdiff = abs(gamma(i)-input);
if(currentdiff < min_diff)
min_diff = currentdiff;
output = i;
end
end
output = gammaInput(output);
end |
github | BrainardLab/TeachingCode-master | RenderImageOnMonitorForDogTutorial.m | .m | TeachingCode-master/ICVS2020Tutorials/RenderImageOnMonitorForDogTutorial.m | 5,976 | utf_8 | 3d978efe6447db441c9fa1acd1786e2c | % RenderImageOnMonitorForDogTutorial
%
% Render an RGB image as a metamer for a dichromat. This tutorial builds
% on the ideas introduced in RenderSpectrumOnMonitorTutorial and
% RenderSpectrumOnMonitorForDogTutorial.
%
% In this version, you can control the metameric image you produce by
% changing the parameter lambda near the top.
%
% This tutorial is available in the github repository
% https://github.com/BrainardLab/TeachingCode
% You can either clone the respository or just download a copy from
% that page (see green "Code" button).
%
% To run this, you will need both the Psychophysics Toolbox (PsychToolbox)
% and the BrainardLabToolbox on your path. You can get the PsychToolbox
% from
% psychtoolbox.org
% You can get the BrainardLabToolbox from
% https://github.com/BrainardLab/BrainardLabToolbox
%
% If you use the ToolboxToolbox (https://github.com/toolboxhub/toolboxtoolbox)
% and install the TeachingCode repository in your projects folder, you can
% install the dependencies by using
% tbUseProject('TeachingCode')
% at the Matlab prompt.
%
% You also need the calibration file NEC_MultisyncPA241W.mat, which is in
% the same directory as this script in the github respository.
%
% See also: RenderSpectrumOnMonitorTutorial, RenderSpectrumOnMonitorForDogTutorial
% History
% 08/03/2020 dhb Wrote it.
%% Clear
clear; close all;
%% Parameters
%
% The lambda parameter governs how the red and green primary spectra are
% mixed to produce the "yellow" primary for the simulated two primary
% device. Varying this will change the metameric image you produce. This
% variable should stay between 0 and 1.
lambda = 0.7;
%% Load and examine a test calibration file
%
% These are measurements from an LCD monitor, with data stored in a
% structure that describes key monitor properties.
calData = load('NEC_MultisyncPA241W');
cal = calData.cals{end};
redPhosphor = cal.processedData.P_device(:,1);
greenPhosphor = cal.processedData.P_device(:,2);
bluePhosphor = cal.processedData.P_device(:,3);
% Get wavelength sampling of functions in cal file.
S = cal.rawData.S;
wls = SToWls(S);
% For simplicity, let's assume that no light comes off the monitor when the
% input is set to zero. This isn't true for real monitors, but we don't
% need to fuss with that aspect at the start.
cal.processedData.P_ambient = zeros(size(cal.processedData.P_ambient));
%% Load human cone spectral sensitivities
load T_cones_ss2
T_conesTrichrom = SplineCmf(S_cones_ss2,T_cones_ss2,S);
%% Get animal spectral sensitivities
%
% Here we use the dog, a dichromat.
%
% By convention in the Psychtoolbox, we store sensitivities as the rows of
% a matrix. Spline the wavelength sampling to match that in the calibration
% file.
%
% T_dogrec has the dog L cone, dog S cone, and dog rod in its three
% rows. We only want the cones for high light level viewing.
load T_dogrec
T_conesDichrom = SplineCmf(S_dogrec,T_dogrec([1,2],:),S);
% If you want ground squirrel instead comment in these lines. You could
% also set T_conesDichrom to some pair of the human LMS cones to generate
% metameric image for human dichromats.
% load T_ground
% T_conesDichrom = SplineCmf(S_dogrec,T_dogrec([1,2],:),S);
%% Get an image to render
%
% This one comes with Matlab, just need to map through the color lookup
% table in variable map to produce a full color image.
load mandrill
RGBImage = zeros(size(X,1),size(X,2),3);
for ii = 1:size(X,1)
for jj = 1:size(X,2)
RGBImage(ii,jj,:) = map(X(ii,jj),:);
end
end
figure(1); imshow(RGBImage);
%% Ungamma correct the image
%
% Cal format strings out each pixel as a column in a 3 by n*m matrix.
% Convenient for color transformations. Put the image in cal format.
[RGBCal,m,n] = ImageToCalFormat(RGBImage);
% Inverse gamma correction to get rgb from RGB
rgbCal = zeros(size(RGBCal));
for ii = 1:m*n
for cc = 1:3
rgbCal(cc,ii) = SimpleGammaCorrection(cal.processedData.gammaTable(:,cc),cal.processedData.gammaInput,RGBCal(cc,ii));
end
end
%% Get spectrum and LS coordinates from rgb
theSpectrumCal = cal.processedData.P_device*rgbCal;
theLSCal = T_conesDichrom*theSpectrumCal;
%% Make virtual two primary monitor and find yb values that produce metamers
%
% Use a controlable mixture of red and green, with parameter lambda
% determining how much of each.
monitorBasis = [lambda*redPhosphor+(1-lambda)*greenPhosphor bluePhosphor];
ybToLSMatrix = T_conesDichrom*monitorBasis;
LSToybMatrix = inv(ybToLSMatrix);
ybCal = LSToybMatrix*theLSCal;
%% Promote yb to rgb using our knowledge of how we built the primaries
%
% Use lambda to determine ratio of red to green, to match the way we set up
% the combined phosphor.
rgbMetamerCal = [lambda*ybCal(1,:) ; (1-lambda)*ybCal(1,:) ; ybCal(2,:)];
%% Check that we get the desired LS excitations ro numerical precision
theLSCalCheck = T_conesDichrom*cal.processedData.P_device*rgbMetamerCal;
if (max(abs(theLSCal(:)-theLSCalCheck(:))) > 1e-10)
error('Do not get desired LS values');
end
%% Gamma correct to get RGB for the metamer, convert back to image format, and display
RGBMetamerCal = zeros(size(RGBCal));
for ii = 1:m*n
for cc = 1:3
RGBMetamerCal(cc,ii) = SimpleGammaCorrection(cal.processedData.gammaInput,cal.processedData.gammaTable(:,cc),rgbMetamerCal(cc,ii));
end
end
RGBMetamerImage = CalFormatToImage(RGBMetamerCal,m,n);
figure(2);
imshow(RGBMetamerImage);
function output = SimpleGammaCorrection(gammaInput,gamma,input)
% output = SimpleGammaCorrection(gammaInput,gamma,input)
%
% Perform gamma correction by exhaustive search. Just to show idea,
% not worried about efficiency.
%
% 9/14/08 ijk Wrote it.
% 12/2/09 dhb Update for [0,1] input table.
% 08/01/20 dhb Get rid of extraneous input variable
min_diff = Inf;
for i=1:length(gammaInput)
currentdiff = abs(gamma(i)-input);
if(currentdiff < min_diff)
min_diff = currentdiff;
output = i;
end
end
output = gammaInput(output);
end
|
github | BrainardLab/TeachingCode-master | GLW_CircularApertureStimulus.m | .m | TeachingCode-master/GLWindowExamples/GLW_CircularApertureStimulus.m | 3,239 | utf_8 | 4a08aa08a3f6335936cb7c5f2a94a11e | function GLW_CircularApertureStimulus()
% GLW_CircularApertureStimulus()
%
% Demonstrate how to generate a noise stimulus with a circular aperture using
% GLWindow.
%
% The program terminates when the user presses the'q' key.
%
%
% 12/3/13 npc Wrote it.
% Generate 256x256 noise stimulus
imageSize = 256;
stimMatrix = rand(imageSize, imageSize)-0.5;
% Generate circular aperture
mask = GenerateSoftCircularAperture(imageSize);
% Apply the mask to the stimulus
imageMatrix = 0.5 + (stimMatrix .* mask);
% Create an RGB version for display by GLWindow
imageMatrixRGB = repmat(imageMatrix, [1 1 3]);
% Get information about the displays attached to our system.
displayInfo = mglDescribeDisplays;
% We will present everything to the last display. Get its ID.
lastDisplay = length(displayInfo);
% Get the screen size
screenSizeInPixels = displayInfo(lastDisplay).screenSizePixel;
win = [];
try
% Create a full-screen GLWindow object
win = GLWindow( 'SceneDimensions', screenSizeInPixels, ...
'BackgroundColor', [0.5 0.5 0.5],...
'windowID', lastDisplay);
% Open the window
win.open;
% Add stimulus image to the GLWindow
centerPosition = [0 0];
win.addImage(centerPosition, size(imageMatrix), ...
imageMatrixRGB, 'Name', 'stimulus');
% Render the scene
win.draw;
% Wait for a character keypress.
ListenChar(2);
FlushEvents;
disp('Press q to exit');
Speak('Press q to exit', 'Alex');
keepLooping = true;
while (keepLooping)
if CharAvail
% Get the key
theKey = GetChar;
if (theKey == 'q')
keepLooping = false;
end
end
end
% Close the window.
win.close;
ListenChar(0);
catch e
disp('An exception was raised');
% Disable character listening.
ListenChar(0);
% Close the window if it was succesfully created.
if ~isempty(win)
win.close;
end
% Send the error back to the Matlab command window.
rethrow(e);
end % try
end
function aperture = GenerateSoftCircularAperture(imageSize)
% aperture = GenerateSoftCircularAperture(imageSize)
%
% This function generates a soft circular aperture that is used to window the test image.
%
% 12/10/12 npc Wrote it.
% 12/13/12 npc Changed computation of soft border to decrease the width of
% the transition area, and thus display more of the image
x = [-imageSize/2:imageSize/2-1] + 0.5;
[X,Y] = meshgrid(x,x);
radius = sqrt(X.^2 + Y.^2);
softRadius = (imageSize/2)*0.9;
softSigma = (imageSize/2 - softRadius) / 3.0;
delta = radius - softRadius;
aperture = ones(size(delta));
indices = find(delta > 0);
aperture(indices) = exp(-0.5*(delta(indices)/softSigma).^2);
end |
github | BrainardLab/TeachingCode-master | GLW_DriftingGrating.m | .m | TeachingCode-master/GLWindowExamples/GLW_DriftingGrating.m | 5,238 | utf_8 | 29ff1094bb6efc08206567a0e2b1a378 | function GLW_DriftingGrating
% GLW_DriftingGrating Demonstrates how to drift a grating in GLWindow.
%
% Syntax:
% GLW_DriftingGrating
%
% Description:
% The function drifts a grating. Might not be completely done
%
% Press - 'd' to dump image of window into a file
% - 'q' to quit
% 12/5/12 dhb Wrote it from code lying around, in part due to Adam Gifford.
% 11/xx/20 dhb Drifting version.
try
% Choose the last attached screen as our target screen, and figure out its
% screen dimensions in pixels. Using these to open the GLWindow keeps
% the aspect ratio of stuff correct.
d = mglDescribeDisplays;
screenDims = d(end).screenSizePixel;
% Open the window.
win = GLWindow('SceneDimensions', screenDims,'windowId',length(d));
win.open;
% Load a calibration file for gamma correction. Put
% your calibration file here.
calFile = 'PTB3TestCal';
S = WlsToS((380:4:780)');
load T_xyz1931
T_xyz = SplineCmf(S_xyz1931,683*T_xyz1931,S);
igertCalSV = LoadCalFile(calFile);
igertCalSV = SetGammaMethod(igertCalSV,0);
igertCalSV = SetSensorColorSpace(igertCalSV,T_xyz,S);
% Draw a neutral background at roughly half the
% dispaly maximum luminance.
bgrgb = [0.5 0.5 0.5]';
bgRGB1 = PrimaryToSettings(igertCalSV,bgrgb);
win.BackgroundColor = bgRGB1';
win.draw;
% Create gabor patches with specified parameters
sine = false;
pixelSize = min(screenDims);
contrast = 0.9;
sf = 1;
sigma = 0.5;
theta = 0;
nPhases = 100;
phases = linspace(0,360,nPhases);
xdist = 0;
ydist = 0;
for ii = 1:nPhases
% Make gabor in each phase
gaborrgb{ii} = createGabor(pixelSize,contrast,sf,theta,phases(ii),sigma);
if (~sine)
gaborrgb{ii}(gaborrgb{ii} > 0.5) = 1;
gaborrgb{ii}(gaborrgb{ii} < 0.5) = 0;
end
% Gamma correct
[calForm1 c1 r1] = ImageToCalFormat(gaborrgb{ii});
[RGB] = PrimaryToSettings(igertCalSV,calForm1);
gaborRGB{ii} = CalFormatToImage(RGB,c1,r1);
win.addImage([xdist ydist], [pixelSize pixelSize], gaborRGB{ii}, 'Name',sprintf('theGabor%d',ii));
end
% Temporal params
hz = 0.5;
frameRate = d.refreshRate;
framesPerPhase = round((frameRate/hz)/nPhases);
% Wait for a key to quit
ListenChar(2);
FlushEvents;
whichPhase = 1;
whichFrame = 1;
oldPhase = nPhases;
flicker = true;
win.enableObject(sprintf('theGabor%d',nPhases));
while true
if (whichFrame == 1)
if (flicker)
win.disableObject(sprintf('theGabor%d',oldPhase));
win.enableObject(sprintf('theGabor%d',whichPhase));
oldPhase = whichPhase;
whichPhase = whichPhase + 1;
if (whichPhase > nPhases)
whichPhase = 1;
end
end
end
win.draw;
whichFrame = whichFrame + 1;
if (whichFrame > framesPerPhase)
whichFrame = 1;
end
key = 'z';
if (CharAvail)
key = GetChar;
end
switch key
% Quit
case 'q'
break;
case 'u'
flicker = false;
win.disableObject(sprintf('theGabor%d',oldPhase));
case 'f'
flicker = true;
otherwise
end
end
% Clean up and exit
win.close;
ListenChar(0);
% Error handler
catch e
ListenChar(0);
if ~isempty(win)
win.close;
end
rethrow(e);
end
function theGabor = createGabor(meshSize,contrast,sf,theta,phase,sigma)
%
% Input
% meshSize: size of meshgrid (and ultimately size of image).
% Must be an even integer
% contrast: contrast on a 0-1 scale
% sf: spatial frequency in cycles/image
% cycles/pixel = sf/meshSize
% theta: gabor orientation in degrees, clockwise relative to positive x axis.
% theta = 0 means horizontal grating
% phase: gabor phase in degrees.
% phase = 0 means sin phase at center, 90 means cosine phase at center
% sigma: standard deviation of the gaussian filter expressed as fraction of image
%
% Output
% theGabor: the gabor patch as rgb primary (not gamma corrected) image
% Create a mesh on which to compute the gabor
if rem(meshSize,2) ~= 0
error('meshSize must be an even integer');
end
res = [meshSize meshSize];
xCenter=res(1)/2;
yCenter=res(2)/2;
[gab_x gab_y] = meshgrid(0:(res(1)-1), 0:(res(2)-1));
% Compute the oriented sinusoidal grating
a=cos(deg2rad(theta));
b=sin(deg2rad(theta));
sinWave=sin((2*pi/meshSize)*sf*(b*(gab_x - xCenter) - a*(gab_y - yCenter)) + deg2rad(phase));
% Compute the Gaussian window
x_factor=-1*(gab_x-xCenter).^2;
y_factor=-1*(gab_y-yCenter).^2;
varScale=2*(sigma*meshSize)^2;
gaussianWindow = exp(x_factor/varScale+y_factor/varScale);
% Compute gabor. Numbers here run from -1 to 1.
theGabor=gaussianWindow.*sinWave;
% Convert to contrast
theGabor = (0.5+0.5*contrast*theGabor);
% Convert single plane to rgb
theGabor = repmat(theGabor,[1 1 3]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.