text:
classdef plot_standard_results_TCT_object

%  This object allows one to display the results for training and testing at different time points in the experiment
%   i.e., temporal cross-training (TCT) results, for results that were saved using the standard_resample_CV.run_cv_decoding method.
%   The results are plotted in an imagesc matrix where the y-axis indicates the time the classifier was trained
%   and the x-axis indicates the time when the classifier was tested.  Additionally, the results can be displayed
%   as a movie, with each frame showing the results for training the classifier at one particular time (indicated
%   by an line interval at the bottom of the screen), and testing the classifier at all other times (also the results
%   for training and testing at the same time as displayed as a black curve on the figure for reference).
%
%  The constructor for this method takes a string that has the name of the saved results that should be plotted, i.e.,
%   plot_obj = plot_standard_results_TCT_object('result_file_name').  Alternatively, the constructor can take a
%   [num_training_times x num_test_times] matrix with precompiled decoding results and will display a TCT plot with these precompiled results.
%   This can be useful, for example, if one wants to average several results together from different decoding experiments and then display
%   the average results as a TCT plot, etc.
%
%  The main method of this object is min_and_max_data_range = plot_obj.plot_results which will create a figure that will display the result matrix,
%   and also optionally a movie showing the results when training the classifier at different points in time. The method also returns
%   the minimum and maxium value of that data which is useful when one wants to plot data on the same range (see the color_result_range property below).
%   There are several optional parameters that can be set prior to calling the plot_results method which will change how the results
%   are displayed.  These optional properties are:
%
%    result_type_to_plot (default = 1).  Specifies which result type should be plotted.
%       If this is set to 1, then 0-1 loss results are plotted.
%       If this is set to 2, normalized rank results are plotted.
%       If this is set to 3, the mean decision values are plotted.
%       If this is set to 4, ROC_AUC results run separately on each CV split are plotted.
%       If this is set to 5, ROC_AUC results combined over CV splits are plotted.
%       If this is set to 6, mutual information created from a confusion matrix that combining data from all resamples is plotted.
%       If this is set to 7, mutual information created from a confusion matrix that is calculated separate and then averaged over resamples is plotted.
%
%    plot_time_intervals (default []). This property specifies which time points in the experiment the results correspond to
%      (i.e., this specifies the x-axis values that the results are plotting against).  If this field is empty
%      then this object will attempt to create the x-axis based on the binning_parameter properties that were created by the create_binned_data_from_raster_data
%      function that is passed through the DS and CV objects (if the binning _parameters structure does not exist, the results will be plotted against sequential
%      integers). If this value is set to a vector, then the times listed on the sides of the TCT matrix will use the values in this time range.
%      Alternatively, this property can be set to a structure (or a cell array of structs with the same length as the number of results) with the following fields:
%      plot_time_intervals.bin_width, plot_time_intervals.sampling_interval, and optionally plot_time_intervals.alignment_event_time,
%      and plot_time_intervals.alignment_type,  which will create a time interval that has the corresponding bin widths, step sizes
%      and zero time.  plot_time_intervals.alignment_type specifies whether the bins should be aligned to the center (lot_time_intervals.alignment_type = 2, default value),
%      the beginning of the bin (plot_time_intervals.alignment_type = 1), or the end of the bin (lot_time_intervals.alignment_type = 3).
%
%   significant_event_times.  This will cause vertical lines to be drawn at the times specified in this vector which can be used to
%     indicate significant events that occurred during a trial.
%
%   significant_training_event_times. This will cause horizontal lines to be drawn at the times specified in this vector which can be used to
%     indicate significant events that occurred during at particular training times in a trial.
%
%   plot_inds.  Allows plot a smaller range of the results given by the indicies listed in this vector.
%
%   saved_results_structure_name.  By default this object assumes that all results were saved in a structure called 'DECODING_RESULTS'. If
%     the structure of the saved results has a different name, the name can be specified here and the results will be plotted using this name.
%
%   color_result_range.  Specifies the range of the colormap for showing worst to best results.
%
%   figure_position (default = [])  Specifies the position of where the figure show be plotted.  This can be useful because resizing the figure after
%    it is plotted can potentially cause errors in the tick labels.  Also, if a figure is opened to a particular size prior to running this function
%    and this property is left empty, the function will use the size of the current figure.
%
%   TCT_figure_number (default = 1).  The figure number to display the TCT matrix.
%
%   plot_colorbar (default = 1).  If this is set to zero, the colorbar will not be plotted.
%
%   decoding_result_type_name (default = []).  Sets the name of result type chosen.  If this is left empty, the name will be chosen based on the type
%     of result_type used.  If displaying a movie of the results, this property will also be used for the label y-axis of the movie.
%
%   font_size (default = 16).  The font size for the axis labels.
%
%   ylabel_name (default = 'Train time (ms)'.  The label of the y-axis.
%
%   xlabel_name (default = 'Test Time (ms)' ). The label of the x-axis.
%
%   plot_training_latencies_increasing_up_the_y_axis (default = 1).  If this is set to 1, then the training latencies that are earlier in the trial
%     will be plotted closer to the x-axis (i.e., the results will be equivalent to using 'axis xy' rather than 'axis ij')
%
%
%
%  To display movies of the TCT results, where each frame shows the results for training at t1 and testing at t2, the display_TCT_movie must be set to one
%   (which is the default behavior of this property).  If plot_obj.display_TCT_movie = 1; then the following additional properties can be set:
%
%  the display_TCT_movie (default = 1).  Plots the temporal-cross-training results as a movie.
%
%  display_movie_pause_time (default = -1).  How long each frame of the movie show be displayed for.  If this is set to a value less than one,
%    then the frame will be shown until a key is pressed.
%
%   movie_figure_number (default = 2).  The figure number that the TCT movie will be shown in.
%
%   movie_save_name (default = []).  If this property is set to a string, the movie will be saved as an avi file using this name.
%
%   movie_time_period_titles  This field allows the movie to display different titles at different time points (which is useful if
%     one wants to give information about particular events such as 'stimulus on', 'stimulus off', etc.). If this field exist and
%     if there subfields 'movie_time_period_titles.title_start_times' that lists an array of
%     times specifying when particular figure titles should be displayed, and and 'movie_time_period_titles.title_names'
%     that is a cell array that lists the names of the titles at particular times, then the title of the movie figure will
%     change to display these titles at the given times.  Note that movie_time_period_titles.title_start_times and
%     movie_time_period_titles.title_names must be the same length.
%
%   chance_level.  Draws a horizontal line at what the chance decoding level is.  If this is unspecified, then the change level will be
%     1/num_classes for 0-1 loss results, no line will be drawn for decision values, and .5 line will be drawn for all other result types.
%
%   line_width (default = 2).  The line width of the plotted movie results.
%
%   sliding_result_color (default = 'b').  The color of the TCT results.  This color is also used
%    for indicating which interval the training time is at the bottom of the plot.
%
%    errorbar_file_name  If this is set to a string that contains decoding results in 'standard format',
%      errorbars for the movie will be plotted based on the file name listed.
%
%    errorbar_type_to_plot (default = 1).  If errorbar_file_name is specified, this field specified which type
%      of decoding variance measure (stdev field) should be plotted.  The values for this field are:
%      If this is set to 1, then the standard deviations over resample runs (i.e., stdev.over_resamples) is used.
%      If this is set to 2, then the standard deviations over the mean decoding results from each CV split (i.e., stdev.over_CVs) is used.
%        The mean value over all resample trials is then plotted.
%      If this is set to 3, then the standard deviations over the mean decoding results from each CV split combined together from all resample runs
%        (i.e., over_CVs_combined_over_resamples) is used.
%      If this is set to 4, then the standard deviation of individual results (e.g., 0 1 values if the 0-1 loss is used) from each CV split (all_single_CV_vals)
%        are used.  The mean value over all resample runs and CV splits is plotted.
%      If this is set to 5, then the standard deviation of individual results (e.g., 0 1 values if the 0-1 loss is used) from each CV split combined
%        from all CV splits in a single resample run (all_single_CV_vals_combined,) are used.  The mean value over all resample runs is plotted.
%      If this is set to 6, and ROC_AUC results are plotted, then the standard deviaion of the ROC results from over the different classes (over_classes)
%        are used. The mean results over resample runs (and CV splits for the separate_CV_ROC_results) are plotted.  This value can only be set when
%        ROC_AUC values are plotted (i.e., result_type_to_plot = 4 or 5)
%      It should also be noted that if separate_CV_ROC_results plotted (i.e., result_type_to_plot = 4), then errorbar_type_to_plot can only be set to values of 1, 2, or 6
%        and if combined_CV_ROC_results plotted (i.e., result_type_to_plot = 5), then errorbar_type_to_plot can only be set to values of 1 or 6.
%
%    errorbar_stdev_multiplication_factor (default = 1).  When plotting the errorbars, the default behavior is to plot then plus and minus 1 stdev for
%        the stdev type that is specified.  If errorbar_stdev_multiplication_factor is set to a value of k, then the errorbars will be plotted as
%        mean_results + (k * stdev)  and mean_results - (k * stdev).
%
%    errorbar_alpha_transparency (default = .2).  Sets the transparency level of the errorbars.
%
%    errorbar_edge_alpha_transparency (default = .2).  Sets the transparency level of the edges of the errorbars.
%
%

%==========================================================================

%     This code is part of the Neural Decoding Toolbox.
%     Copyright (C) 2011 by Ethan Meyers (emeyers@mit.edu)
%
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/>.

%==========================================================================

  properties

      result_file_name;
      result_type_to_plot = 1;   % 1: 0-1 loss, 2: normalized rank, 3: mean decision values 4: Area under ROC curve separate, 5: Areau udner ROC curve combined over CV splits

      plot_time_intervals;
      significant_event_times = [];
      significant_training_event_times = [];
      plot_inds = [];  % if only want to plot a smaller range of the results
      color_result_range = [];

      figure_position = [];
      plot_colorbar = 1;

      decoding_result_type_name = [];

      saved_results_structure_name = 'DECODING_RESULTS';

      TCT_figure_number = 1;

      plot_training_latencies_increasing_up_the_y_axis = 1;

      % parameters for creating a TCT movie

      display_TCT_movie = 1;
      display_movie_pause_time = -1;

      movie_figure_number = 2;

      movie_save_name = [];

      movie_time_period_titles = [];

      errorbar_file_name = [];
      errorbar_type_to_plot = 1;     % 1: over_resamples, 2: over_CVs, 3: over_CVs_combined_over_resamples, 4: all_single_CV_vals_combined, 5: all_single_CV_vals, 6: over_classes
      errorbar_stdev_multiplication_factor = 1;
      errorbar_alpha_transparency = .2;
      errorbar_edge_alpha_transparency = .2;

      chance_level = NaN;

      sliding_result_color = 'b';

      line_width = 2;
      font_size = 16;
      ylabel_name = 'Train time (ms)';
      xlabel_name = 'Test time (ms)';

  end

    methods

        % constructor
        function plot_obj = plot_standard_results_TCT_object(result_file_name)

            plot_obj.result_file_name = result_file_name;

        end

        function min_and_max_data_range = plot_results(plot_obj)

            if isstr(plot_obj.result_file_name)

                if plot_obj.result_type_to_plot == 1
                    result_type_name = 'ZERO_ONE_LOSS_RESULTS';
                    if isempty(plot_obj.decoding_result_type_name), plot_obj.decoding_result_type_name = 'Classification Accuracy'; end
                elseif plot_obj.result_type_to_plot == 2
                    result_type_name = 'NORMALIZED_RANK_RESULTS';
                    if isnan(plot_obj.chance_level), plot_obj.chance_level = .5; end
                    if isempty(plot_obj.decoding_result_type_name), plot_obj.decoding_result_type_name = 'Normalized Rank Accuracy'; end
                elseif plot_obj.result_type_to_plot == 3
                    result_type_name = 'DECISION_VALUES';
                    if isempty(plot_obj.decoding_result_type_name), plot_obj.decoding_result_type_name = 'Mean Decision Values'; end
                elseif plot_obj.result_type_to_plot == 4
                    result_type_name = 'ROC_AUC_RESULTS.separate_CV_ROC_results';
                    if isnan(plot_obj.chance_level), plot_obj.chance_level = .5; end
                    if isempty(plot_obj.decoding_result_type_name), plot_obj.decoding_result_type_name = 'Area under ROC curve'; end
                elseif plot_obj.result_type_to_plot == 5
                    result_type_name = 'ROC_AUC_RESULTS.combined_CV_ROC_results';
                    if isnan(plot_obj.chance_level), plot_obj.chance_level = .5; end
                    if isempty(plot_obj.decoding_result_type_name), plot_obj.decoding_result_type_name = 'Area under ROC curve'; end
                elseif plot_obj.result_type_to_plot == 6
                     result_type_name = 'MUTUAL_INFORMATION.from_combined_confusion_matrix_over_all_resamples';
                     if isnan(plot_obj.chance_level), plot_obj.chance_level = 0; end
                     if isempty(plot_obj.ylabel_name) &&  ~isstr(plot_obj.ylabel_name), plot_obj.ylabel_name = 'Mutual Information (bits)'; end
                elseif plot_obj.result_type_to_plot == 7
                     result_type_name = 'MUTUAL_INFORMATION.from_separate_confusion_matrix_for_each_resample';
                     if isnan(plot_obj.chance_level), plot_obj.chance_level = 0; end
                     if isempty(plot_obj.ylabel_name) &&  ~isstr(plot_obj.ylabel_name), plot_obj.ylabel_name = 'Mutual Information (bits)'; end
                end

                all_results = load(plot_obj.result_file_name);
                all_results_data = eval(['all_results.'  plot_obj.saved_results_structure_name]);

                if plot_obj.result_type_to_plot ~= 6
                    result_to_plot = eval(['all_results_data.' result_type_name '.mean_decoding_results']);
                else
                    result_to_plot = eval(['all_results_data.' result_type_name '.decoding_results']);
                end

                if size(result_to_plot, 2) == 1
                    error('Can only use this function for results in which the classifier was trained and tested at all times (i.e., .mean_decoding_results must be a matrix');
                end

                % for 0-1 loss results, find chance level if not specified, and also convert results to percent correct from proportion correct
                if (plot_obj.result_type_to_plot == 1)
                    if isnan(plot_obj.chance_level)
                        plot_obj.chance_level = (1./all_results_data.CV_PARAMETERS.num_unique_labels) .* 100;
                    end
                    result_to_plot = result_to_plot .* 100;
                end

                % if plot_obj.plot_time_intervals is not set to a vector (or cell array of vectors) of specific times, try to use the binning parameters to
                %    get the time interval to plot the results against
                if isfield(all_results_data, 'DS_PARAMETERS') && isfield(all_results_data.DS_PARAMETERS, 'binned_site_info') && isfield(all_results_data.DS_PARAMETERS.binned_site_info, 'binning_parameters')
                    curr_default_binning_parameters = all_results_data.DS_PARAMETERS.binned_site_info.binning_parameters;
                else
                    curr_default_binning_parameters = [];
                end

            elseif ismatrix(plot_obj.result_file_name)

                result_to_plot = plot_obj.result_file_name;
                curr_default_binning_parameters = [];

            end

            % if only plotting only a smaller range,
            if ~isempty(plot_obj.plot_inds)
               result_to_plot = result_to_plot(plot_obj.plot_inds, plot_obj.plot_inds);
            end

            the_time_interval  = plot_obj.plot_time_intervals;

            % if plot_obj.plot_time_intervals has been set by the user to a structure with bin_width, sampling_interval, etc.
            %  then create the x-axis time interval from these parameters, or if the_time_interval  is empty and DS_PARAMETERS.binned_site_info.binning_parameters exist,
            %  use these parameters to create a time interval.  Also make sure that plot_time_intervals has not been set to a vector of times.
               %if (isstruct(curr_time_interval) || ~isempty(curr_default_binning_parameters))  &&  ~(ismatrix(curr_time_interval) && ~isempty(curr_time_interval))
               if (isstruct(the_time_interval) || ~isempty(curr_default_binning_parameters))  ||  ~(ismatrix(the_time_interval) && ~isempty(the_time_interval))

                time_interval_obj = time_interval_object;
                time_interval_obj.set_parameters_with_binning_stucture(the_time_interval);

                time_interval_obj.set_all_currently_unset_parameters_with_binning_structure(curr_default_binning_parameters);

                the_time_interval = time_interval_obj.get_time_interval;

                if isempty(time_interval_obj.end_time), the_time_interval = the_time_interval(1:length(result_to_plot)); end

            elseif isempty(the_time_interval)  % otherwise if binning_parmaters don't exist (and no interval has been set) just use consecuative numbers on x-axis
                 the_time_interval = 1:length(result_to_plot);
            end

            % display the results
            figure(plot_obj.TCT_figure_number)
            hold off

            if ~isempty(plot_obj.color_result_range)
                imagesc(result_to_plot, plot_obj.color_result_range);
            else
                imagesc(result_to_plot);
            end

            min_and_max_data_range = [min(min(result_to_plot))  max(max(result_to_plot))];

            if plot_obj.plot_colorbar
                h = colorbar;
                %set(get(h, 'ylabel'), 'String', plot_obj.decoding_result_type_name, 'Rotation', 270, 'VerticalAlignment', 'Bottom', 'FontSize', plot_obj.font_size);
                title(plot_obj.decoding_result_type_name, 'FontSize', plot_obj.font_size);
            end

            % put the figure in the correct size before plotting the x and y tick labels since they will get messed up if the figure is resized after this
            if isempty(plot_obj.figure_position),
                plot_obj.figure_position = get(gcf, 'position');
            end
            set(gcf, 'position', plot_obj.figure_position);

            xticks = get(gca, 'XTick');
            xticks(xticks < 1) = [];  xticks(xticks > length(the_time_interval)) = [];  % added to get things to work in Octave
            if min(get(gca, 'XTick')) < 1
                set(gca, 'XTickLabel', [-1 the_time_interval(xticks)]);  % added to get things to work in Octave
            else
                set(gca, 'XTickLabel', the_time_interval(xticks));
            end

            yticks = get(gca, 'YTick');
            yticks(yticks < 1) = [];  yticks(yticks > length(the_time_interval)) = [];  % added to get things to work in Octave
            if min(get(gca, 'YTick')) < 1
                set(gca, 'YTickLabel', [-1 the_time_interval(yticks)]);  % added to get things to work in Octave
            else
                set(gca, 'YTickLabel', the_time_interval(yticks));
            end

            % add lines at significant event times
            significant_event_inds = (((plot_obj.significant_event_times - the_time_interval(1))./(the_time_interval(end) - the_time_interval(1))) .* (size(result_to_plot, 2) - 1)) + 1;

            for iEvent = 1:length(plot_obj.significant_event_times)
               line([significant_event_inds(iEvent), significant_event_inds(iEvent)], get(gca, 'YLim'), 'color', [0 0 0])
            end

            % add horizontal lines at significant training times
            significant_training_event_inds = (((plot_obj.significant_training_event_times - the_time_interval(1))./(the_time_interval(end) - the_time_interval(1))) .* (size(result_to_plot, 2) - 1)) + 1;

            for iEvent = 1:length(plot_obj.significant_training_event_times)
               line(get(gca, 'XLim'), [significant_training_event_inds(iEvent), significant_training_event_inds(iEvent)], 'color', [0 0 0])
            end

            ylabel(plot_obj.ylabel_name, 'FontSize', plot_obj.font_size);
            xlabel(plot_obj.xlabel_name, 'FontSize', plot_obj.font_size);

            if plot_obj.plot_training_latencies_increasing_up_the_y_axis == 1
                axis xy
            end

            %  plot/show a movie of the TCT results
            if plot_obj.display_TCT_movie > 0

                if ~isempty(plot_obj.movie_save_name)
                   mov = avifile([plot_obj.movie_save_name '.avi'], 'fps', 2);
                end

                min_and_max_decoding_vals = [min(min(result_to_plot)), max(max(result_to_plot))];

                % if plotting errorbars
                if ~isempty(plot_obj.errorbar_file_name)

                    % more sanity checks
                    if (plot_obj.errorbar_type_to_plot > 2) && (plot_obj.errorbar_type_to_plot ~=6) && (plot_obj.result_type_to_plot == 4)
                        error('When plotting ROC_AUC_RESULTS.separate_CV_ROC_results one can only plot stdevs over_resamples, over_CVs, and over_classes (i.e., if plot_obj.result_type_to_plot == 4, then plot_obj.errorbar_type_to_plot must be in the range 1, 2, or 6');
                    end

                    if (plot_obj.errorbar_type_to_plot > 1) && (plot_obj.errorbar_type_to_plot ~=6) && (plot_obj.result_type_to_plot == 5)
                        error('When plotting ROC_AUC_RESULTS.combined_CV_ROC_results one can only plot stdevs over_resamples, and over_classes (i.e., if plot_obj.result_type_to_plot == 5, then plot_obj.errorbar_type_to_plot must be 1 or 6');
                    end

                    all_errorbar = load(plot_obj.errorbar_file_name);
                    all_errorbar_data = eval(['all_errorbar.'  plot_obj.saved_results_structure_name]);

                    if  plot_obj.errorbar_type_to_plot == 1
                        stdev_type_name = 'over_resamples';
                        stdev_to_plot = eval(['all_errorbar_data.' result_type_name '.stdev.' stdev_type_name]);
                    elseif  plot_obj.errorbar_type_to_plot == 2
                        stdev_type_name = 'over_CVs';
                        stdev_to_plot = eval(['all_errorbar_data.' result_type_name '.stdev.' stdev_type_name]);
                        stdev_to_plot = squeeze(mean(stdev_to_plot, 1))';
                    elseif  plot_obj.errorbar_type_to_plot == 3
                        stdev_type_name = 'over_CVs_combined_over_resamples';
                        stdev_to_plot = eval(['all_errorbar_data.' result_type_name '.stdev.' stdev_type_name]);
                    elseif  plot_obj.errorbar_type_to_plot == 4
                        stdev_type_name = 'all_single_CV_vals';
                        stdev_to_plot = eval(['all_errorbar_data.' result_type_name '.stdev.' stdev_type_name]);
                        stdev_to_plot = squeeze(mean(mean(stdev_to_plot, 1), 2));
                    elseif  plot_obj.errorbar_type_to_plot == 5
                        stdev_type_name = 'all_single_CV_vals_combined';
                        stdev_to_plot = eval(['all_errorbar_data.' result_type_name '.stdev.' stdev_type_name]);
                        stdev_to_plot = squeeze(mean(stdev_to_plot, 1))';
                    elseif  plot_obj.errorbar_type_to_plot == 6
                        stdev_type_name = 'over_classes';
                        if plot_obj.result_type_to_plot < 4
                            error('Can only plot stdevs over classes for AUROC results (i.e., if plot_obj.result_type_to_plot is 4 or 5, then plot_obj.errorbar_type_to_plot must be in the range 1-6');
                        end
                        stdev_to_plot = eval(['all_errorbar_data.' result_type_name '.stdev.' stdev_type_name]);
                        if plot_obj.result_type_to_plot == 5
                            stdev_to_plot = squeeze(mean(stdev_to_plot, 1))';
                        else
                            stdev_to_plot = squeeze(mean(mean(stdev_to_plot, 1), 2));
                        end
                    end

                    if size(stdev_to_plot, 2) == 1
                        error('Can only create errorbars for results in which the classifier was trained and tested at all times (i.e., .mean_decoding_results must be a matrix');
                    end

                    if plot_obj.result_type_to_plot == 1
                        stdev_to_plot = stdev_to_plot .* 100;
                    end

                    % if only plotting only a smaller range,
                    if ~isempty(plot_obj.plot_inds)
                       stdev_to_plot = stdev_to_plot(plot_obj.plot_inds, plot_obj.plot_inds);
                    end

                end

                % for each training time, plot the results at all test times

                h = figure(plot_obj.movie_figure_number);

                for iTime = 1:size(result_to_plot, 1)

                    hold off
                    plot(the_time_interval, diag(result_to_plot), 'LineWidth', plot_obj.line_width, 'Color', [0 0 0]);
                    hold on

                    plot(the_time_interval, result_to_plot(iTime, :), 'LineWidth', plot_obj.line_width, 'Color', plot_obj.sliding_result_color);

                    % plot the errorbars if specified
                    if ~isempty(plot_obj.errorbar_file_name)
                        upper_errorbar = (diag(result_to_plot) + (plot_obj.errorbar_stdev_multiplication_factor .* diag(stdev_to_plot)))';
                        lower_errorbar = (diag(result_to_plot) - (plot_obj.errorbar_stdev_multiplication_factor .* diag(stdev_to_plot)))';

                        fill([the_time_interval fliplr(the_time_interval)],[upper_errorbar fliplr(lower_errorbar)], [0 0 0], 'EdgeColor', [0 0 0], 'EdgeAlpha', plot_obj.errorbar_edge_alpha_transparency, 'FaceAlpha', plot_obj.errorbar_alpha_transparency)

                        upper_errorbar = (result_to_plot(iTime, :) + (plot_obj.errorbar_stdev_multiplication_factor .* stdev_to_plot(iTime, :)));
                        lower_errorbar = (result_to_plot(iTime, :) - (plot_obj.errorbar_stdev_multiplication_factor .* stdev_to_plot(iTime, :)));

                        fill([the_time_interval fliplr(the_time_interval)],[upper_errorbar fliplr(lower_errorbar)], plot_obj.sliding_result_color, 'EdgeColor', plot_obj.sliding_result_color, 'EdgeAlpha', plot_obj.errorbar_edge_alpha_transparency, 'FaceAlpha', plot_obj.errorbar_alpha_transparency)
                    end

                    % plot a spot at the training time...
                    percent_below_min_val_to_plot_spot = .1;
                    spot_y_position = min_and_max_decoding_vals(1) - (percent_below_min_val_to_plot_spot .* (min_and_max_decoding_vals(2) - min_and_max_decoding_vals(1)));
                    plot(the_time_interval(iTime), spot_y_position, 'o', 'Color', plot_obj.sliding_result_color, 'MarkerFaceColor', plot_obj.sliding_result_color)

                    if exist('time_interval_obj')
                        bin_width_half_size = round(time_interval_obj.bin_width./2);
                        line([the_time_interval(iTime) - bin_width_half_size, the_time_interval(iTime) + bin_width_half_size], [spot_y_position spot_y_position], 'color', plot_obj.sliding_result_color, 'LineWidth', 2)
                    end

                    % add axis labels, lines for significant events, etc.
                    xlabel('Time (ms)', 'FontSize', plot_obj.font_size)
                    ylabel(plot_obj.decoding_result_type_name, 'FontSize', plot_obj.font_size)
                    if ~isnan(plot_obj.chance_level)
                        line(get(gca, 'XLim'), [plot_obj.chance_level plot_obj.chance_level], 'color', [0 0 0])
                    end

                    for iEvent = 1:length(plot_obj.significant_event_times)
                       line([plot_obj.significant_event_times(iEvent), plot_obj.significant_event_times(iEvent)], get(gca, 'YLim'), 'color', [0 0 0])
                    end

                    % if different titles are given for differnt time periods, plot the appropriate title
                    if ~isempty (plot_obj.movie_time_period_titles)
                        if ~isfield(plot_obj.movie_time_period_titles, 'title_start_times') ||  ~isfield(plot_obj.movie_time_period_titles, 'title_names')
                           warning('plot_obj.movie_time_period_titles.title_start_times and plot_obj.movie_time_period_titles.title_names must both be specified in order to plot particular titles at particular times - skipping plotting titles');
                        elseif length(plot_obj.movie_time_period_titles.title_start_times) ~= length(plot_obj.movie_time_period_titles.title_names)
                           warning('plot_obj.movie_time_period_titles.title_start_times and plot_obj.movie_time_period_titles.title_names must both be the same length - skipping plotting titles');
                        else
                            [junk cur_title_ind] =  min(the_time_interval(iTime) - plot_obj.movie_time_period_titles.title_start_times(find((the_time_interval(iTime) - plot_obj.movie_time_period_titles.title_start_times) >= 0)));
                            title(plot_obj.movie_time_period_titles.title_names{cur_title_ind}, 'FontSize', plot_obj.font_size);
                        end
                    end

                    if exist('bin_width_half_size')
                        axis([the_time_interval(1) - bin_width_half_size, the_time_interval(end) + bin_width_half_size, get(gca, 'YLim')])
                    end

                    if ~isempty(plot_obj.movie_save_name)
                            F = getframe(h);  % getframe(gcf);
                            mov = addframe(mov, F);
                    end

                    if plot_obj.display_movie_pause_time < 0
                        pause;  % pause until a key is pressed
                    else
                        pause(plot_obj.display_movie_pause_time);
                    end

                end  % end the for loop over all times

                if ~isempty(plot_obj.movie_save_name)
                    mov = close(mov);
                end

            end   % end if for creating the movie

        end

    end

end   % end classdef

author: buzsakilab

repo: buzcode

save_path: github-repos/MATLAB/buzsakilab-buzcode


text:
function mpc = t_case_tlmp
%T_CASE_TLMP  Single bus, 2-gen case for TLMP examples from Cong Chen
%   Please see CASEFORMAT for details on the case file format.

%   MOST
%   Copyright (c) 2022, Power Systems Engineering Research Center (PSERC)
%   by Ray Zimmerman, PSERC Cornell
%
%   This file is part of MOST.
%   Covered by the 3-clause BSD License (see LICENSE file for details).
%   See https://github.com/MATPOWER/most for more info.

%% MATPOWER Case Format : Version 2
mpc.version = '2';

%%-----  Power Flow Data  -----%%
%% system MVA base
mpc.baseMVA = 100;

%% bus data
%	bus_i	type	Pd	Qd	Gs	Bs	area	Vm	Va	baseKV	zone	Vmax	Vmin
mpc.bus = [
	1	3	0	0	0	0	1	1	0	135	1	1.05	0.95;
	2	1	0	0	0	0	1	1	0	135	1	1.05	0.95;
];

%% generator data
%	bus	Pg	Qg	Qmax	Qmin	Vg	mBase	status	Pmax	Pmin	Pc1	Pc2	Qc1min	Qc1max	Qc2min	Qc2max	ramp_agc	ramp_10	ramp_30	ramp_q	apf
mpc.gen = [
	1	450	0	50	-50	1	100	1	500	0	0	0	0	0	0	0	0	1000	1000	0	0;
	1	50	0	50	-50	1	100	1	500	0	0	0	0	0	0	0	0	1000	1000	0	0;
	2	-420	0	0	0	1	100	1	0	-450	0	0	0	0	0	0	0	1000	1000	0	0;
];

%% branch data
%	fbus	tbus	r	x	b	rateA	rateB	rateC	ratio	angle	status	angmin	angmax
mpc.branch = [
	1	2	0.005	0.01	0	0	0	3	0	0	1	-360	360;
];

%%-----  OPF Data  -----%%
%% generator cost data
%	1	startup	shutdown	n	x1	y1	...	xn	yn
%	2	startup	shutdown	n	c(n-1)	...	c0
mpc.gencost = [
	2	0	0	2	25	0;
	2	0	0	2	30	0;
	2	0	0	2	1000	0;
];

author: MATPOWER

repo: matpower

save_path: github-repos/MATLAB/MATPOWER-matpower


text:
function test_suite = test_grDilate
%TEST_GRDILATE  test suite for function grDilate
%
%   output = test_grDilate(input)
%
%   Example
%   testGrDilate
%
%   See also
%
%
% ------
% Author: David Legland
% e-mail: david.legland@grignon.inra.fr
% Created: 2011-05-18,    using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.

test_suite = functiontests(localfunctions);

function testSimpleGraph(testCase) %#ok<*DEFNU>

[nodes, edges, values] = createTestGraph01(); %#ok<ASGLU>

valDil = grDilate(edges, values);
exp = [80;80;70;70;80;50;80;40];
testCase.assertEqual(exp, valDil);

author: mattools

repo: matGeom

save_path: github-repos/MATLAB/mattools-matGeom


text:
function writestruct(filename, s)
% writestruct Store a structure to file
%
% Saves a structure object to a text file in an INI-like format.
%
% Input:
% - filename (string): Path to the file.
% - s (structure): A structure.
%

fid = fopen(filename, 'w');

writeimpl(fid, s, '');

fclose(fid);

end

function writeimpl(fid, s, prefix)

    % Extract field data
    fields = repmat(fieldnames(s), numel(s), 1);
    values = struct2cell(s);

    % Convert all numerical values to strings
    idx = cellfun(@isnumeric, values);
    values(idx) = cellfun(@num2str, values(idx), 'UniformOutput', 0);

    for i = 1:numel(fields)
        if isstruct(values{i})
            writeimpl(fid, values{i}, [prefix, fields{i}, '.']);
        else
            fprintf(fid, '%s%s=%s\n', prefix, fields{i}, values{i});
        end
    end;

end

author: votchallenge

repo: toolkit-legacy


text:
function NewCalls = SeperateLong22s_Callback(hObject, eventdata, handles, inputfile, Calls)
%% Get if clicked through menu, or using the long call network
if nargin == 3
    [trainingdata, trainingpath] = uigetfile([handles.data.settings.detectionfolder '/*.mat'],'Select Detection File','MultiSelect', 'off');
    [audioname, audiopath] = uigetfile({
        '*.wav;*.ogg;*.flac;*.UVD;*.au;*.aiff;*.aif;*.aifc;*.mp3;*.m4a;*.mp4' 'Audio File'
        '*.wav' 'WAVE'
        '*.flac' 'FLAC'
        '*.ogg' 'OGG'
        '*.UVD' 'Ultravox File'
        '*.aiff;*.aif', 'AIFF'
        '*.aifc', 'AIFC'
        '*.mp3', 'MP3 (it''s probably a bad idea to record in MP3'
        '*.m4a;*.mp4' 'MPEG-4 AAC'
        }, ['Select Corresponding Audio File for ' trainingdata], handles.data.settings.audiofolder);

    inputfile = fullfile(audiopath, audioname);
    hc = waitbar(0,'Loading File');
    Calls = loadCallfile([trainingpath trainingdata],handles);

end

audiodata = audioinfo(inputfile);
if audiodata.NumChannels > 1
    warning('Audio file contains more than one channel. Use channel 1...')
end

newBoxes = [];
newScores = [];
newPower = [];

%% First, find all the overlapping calls

% Get the oldBoxes
oldBoxes = Calls.Box;

% Pad the oldBoxes so that all of the audio is contained within the box
oldBoxes(:,1) = oldBoxes(:,1) - 0.5;
oldBoxes(:,2) = oldBoxes(:,2) - 2.0;
oldBoxes(:,3) = oldBoxes(:,3) + 1.0;
oldBoxes(:,4) = oldBoxes(:,4) + 4.0;

% Calculate overlap ratio
overlapRatio = bboxOverlapRatio(oldBoxes, oldBoxes);

g = graph(overlapRatio);

% Make new oldBoxes from the minimum and maximum start and end time of each
% overlapping box.
componentIndices = conncomp(g);
begin_time = accumarray(componentIndices', oldBoxes(:,1), [], @min);
lower_freq = accumarray(componentIndices', oldBoxes(:,2), [], @min);
end_time__ = accumarray(componentIndices', oldBoxes(:,1)+oldBoxes(:,3), [], @max);
high_freq_ = accumarray(componentIndices', oldBoxes(:,2)+oldBoxes(:,4), [], @max);

merged_scores = accumarray(componentIndices', Calls.Score, [], @mean);

call_duration = end_time__ - begin_time;
call_bandwidth = high_freq_ - lower_freq;

%% Now, extract the spectrogram from each box, and find the calls within the box by using tonality
for i=1:length(begin_time)

    % If ran through the menu
    if nargin == 3
        waitbar(i/height(Calls),hc,'Splitting Calls');
    end

    % Get the audio
    WindL=round((begin_time(i)-0.1) .* audiodata.SampleRate);
    pad = [];
    if WindL<=1
        pad=zeros(abs(WindL),1);
        WindL = 1;
    end
    WindR=round((end_time__(i)+0.1) .* audiodata.SampleRate);
    WindR = min(WindR,audiodata.TotalSamples); % Prevent WindR from being greater than total samples

    audio = audioread(inputfile,[WindL WindR]); % Take channel 1
    audio = [pad; mean(audio - mean(audio,1),2)];

    % Make the spectrogram
    windowsize = round(audiodata.SampleRate * 0.02);
    noverlap = round(audiodata.SampleRate * 0.01);
    nfft = round(audiodata.SampleRate * 0.02);

    [s, fr, ti] = spectrogram(audio,windowsize,noverlap,nfft,audiodata.SampleRate,'yaxis');

    % Get the part of the spectrogram within the frequency bandwidth
    x1 = axes2pix(length(ti),ti,call_duration(i));
    x2 = axes2pix(length(ti),ti,call_duration(i));
    lowfreq = axes2pix(length(fr),fr./1000,lower_freq(i));
    hi_freq = axes2pix(length(fr),fr./1000,high_freq_(i));
    I = abs(s(round(lowfreq:hi_freq),:));
    % Calculate the entropy
    entropy = 1 - (geomean(I,1) ./ mean(I,1));

    % Tonality of the upper region
    I2 = abs(s(round(hi_freq:min(2*hi_freq-lowfreq,size(s,1))),:));
    UpperEntropy = 1 - (geomean(I2,1) ./ mean(I2,1));
    % Use MAD to estimate mean and sd of entropy
    EntropyMedian = median(UpperEntropy);
    EntropySD = 1.4826 * median(abs(EntropyMedian - UpperEntropy));

    CallRegions = entropy > EntropyMedian + EntropySD*3;
    %CallRegions = entropy > EntropyMedian + 0.1;
    % Calls must have continuously high tonality
    radius = find(ti>0.1,1);
    CallRegions = movmean(CallRegions,radius);

    CallRegions = [0, CallRegions, 0];
    startime = find(CallRegions(1:end-1) < 0.5 & CallRegions(2:end) >= 0.5);
    stoptime = find(CallRegions(1:end-1) >= 0.5 & CallRegions(2:end) < 0.5);

    newBoxes = [newBoxes
        ti(startime)' + (WindL ./ audiodata.SampleRate),...
        repmat(lower_freq(i),length(startime),1),...
        ti(stoptime - startime)',...
        repmat(high_freq_(i)-lower_freq(i),length(startime),1)];

    newScores = [newScores; repmat(merged_scores(i),length(startime),1)];
end

%%

% Now that we have new boxes of high tonality regions, exclude the new
% boxes that don't overlap with the old boxes.
overlapRatio = bboxOverlapRatio(newBoxes, oldBoxes);
OverlapsWithOld = any(overlapRatio,2);

% Re Make Call Structure
for i=1:size(newBoxes,1)
    if nargin == 3
        waitbar(i/length(newBoxes),hc,'Remaking Structure');
    end

    if ~OverlapsWithOld; continue; end

    % Final Structure
    NewCalls(i).Box=newBoxes(i,:);
    NewCalls(i).Score=newScores(i);
    NewCalls(i).Type=categorical({'USV'});
    NewCalls(i).Accept=1;

end
    NewCalls = struct2table(NewCalls);

if nargin == 3
    [FileName,PathName] = uiputfile(fullfile(handles.data.settings.detectionfolder,trainingdata),'Save Merged Detections');
    waitbar(i/length(newBoxes),hc,'Saving...');
    Calls = NewCalls;
    save(fullfile(PathName, FileName), 'Calls', 'audiodata', '-v7.3');
    update_folders(hObject, eventdata, handles);
    close(hc);
end

author: DrCoffey

repo: DeepSqueak

save_path: github-repos/MATLAB/DrCoffey-DeepSqueak


text:
function H=MDexact(M,x0,y0,z0,x,y,z,er,mr,sigma,f)
%
% function H=MDexact(M,x0,y0,z0,x,y,z,er,mr,sigma,f)
%
% Function MDEXACT calculates the magnetic field in position (x,y,z) for a
% impulsive source M=I*Am placed in the point (x0,y0,z0). The source is
% inserted in a medium characterized by dielectric permettivity er,
% magnetic permeability mr and conductivity sigma. The temporal rule is
% exp(-i*omega*t).
%
% INPUT
%   M = M*l, impulsive value of the magnetic dipole [A*m^2]
%   x0,y0,z0 = coordinates of the dipole [m]
%   x,y,z = point where the field is calculated [m]
%   er = relative dialectric permettivity
%   mr = relative magnetic permeability
%   sigma = conductivity [S/m]
%   f = frequency [Hz]
%
% OUTPUT
%   H(1:3,1) = Hx, Hy and Hz with dipole directed along x
%   H(1:3,2) = Hx, Hy and Hz with dipole directed along y
%   H(1:3,3) = Hx, Hy and Hz with dipole directed along z

% change the reference system (index 0 refers to the system in which the
% dipole is placed in the origin): the script was originally written for a
% dipole placed in (0,0,0).
x=x-x0;
y=y-y0;
z=z-z0;

% constant
v0=2.997925e8;
mu0=pi*4e-7;
eps0=1/(v0^2*mu0);
eps=eps0*er;
mu=mu0*mr;
omega=2*pi*f;
gammaq=j*omega*mu.*(sigma+j*omega*eps);
gamma=sqrt(gammaq);

H=zeros(3,3);

% dipole along x
rho=sqrt(y^2+z^2);
r=sqrt(rho^2+x^2);
if rho<1e-10,
    cosphi=1;
    sinphi=0;
else
    cosphi=z/rho;
    sinphi=-y/rho;
end
costheta=x/r;
sintheta=sqrt(1-costheta^2);

Hr_exact=-j*(M/(2*pi*omega*mu*r^3))*(1+gamma*r).*exp(-gamma*r)*costheta;
Htheta_exact=-j*(M/(4*pi*omega*mu*r^3))*(1+gamma*r+gamma.^2*r^2).*exp(-gamma*r)*sintheta;
Hrho_exact=Hr_exact*sintheta+Htheta_exact*costheta;

Hx_exact=Hr_exact*costheta-Htheta_exact*sintheta;
Hz_exact=Hrho_exact*cosphi;
Hy_exact=-Hrho_exact*sinphi;

H(1,1)=Hx_exact;
H(2,1)=Hy_exact;
H(3,1)=Hz_exact;

% dipole along y
rho=sqrt(x^2+z^2);
r=sqrt(rho^2+y^2);
if rho<1e-10,
    cosphi=1;
    sinphi=0;
else
    cosphi=x/rho;
    sinphi=z/rho;
end
costheta=y/r;
sintheta=sqrt(1-costheta^2);

Hr_exact=(M/(2*pi*r^3))*(1+gamma*r).*exp(-gamma*r)*costheta;
Htheta_exact=(M/(4*pi*r^3))*(1+gamma*r+gamma.^2*r^2).*exp(-gamma*r)*sintheta;
Hrho_exact=Hr_exact*sintheta+Htheta_exact*costheta;

Hy_exact=Hr_exact*costheta-Htheta_exact*sintheta;
Hx_exact=Hrho_exact*cosphi;
Hz_exact=Hrho_exact*sinphi;

H(1,2)=Hx_exact;
H(2,2)=Hy_exact;
H(3,2)=Hz_exact;

% dipole along z
rho=sqrt(x^2+y^2);
r=sqrt(rho^2+z^2);
if rho<1e-10,
    cosphi=1;
    sinphi=0;
else
    cosphi= x/rho;
    sinphi= y/rho;
end
costheta=z/r;
sintheta=sqrt(1-costheta^2);

Hr_exact=(M/(2*pi*r^3))*(1+gamma*r).*exp(-gamma*r)*costheta;
Htheta_exact=(M/(4*pi*r^3))*(1+gamma*r+gamma.^2*r^2).*exp(-gamma*r)*sintheta;
Hrho_exact=Hr_exact*sintheta+Htheta_exact*costheta;

Hz_exact=Hr_exact*costheta-Htheta_exact*sintheta;
Hx_exact=Hrho_exact*cosphi;
Hy_exact=Hrho_exact*sinphi;

H(1,3)=Hx_exact;
H(2,3)=Hy_exact;
H(3,3)=Hz_exact;

% switch to exp(-i*omega*t)
H = conj(H);

author: Sable

repo: mcbench-benchmarks


text:
function sphere_grid_test06 ( )

%*****************************************************************************80
%
%% SPHERE_GRID_TEST06 tests SPHERE_LL_LINES.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    08 October 2012
%
%  Author:
%
%    John Burkardt
%
  lat_num = 3;
  long_num = 4;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'SPHERE_GRID_TEST06\n' );
  fprintf ( 1, '  SPHERE_LL_LINES computes gridlines\n' );
  fprintf ( 1, '  on a sphere in 3D.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of latitudes is  %d\n', lat_num );
  fprintf ( 1, '  Number of longitudes is %d\n', long_num );

  line_num = sphere_ll_line_num ( lat_num, long_num );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Number of line segments is %d\n', line_num );

  line = sphere_ll_lines ( lat_num, long_num, line_num );

  i4mat_transpose_print ( 2, line_num, line, '  Grid line vertices:' );

  return
end

author: johannesgerer

repo: jburkardt-m


text:
function out = load_volcanoes(~, filename, vname)
    % loads volcano information from a file
    % by default, this loads volcao.mat, which contains
    % a Table called GVPHoloceneVolcanoes
    % This table has several fields that describe the volcano.
    % Most importantly:
    %  VolcanoName - name of volcano
    %  LastKnownEruption - year in which eruption occurred (numeric, not a datetime)
    %  Latitude, Longitude - lat & lon in degrees
    %  Elevationm - elevation in meters
    %  Depth - negative elevation in km

    if ~exist('filename','var')
        filename = 'features/volcano.mat';
    end

    if ~exist('vname','var')
        vname = 'data';
    end

    out = [];

    try
        XX = load(filename, vname);
    catch ME
        error('unable to load volcanoes. Expected variable "%s" in file "%s"',...
        vname, filename)
    end

    if isfield(XX,vname)
        out = XX.(vname);
    end

    if ~isfield(out,'Depth')
        out.Depth= -(out.Elevationm ./ 1000);
    end

    fn = fieldnames(out);
    if ~all(ismember({'VolcanoName','Latitude','Longitude','Elevationm','LastKnownEruption'}, fn))
        warning('loaded volcano file, but it doesn''t appear to have all the required fields');
    end
    out.Name=out.VolcanoName;

end

author: CelsoReyes


text:
function RS_DF(actualdata, gridDF, Bu, forecasts_dist, ind_feval, ind_deval, hstep, el, bootMC)
%% Density Forecast Evaluation

% Number of Observations in Forecasted Sample
T = size(actualdata,2);
%
% % Create Vector of Dates for Plotting
% date_vec = date;
% startdate = char(date_vec(end-numt+1,:));
% enddate   = char(date_vec(end,:));
% [pdate,stringdate] = bear.genpdate(names,0,frequency,startdate,enddate);

%% Rossi-Sekhposyan (2016) Tests for Correct Specification of Forecast Densities

%% Construct Density Probabilities Corresponding to Grid

densitygrid = zeros(T,length(gridDF)-1);
draws = Bu;

for i=1:T

    for j = 1:length(gridDF)-1

        obj = forecasts_dist(:,ind_feval(1),i);

        logic = sum((gridDF(j)<=obj) & (obj<gridDF(j+1)));
        num = sum(logic);

        if isempty(num)
            num = 0;
        end

        densitygrid(i,j) = (num/draws)*100;

    end

end

 %% Construct Midpoints of Bins in Grid
gridDF_mid = zeros(1,length(gridDF)-1);
for j = 1:length(gridDF)-1
    gridDF_mid(1,j) = (gridDF(j+1)+gridDF(j))/2;
end

%% Obtain PIT Histogram and RS Test-Statistic
result = bear.RS_DF_Test(densitygrid,actualdata(ind_deval(1),:)',gridDF_mid',hstep,el,bootMC);

%% Plots
%if pref.plot
% Plot Actual Data vs Median Forecasts

% PIT Histogram
subplot(2,2,3);
hs=result.histogram;
bin=result.bin;
m=result.m;
bar(0:1/bin:1,bin*hs./m,'histc');
title('PIT Histogram','Fontsize',8,'Fontname','Palatino Linotype');
xlim([0 1]);
box on;
set(gca,'Fontname','Palatino Linotype');

% Test Statistic
subplot(2,2,4);
rvec=result.rvec;
ecdf=result.ecdf;
plot(rvec,ecdf,'LineWidth',2)
hold on
if hstep == 1
    plot(rvec,rvec,'r','LineWidth',2);
    hold on
    plot(rvec,rvec + 1.34/sqrt(m),'r:','LineWidth',2);
    hold on
    plot(rvec,rvec - 1.34/sqrt(m),'r:','LineWidth',2);
end
hold off
xlim([0 1])
ylim([0 1])
grid on
xlabel('Test rejects correct calibration if test line is outside critical value line.','fontsize',7,'Fontname','Palatino Linotype');
ylabel('Test Statistic','fontsize',8,'Fontname','Palatino Linotype')
%legend('Empirical','Theoretical','5% Critical Value','Location','NorthWest');
hleg = legend('Empirical','Theoretical','5% Critical Value','Location','Best');
set(hleg,'Fontsize',8, 'Fontname','Palatino Linotype');
title('Rossi-Sekhposyan(2017) Test','Fontsize',8,'Fontname','Palatino Linotype')
box on
set(gca,'Fontname','Palatino Linotype');

%end %pref.plot

author: european-central-bank

repo: BEAR-toolbox


text:
function frame = getnext(vr)
%FRAME=GETNEXT(VR)
%  This method is a shortcut for
%    if (next(vr))
%      frame = getframe(vr);
%    else
%      frame = [];
%    end
%
%  Although this method can be more convenient than calling NEXT and GETFRAME
%  separately, there is no way to distinguish between a zero-sized frame and
%  reading past the end of the stream.
%
%  Typical usage:
%    vr = videoReader('numbers.uncompressed.avi');
%    info = getinfo(vr);
%    for i=1:info.numFrames
%      img = getnext(vr);
%      imshow(img);
%      pause(1/info.fps);
%    end
%    vr = close(vr);
%
%SEE ALSO
%  videoReader
%  videoReader/getframe
%  videoReader/next
%
%Copyright (c) 2006 Gerald Dalley
%See "MIT.txt" in the installation directory for licensing details (especially
%when using this library on GNU/Linux).

if (next(vr))
  frame = getframe(vr);
else
  frame = [];
end


text:
%% prepDataForLBP.m
% Loads prepared datasets (TRN, VAL, TST) and prepares data for LBP
% features computation.
%
% 12-07-11 Michal Uricar

clc;
close all; clearvars;

%% Timestamp

fprintf(1,'Started on %s\n\n', datestr(now));

%% add paths

addpath('./Functions/');
addpath('../../matlab_toolbox/mex/');

%% Load data

overwrite = false;
% overwrite = true;   % re-generate images and gt mat files

% load options
load('./results/options.mat');
S = options.S;
% verbose output
options.verbose = true;

M = size(options.components, 2);

% load config
load('./MAT/config.mat');

%% Load all images & save annotations

% TRN
images_fname = ['./MAT/Images_nImages-' config.nImages '.mat'];
gt_fname = ['./MAT/GT_nImages-' config.nImages '.mat'];
if (~exist(images_fname, 'file') || overwrite)
    load('./MAT/TRN.mat');
    bad_idx_TRN = prepLBPconf(config, options, 'TRN', annotation_struct, images_fname, gt_fname);
else
    fprintf('TRN: Array of images already created. Loading %s...\n', images_fname);
    load(images_fname);
end;

% VAL
images_fname = ['./MAT/ImagesVal_nImages-' config.nImages '.mat'];
gt_fname = ['./MAT/GTVal_nImages-' config.nImages '.mat'];
if (~exist(images_fname, 'file') || overwrite)
    load('./MAT/VAL.mat');
    bad_idx_VAL = prepLBPconf(config, options, 'VAL', annotation_struct, images_fname, gt_fname);
else
    fprintf('VAL: Array of images already created. Loading %s...\n', images_fname);
    load(images_fname);
end;

% TST
images_fname = ['./MAT/ImagesTst_nImages-' config.nImages '.mat'];
gt_fname = ['./MAT/GTTst_nImages-' config.nImages '.mat'];
if (~exist(images_fname, 'file') || overwrite)
    load('./MAT/TST.mat');
    bad_idx_TST = prepLBPconf(config, options, 'TST', annotation_struct, images_fname, gt_fname);
else
    fprintf('TST: Array of images already created. Loading %s...\n', images_fname);
    load(images_fname);
end;

if (exist('bad_idx_TRN', 'var') && exist('bad_idx_VAL', 'var') && exist('bad_idx_TST', 'var'))
    save('./MAT/bad_idx.mat', 'bad_idx_TRN', 'bad_idx_VAL', 'bad_idx_TST');
end;

%% Prepare data for LBP

fprintf('Preparing data for LBP...\n');

lbpconfig = cell(1, M);

% get psi matrix for each component
for j = 1 : M
    siz = [S(4, j) - S(2, j) + 1; S(3, j) - S(1, j) + 1];
    offset = S(1:2, j);
    coors = zeros(2, siz(1)*siz(2));
    for cor_i = 1 : siz(2)
        coors(1, ((cor_i-1)*siz(1)+1):cor_i*siz(1)) = (cor_i - 1 + offset(1));
        coors(2, ((cor_i-1)*siz(1)+1):cor_i*siz(1)) = (offset(2):(siz(1)-1+offset(2)));
    end;

    card_si = size(coors, 2);

    height = round(options.components(2, j));
    width = round(options.components(1, j));
    lbpconfig{j}.winSize = [height; width];
    lbpconfig{j}.hop = config.heightOfPyramid;
    lbpconfig{j}.wins = uint32([ones(1, card_si); coors; zeros(1, card_si)] - repmat([0; floor(width/2); floor(height/2); 0], 1, card_si));
end;

lbpconfig_fname = ['./MAT/lbpconfig_nImages-' config.nImages '_hop-' num2str(config.heightOfPyramid) '.mat'];
fprintf('Saving data %s ... ', lbpconfig_fname);
save(lbpconfig_fname, 'lbpconfig');
% save(lbpconfig_fname, 'Images', 'gt', 'lbpconfig', 'options', 'S');
fprintf('Done.\n');

author: uricamic

repo: flandmark

save_path: github-repos/MATLAB/uricamic-flandmark